From e01c004cc6edaf1c671d91dc303ec1e302373d95 Mon Sep 17 00:00:00 2001 From: Tianon Gravi Date: Tue, 2 Jun 2026 13:39:10 -0700 Subject: [PATCH] Remove dependency on `github.com/opencontainers/runtime-tools` The direct use was two lines in `internal/cri/nri/nri_api_linux.go` -- constructing a `generate.Generator{Config: spec}` solely to satisfy the `nrigen.UnderlyingGenerator` interface defined in `containerd/nri`. Since that interface already exists, we just need an implementation. Add `spec_generator.go` in the same package, implementing `UnderlyingGenerator` directly on `*rspec.Spec` with no external dependencies beyond `runtime-spec`. Assisted-By: "claude my eyes right out" Signed-off-by: Tianon Gravi --- go.mod | 5 +- go.sum | 16 +- internal/cri/nri/nri_api_linux.go | 4 +- internal/cri/nri/spec_generator_linux.go | 372 ++++ .../moby/sys/capability/CHANGELOG.md | 124 -- vendor/github.com/moby/sys/capability/LICENSE | 25 - .../github.com/moby/sys/capability/README.md | 13 - .../moby/sys/capability/capability.go | 176 -- .../moby/sys/capability/capability_linux.go | 591 ------ .../moby/sys/capability/capability_noop.go | 46 - vendor/github.com/moby/sys/capability/enum.go | 330 --- .../moby/sys/capability/enum_gen.go | 137 -- .../moby/sys/capability/syscall_linux.go | 161 -- .../opencontainers/runtime-tools/LICENSE | 191 -- .../runtime-tools/generate/config.go | 194 -- .../runtime-tools/generate/generate.go | 1881 ----------------- .../runtime-tools/generate/seccomp/consts.go | 7 - .../generate/seccomp/parse_action.go | 137 -- .../generate/seccomp/parse_architecture.go | 55 - .../generate/seccomp/parse_arguments.go | 73 - .../generate/seccomp/parse_remove.go | 52 - .../generate/seccomp/seccomp_default.go | 603 ------ .../generate/seccomp/seccomp_default_linux.go | 16 - .../seccomp/seccomp_default_unsupported.go | 15 - .../generate/seccomp/syscall_compare.go | 124 -- .../validate/capabilities/lastcap.go | 16 - .../validate/capabilities/validate.go | 45 - vendor/modules.txt | 13 +- .../internal/ociedit/spec_editor.go | 247 +++ .../pkg/cdi/container-edits.go | 120 +- .../container-device-interface/pkg/cdi/oci.go | 36 +- .../pkg/cdi/spec-dirs.go | 4 + .../pkg/parser/parser.go | 3 + 33 files changed, 724 insertions(+), 5108 deletions(-) create mode 100644 internal/cri/nri/spec_generator_linux.go delete mode 100644 vendor/github.com/moby/sys/capability/CHANGELOG.md delete mode 100644 vendor/github.com/moby/sys/capability/LICENSE delete mode 100644 vendor/github.com/moby/sys/capability/README.md delete mode 100644 vendor/github.com/moby/sys/capability/capability.go delete mode 100644 vendor/github.com/moby/sys/capability/capability_linux.go delete mode 100644 vendor/github.com/moby/sys/capability/capability_noop.go delete mode 100644 vendor/github.com/moby/sys/capability/enum.go delete mode 100644 vendor/github.com/moby/sys/capability/enum_gen.go delete mode 100644 vendor/github.com/moby/sys/capability/syscall_linux.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/LICENSE delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/config.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/generate.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/validate/capabilities/lastcap.go delete mode 100644 vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go create mode 100644 vendor/tags.cncf.io/container-device-interface/internal/ociedit/spec_editor.go diff --git a/go.mod b/go.mod index 9851fddc56..7c7734df78 100644 --- a/go.mod +++ b/go.mod @@ -55,7 +55,6 @@ require ( github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 github.com/opencontainers/runtime-spec v1.3.0 - github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 github.com/opencontainers/selinux v1.15.1 github.com/pelletier/go-toml/v2 v2.4.3 github.com/prometheus/client_golang v1.24.0 @@ -90,7 +89,7 @@ require ( k8s.io/klog/v2 v2.140.0 k8s.io/streaming v0.36.3 k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 - tags.cncf.io/container-device-interface v1.1.0 + tags.cncf.io/container-device-interface v1.1.1-0.20260720132747-49ac08dcf160 ) require ( @@ -118,14 +117,12 @@ require ( github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/knqyf263/go-plugin v0.9.0 // indirect github.com/mdlayher/socket v0.6.0 // indirect github.com/miekg/pkcs11 v1.1.2 // indirect github.com/mistifyio/go-zfs/v3 v3.0.1 // indirect github.com/moby/spdystream v0.5.1 // indirect - github.com/moby/sys/capability v0.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect diff --git a/go.sum b/go.sum index 2cf156d38f..f700d2eb6d 100644 --- a/go.sum +++ b/go.sum @@ -24,8 +24,6 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24 github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/brianvoe/gofakeit/v7 v7.12.1 h1:df1tiI4SL1dR5Ix4D/r6a3a+nXBJ/OBGU5jEKRBmmqg= github.com/brianvoe/gofakeit/v7 v7.12.1/go.mod h1:QXuPeBw164PJCzCUZVmgpgHJ3Llj49jSLVkKPMtxtxA= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= @@ -194,10 +192,6 @@ github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 h1:pRhl55Yx1eC7BZ1N+BBWwn github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0/go.mod h1:XKMd7iuf/RGPSMJ/U4HP0zS2Z9Fh8Ps9a+6X26m/tmI= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/intel/goresctrl v0.13.0 h1:5fhKjNq4V5MYDFHa//6M6x0jP6Iq5EXwZc6/eYxdEtQ= github.com/intel/goresctrl v0.13.0/go.mod h1:KFHS91JGOmeeuEog+nTQcsGjLC81nRqdsdhcqf69fjU= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= @@ -346,12 +340,6 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= -github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= @@ -579,7 +567,7 @@ sigs.k8s.io/structured-merge-diff/v6 v6.3.3 h1:u08YRbVUi59ri4YD6cg0UqNM4Dimn0sIl sigs.k8s.io/structured-merge-diff/v6 v6.3.3/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= -tags.cncf.io/container-device-interface v1.1.0 h1:RnxNhxF1JOu6CJUVpetTYvrXHdxw9j9jFYgZpI+anSY= -tags.cncf.io/container-device-interface v1.1.0/go.mod h1:76Oj0Yqp9FwTx/pySDc8Bxjpg+VqXfDb50cKAXVJ34Q= +tags.cncf.io/container-device-interface v1.1.1-0.20260720132747-49ac08dcf160 h1:ZusVLZsIsAXuoxfJNIv3bL2Io7pKQyx0zaMbgRTz+X8= +tags.cncf.io/container-device-interface v1.1.1-0.20260720132747-49ac08dcf160/go.mod h1:Q9xVPbYCl0qhaLAPYQ7Dra+Bd51FsEUaGQb12MXxVb4= tags.cncf.io/container-device-interface/specs-go v1.1.0 h1:QRZVeAceQM+zTZe12eyfuJuuzp524EKYwhmvLd+h+yQ= tags.cncf.io/container-device-interface/specs-go v1.1.0/go.mod h1:u86hoFWqnh3hWz3esofRFKbI261bUlvUfLKGrDhJkgQ= diff --git a/internal/cri/nri/nri_api_linux.go b/internal/cri/nri/nri_api_linux.go index b1f6eacead..f28ec0ef7d 100644 --- a/internal/cri/nri/nri_api_linux.go +++ b/internal/cri/nri/nri_api_linux.go @@ -40,7 +40,6 @@ import ( "github.com/containerd/log" "github.com/containerd/typeurl/v2" runtimespec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/opencontainers/runtime-tools/generate" cri "k8s.io/cri-api/pkg/apis/runtime/v1" "github.com/containerd/containerd/v2/internal/nri" @@ -368,8 +367,7 @@ func (a *API) WithContainerAdjustment() containerd.NewContainerOpts { return nil } - sgen := generate.Generator{Config: spec} - ngen := nrigen.SpecGenerator(&sgen, generatorOptions...) + ngen := nrigen.SpecGenerator(newSpecGen(spec), generatorOptions...) err = ngen.Adjust(adjust) if err != nil { diff --git a/internal/cri/nri/spec_generator_linux.go b/internal/cri/nri/spec_generator_linux.go new file mode 100644 index 0000000000..f708ca7375 --- /dev/null +++ b/internal/cri/nri/spec_generator_linux.go @@ -0,0 +1,372 @@ +/* + Copyright The containerd Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package nri + +import ( + "fmt" + "strings" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// specGen implements nrigen.UnderlyingGenerator directly on an *rspec.Spec, +// removing the need to import github.com/opencontainers/runtime-tools/generate. +type specGen struct { + spec *rspec.Spec +} + +func newSpecGen(spec *rspec.Spec) *specGen { + return &specGen{spec: spec} +} + +func (g *specGen) Spec() *rspec.Spec { + return g.spec +} + +func (g *specGen) initConfig() { + if g.spec == nil { + g.spec = &rspec.Spec{} + } +} + +func (g *specGen) initProcess() { + g.initConfig() + if g.spec.Process == nil { + g.spec.Process = &rspec.Process{} + } +} + +func (g *specGen) initLinux() { + g.initConfig() + if g.spec.Linux == nil { + g.spec.Linux = &rspec.Linux{} + } +} + +func (g *specGen) initLinuxResources() { + g.initLinux() + if g.spec.Linux.Resources == nil { + g.spec.Linux.Resources = &rspec.LinuxResources{} + } +} + +func (g *specGen) initLinuxCPU() { + g.initLinuxResources() + if g.spec.Linux.Resources.CPU == nil { + g.spec.Linux.Resources.CPU = &rspec.LinuxCPU{} + } +} + +func (g *specGen) initLinuxMemory() { + g.initLinuxResources() + if g.spec.Linux.Resources.Memory == nil { + g.spec.Linux.Resources.Memory = &rspec.LinuxMemory{} + } +} + +func (g *specGen) initHooks() { + g.initConfig() + if g.spec.Hooks == nil { + g.spec.Hooks = &rspec.Hooks{} + } +} + +func (g *specGen) initAnnotations() { + g.initConfig() + if g.spec.Annotations == nil { + g.spec.Annotations = map[string]string{} + } +} + +func (g *specGen) initSysctl() { + g.initLinux() + if g.spec.Linux.Sysctl == nil { + g.spec.Linux.Sysctl = map[string]string{} + } +} + +func (g *specGen) AddAnnotation(key, value string) { + g.initAnnotations() + g.spec.Annotations[key] = value +} + +func (g *specGen) RemoveAnnotation(key string) { + if g.spec != nil && g.spec.Annotations != nil { + delete(g.spec.Annotations, key) + } +} + +func (g *specGen) AddDevice(device rspec.LinuxDevice) { + g.initLinux() + for i, d := range g.spec.Linux.Devices { + if d.Path == device.Path { + g.spec.Linux.Devices[i] = device + return + } + } + g.spec.Linux.Devices = append(g.spec.Linux.Devices, device) +} + +func (g *specGen) RemoveDevice(path string) { + if g.spec == nil || g.spec.Linux == nil { + return + } + for i, d := range g.spec.Linux.Devices { + if d.Path == path { + g.spec.Linux.Devices = append(g.spec.Linux.Devices[:i], g.spec.Linux.Devices[i+1:]...) + return + } + } +} + +func (g *specGen) AddOrReplaceLinuxNamespace(ns string, path string) error { + nsType, err := namespaceType(ns) + if err != nil { + return err + } + g.initLinux() + for i, n := range g.spec.Linux.Namespaces { + if n.Type == nsType { + g.spec.Linux.Namespaces[i].Path = path + return nil + } + } + g.spec.Linux.Namespaces = append(g.spec.Linux.Namespaces, rspec.LinuxNamespace{Type: nsType, Path: path}) + return nil +} + +func (g *specGen) RemoveLinuxNamespace(ns string) error { + nsType, err := namespaceType(ns) + if err != nil { + return err + } + if g.spec == nil || g.spec.Linux == nil { + return nil + } + for i, n := range g.spec.Linux.Namespaces { + if n.Type == nsType { + g.spec.Linux.Namespaces = append(g.spec.Linux.Namespaces[:i], g.spec.Linux.Namespaces[i+1:]...) + return nil + } + } + return nil +} + +func namespaceType(ns string) (rspec.LinuxNamespaceType, error) { + switch ns { + case "network": + return rspec.NetworkNamespace, nil + case "pid": + return rspec.PIDNamespace, nil + case "mount": + return rspec.MountNamespace, nil + case "ipc": + return rspec.IPCNamespace, nil + case "uts": + return rspec.UTSNamespace, nil + case "user": + return rspec.UserNamespace, nil + case "cgroup": + return rspec.CgroupNamespace, nil + case "time": + return rspec.TimeNamespace, nil + default: + return "", fmt.Errorf("unrecognized namespace %q", ns) + } +} + +func (g *specGen) AddPreStartHook(hook rspec.Hook) { + g.initHooks() + g.spec.Hooks.Prestart = append(g.spec.Hooks.Prestart, hook) //nolint:staticcheck +} + +func (g *specGen) AddPostStartHook(hook rspec.Hook) { + g.initHooks() + g.spec.Hooks.Poststart = append(g.spec.Hooks.Poststart, hook) +} + +func (g *specGen) AddPostStopHook(hook rspec.Hook) { + g.initHooks() + g.spec.Hooks.Poststop = append(g.spec.Hooks.Poststop, hook) +} + +func (g *specGen) AddProcessEnv(name, value string) { + if name == "" { + return + } + g.initProcess() + prefix := name + "=" + for i, e := range g.spec.Process.Env { + if strings.HasPrefix(e, prefix) { + g.spec.Process.Env[i] = prefix + value + return + } + } + g.spec.Process.Env = append(g.spec.Process.Env, prefix+value) +} + +func (g *specGen) ClearProcessEnv() { + if g.spec == nil || g.spec.Process == nil { + return + } + g.spec.Process.Env = []string{} +} + +func (g *specGen) SetProcessArgs(args []string) { + g.initProcess() + g.spec.Process.Args = args +} + +func (g *specGen) SetProcessOOMScoreAdj(adj int) { + g.initProcess() + g.spec.Process.OOMScoreAdj = &adj +} + +func (g *specGen) AddMount(mnt rspec.Mount) { + g.initConfig() + g.spec.Mounts = append(g.spec.Mounts, mnt) +} + +func (g *specGen) RemoveMount(dest string) { + if g.spec == nil { + return + } + for i, m := range g.spec.Mounts { + if m.Destination == dest { + g.spec.Mounts = append(g.spec.Mounts[:i], g.spec.Mounts[i+1:]...) + return + } + } +} + +func (g *specGen) ClearMounts() { + if g.spec == nil { + return + } + g.spec.Mounts = []rspec.Mount{} +} + +func (g *specGen) Mounts() []rspec.Mount { + if g.spec == nil { + return nil + } + return g.spec.Mounts +} + +func (g *specGen) AddLinuxSysctl(key, value string) { + g.initSysctl() + g.spec.Linux.Sysctl[key] = value +} + +func (g *specGen) RemoveLinuxSysctl(key string) { + if g.spec == nil || g.spec.Linux == nil || g.spec.Linux.Sysctl == nil { + return + } + delete(g.spec.Linux.Sysctl, key) +} + +func (g *specGen) SetLinuxCgroupsPath(path string) { + g.initLinux() + g.spec.Linux.CgroupsPath = path +} + +func (g *specGen) SetLinuxRootPropagation(rp string) error { + switch rp { + case "", "private", "rprivate", "slave", "rslave", "shared", "rshared", "unbindable", "runbindable": + default: + return fmt.Errorf("rootfs-propagation %q must be empty or one of (r)private|(r)slave|(r)shared|(r)unbindable", rp) + } + g.initLinux() + g.spec.Linux.RootfsPropagation = rp + return nil +} + +func (g *specGen) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + g.initLinuxResources() + g.spec.Linux.Resources.Devices = append(g.spec.Linux.Resources.Devices, rspec.LinuxDeviceCgroup{ + Allow: allow, + Type: devType, + Major: major, + Minor: minor, + Access: access, + }) +} + +func (g *specGen) AddLinuxResourcesHugepageLimit(pageSize string, limit uint64) { + g.initLinuxResources() + for i, h := range g.spec.Linux.Resources.HugepageLimits { + if h.Pagesize == pageSize { + g.spec.Linux.Resources.HugepageLimits[i].Limit = limit + return + } + } + g.spec.Linux.Resources.HugepageLimits = append(g.spec.Linux.Resources.HugepageLimits, + rspec.LinuxHugepageLimit{Pagesize: pageSize, Limit: limit}) +} + +func (g *specGen) AddLinuxResourcesUnified(key, val string) { + g.initLinuxResources() + if g.spec.Linux.Resources.Unified == nil { + g.spec.Linux.Resources.Unified = map[string]string{} + } + g.spec.Linux.Resources.Unified[key] = val +} + +func (g *specGen) SetLinuxResourcesCPUShares(shares uint64) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.Shares = &shares +} + +func (g *specGen) SetLinuxResourcesCPUQuota(quota int64) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.Quota = "a +} + +func (g *specGen) SetLinuxResourcesCPUPeriod(period uint64) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.Period = &period +} + +func (g *specGen) SetLinuxResourcesCPURealtimeRuntime(time int64) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.RealtimeRuntime = &time +} + +func (g *specGen) SetLinuxResourcesCPURealtimePeriod(period uint64) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.RealtimePeriod = &period +} + +func (g *specGen) SetLinuxResourcesCPUCpus(cpus string) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.Cpus = cpus +} + +func (g *specGen) SetLinuxResourcesCPUMems(mems string) { + g.initLinuxCPU() + g.spec.Linux.Resources.CPU.Mems = mems +} + +func (g *specGen) SetLinuxResourcesMemoryLimit(limit int64) { + g.initLinuxMemory() + g.spec.Linux.Resources.Memory.Limit = &limit +} + +func (g *specGen) SetLinuxResourcesMemorySwap(swap int64) { + g.initLinuxMemory() + g.spec.Linux.Resources.Memory.Swap = &swap +} diff --git a/vendor/github.com/moby/sys/capability/CHANGELOG.md b/vendor/github.com/moby/sys/capability/CHANGELOG.md deleted file mode 100644 index 299b36d92a..0000000000 --- a/vendor/github.com/moby/sys/capability/CHANGELOG.md +++ /dev/null @@ -1,124 +0,0 @@ -# Changelog -This file documents all notable changes made to this project since the initial fork -from https://github.com/syndtr/gocapability/commit/42c35b4376354fd5. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [0.4.0] - 2024-11-11 - -### Added -* New separate API for ambient ([GetAmbient], [SetAmbient], [ResetAmbient]) - and bound ([GetBound], [DropBound]) capabilities, modelled after libcap. (#176) - -### Fixed -* [Apply] now returns an error if called for non-zero `pid`. Before this change, - it could silently change some capabilities of the current process, instead of - the one identified by the `pid`. (#168, #174) -* Fixed tests that change capabilities to be run in a separate process. (#173) -* Other improvements in tests. (#169, #170) - -### Changed -* Use raw syscalls (which are slightly faster). (#176) -* Most tests are now limited to testing the public API of the package. (#162) -* Simplify parsing /proc/*pid*/status, add a test case. (#162) -* Optimize the number of syscall to set ambient capabilities in Apply - by clearing them first; add a test case. (#163, #164) -* Better documentation for [Apply], [NewFile], [NewFile2], [NewPid], [NewPid2]. (#175) - -### Removed -* `.golangci.yml` and `.codespellrc` are no longer part of the package. (#158) - -## [0.3.0] - 2024-09-25 - -### Added -* Added [ListKnown] and [ListSupported] functions. (#153) -* [LastCap] is now available on non-Linux platforms (where it returns an error). (#152) - -### Changed -* [List] is now deprecated in favor of [ListKnown] and [ListSupported]. (#153) - -### Fixed -* Various documentation improvements. (#151) -* Fix "generated code" comment. (#153) - -## [0.2.0] - 2024-09-16 - -This is the first release after the move to a new home in -github.com/moby/sys/capability. - -### Fixed - * Fixed URLs in documentation to reflect the new home. - -## [0.1.1] - 2024-08-01 - -This is a maintenance release, fixing a few minor issues. - -### Fixed - * Fixed future kernel compatibility, for real this time. [#11] - * Fixed [LastCap] to be a function. [#12] - -## [0.1.0] - 2024-07-31 - -This is an initial release since the fork. - -### Breaking changes - - * The `CAP_LAST_CAP` variable is removed; users need to modify the code to - use [LastCap] to get the value. [#6] - * The code now requires Go >= 1.21. - -### Added - * `go.mod` and `go.sum` files. [#2] - * New [LastCap] function. [#6] - * Basic CI using GHA infra. [#8], [#9] - * README and CHANGELOG. [#10] - -### Fixed - * Fixed ambient capabilities error handling in [Apply]. [#3] - * Fixed future kernel compatibility. [#1] - * Fixed various linter warnings. [#4], [#7] - -### Changed - * Go build tags changed from old-style (`+build`) to new Go 1.17+ style (`go:build`). [#2] - -### Removed - * Removed support for capabilities v1 and v2. [#1] - * Removed init function so programs that use this package start faster. [#6] - * Removed `CAP_LAST_CAP` (use [LastCap] instead). [#6] - - -[Apply]: https://pkg.go.dev/github.com/moby/sys/capability#Capabilities.Apply -[DropBound]: https://pkg.go.dev/github.com/moby/sys/capability#DropBound -[GetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#GetAmbient -[GetBound]: https://pkg.go.dev/github.com/moby/sys/capability#GetBound -[LastCap]: https://pkg.go.dev/github.com/moby/sys/capability#LastCap -[ListKnown]: https://pkg.go.dev/github.com/moby/sys/capability#ListKnown -[ListSupported]: https://pkg.go.dev/github.com/moby/sys/capability#ListSupported -[List]: https://pkg.go.dev/github.com/moby/sys/capability#List -[NewFile2]: https://pkg.go.dev/github.com/moby/sys/capability#NewFile2 -[NewFile]: https://pkg.go.dev/github.com/moby/sys/capability#NewFile -[NewPid2]: https://pkg.go.dev/github.com/moby/sys/capability#NewPid2 -[NewPid]: https://pkg.go.dev/github.com/moby/sys/capability#NewPid -[ResetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#ResetAmbient -[SetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#SetAmbient - - -[0.4.0]: https://github.com/moby/sys/releases/tag/capability%2Fv0.4.0 -[0.3.0]: https://github.com/moby/sys/releases/tag/capability%2Fv0.3.0 -[0.2.0]: https://github.com/moby/sys/releases/tag/capability%2Fv0.2.0 -[0.1.1]: https://github.com/kolyshkin/capability/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/kolyshkin/capability/compare/42c35b4376354fd5...v0.1.0 - - -[#1]: https://github.com/kolyshkin/capability/pull/1 -[#2]: https://github.com/kolyshkin/capability/pull/2 -[#3]: https://github.com/kolyshkin/capability/pull/3 -[#4]: https://github.com/kolyshkin/capability/pull/4 -[#6]: https://github.com/kolyshkin/capability/pull/6 -[#7]: https://github.com/kolyshkin/capability/pull/7 -[#8]: https://github.com/kolyshkin/capability/pull/8 -[#9]: https://github.com/kolyshkin/capability/pull/9 -[#10]: https://github.com/kolyshkin/capability/pull/10 -[#11]: https://github.com/kolyshkin/capability/pull/11 -[#12]: https://github.com/kolyshkin/capability/pull/12 diff --git a/vendor/github.com/moby/sys/capability/LICENSE b/vendor/github.com/moby/sys/capability/LICENSE deleted file mode 100644 index 08adcd6ecf..0000000000 --- a/vendor/github.com/moby/sys/capability/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright 2023 The Capability Authors. -Copyright 2013 Suryandaru Triandana -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/moby/sys/capability/README.md b/vendor/github.com/moby/sys/capability/README.md deleted file mode 100644 index 84b74871aa..0000000000 --- a/vendor/github.com/moby/sys/capability/README.md +++ /dev/null @@ -1,13 +0,0 @@ -This is a fork of (apparently no longer maintained) -https://github.com/syndtr/gocapability package. It provides basic primitives to -work with [Linux capabilities][capabilities(7)]. - -For changes, see [CHANGELOG.md](./CHANGELOG.md). - -[![Go Reference](https://pkg.go.dev/badge/github.com/moby/sys/capability/capability.svg)](https://pkg.go.dev/github.com/moby/sys/capability) - -## Alternatives - - * https://pkg.go.dev/kernel.org/pub/linux/libs/security/libcap/cap - -[capabilities(7)]: https://man7.org/linux/man-pages/man7/capabilities.7.html diff --git a/vendor/github.com/moby/sys/capability/capability.go b/vendor/github.com/moby/sys/capability/capability.go deleted file mode 100644 index 11e47bed73..0000000000 --- a/vendor/github.com/moby/sys/capability/capability.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2023 The Capability Authors. -// Copyright 2013 Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package capability provides utilities for manipulating POSIX capabilities. -package capability - -type Capabilities interface { - // Get check whether a capability present in the given - // capabilities set. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. - Get(which CapType, what Cap) bool - - // Empty check whether all capability bits of the given capabilities - // set are zero. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. - Empty(which CapType) bool - - // Full check whether all capability bits of the given capabilities - // set are one. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. - Full(which CapType) bool - - // Set sets capabilities of the given capabilities sets. The - // 'which' value should be one or combination (OR'ed) of EFFECTIVE, - // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. - Set(which CapType, caps ...Cap) - - // Unset unsets capabilities of the given capabilities sets. The - // 'which' value should be one or combination (OR'ed) of EFFECTIVE, - // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. - Unset(which CapType, caps ...Cap) - - // Fill sets all bits of the given capabilities kind to one. The - // 'kind' value should be one or combination (OR'ed) of CAPS, - // BOUNDS or AMBS. - Fill(kind CapType) - - // Clear sets all bits of the given capabilities kind to zero. The - // 'kind' value should be one or combination (OR'ed) of CAPS, - // BOUNDS or AMBS. - Clear(kind CapType) - - // String return current capabilities state of the given capabilities - // set as string. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE BOUNDING or AMBIENT - StringCap(which CapType) string - - // String return current capabilities state as string. - String() string - - // Load load actual capabilities value. This will overwrite all - // outstanding changes. - Load() error - - // Apply apply the capabilities settings, so all changes made by - // [Set], [Unset], [Fill], or [Clear] will take effect. - Apply(kind CapType) error -} - -// NewPid initializes a new [Capabilities] object for given pid when -// it is nonzero, or for the current process if pid is 0. -// -// Deprecated: replace with [NewPid2] followed by optional [Capabilities.Load] -// (only if needed). For example, replace: -// -// c, err := NewPid(0) -// if err != nil { -// return err -// } -// -// with: -// -// c, err := NewPid2(0) -// if err != nil { -// return err -// } -// err = c.Load() -// if err != nil { -// return err -// } -func NewPid(pid int) (Capabilities, error) { - c, err := newPid(pid) - if err != nil { - return c, err - } - err = c.Load() - return c, err -} - -// NewPid2 initializes a new [Capabilities] object for given pid when -// it is nonzero, or for the current process if pid is 0. This -// does not load the process's current capabilities; if needed, -// call [Capabilities.Load]. -func NewPid2(pid int) (Capabilities, error) { - return newPid(pid) -} - -// NewFile initializes a new Capabilities object for given file path. -// -// Deprecated: replace with [NewFile2] followed by optional [Capabilities.Load] -// (only if needed). For example, replace: -// -// c, err := NewFile(path) -// if err != nil { -// return err -// } -// -// with: -// -// c, err := NewFile2(path) -// if err != nil { -// return err -// } -// err = c.Load() -// if err != nil { -// return err -// } -func NewFile(path string) (Capabilities, error) { - c, err := newFile(path) - if err != nil { - return c, err - } - err = c.Load() - return c, err -} - -// NewFile2 creates a new initialized [Capabilities] object for given -// file path. This does not load the process's current capabilities; -// if needed, call [Capabilities.Load]. -func NewFile2(path string) (Capabilities, error) { - return newFile(path) -} - -// LastCap returns highest valid capability of the running kernel, -// or an error if it can not be obtained. -// -// See also: [ListSupported]. -func LastCap() (Cap, error) { - return lastCap() -} - -// GetAmbient determines if a specific ambient capability is raised in the -// calling thread. -func GetAmbient(c Cap) (bool, error) { - return getAmbient(c) -} - -// SetAmbient raises or lowers specified ambient capabilities for the calling -// thread. To complete successfully, the prevailing effective capability set -// must have a raised CAP_SETPCAP. Further, to raise a specific ambient -// capability the inheritable and permitted sets of the calling thread must -// already contain the specified capability. -func SetAmbient(raise bool, caps ...Cap) error { - return setAmbient(raise, caps...) -} - -// ResetAmbient resets all of the ambient capabilities for the calling thread -// to their lowered value. -func ResetAmbient() error { - return resetAmbient() -} - -// GetBound determines if a specific bounding capability is raised in the -// calling thread. -func GetBound(c Cap) (bool, error) { - return getBound(c) -} - -// DropBound lowers the specified bounding set capability. -func DropBound(caps ...Cap) error { - return dropBound(caps...) -} diff --git a/vendor/github.com/moby/sys/capability/capability_linux.go b/vendor/github.com/moby/sys/capability/capability_linux.go deleted file mode 100644 index 234b1efb29..0000000000 --- a/vendor/github.com/moby/sys/capability/capability_linux.go +++ /dev/null @@ -1,591 +0,0 @@ -// Copyright 2023 The Capability Authors. -// Copyright 2013 Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package capability - -import ( - "bufio" - "errors" - "fmt" - "io" - "os" - "strconv" - "strings" - "sync" - "syscall" -) - -const ( - linuxCapVer1 = 0x19980330 // No longer supported. - linuxCapVer2 = 0x20071026 // No longer supported. - linuxCapVer3 = 0x20080522 -) - -var lastCap = sync.OnceValues(func() (Cap, error) { - f, err := os.Open("/proc/sys/kernel/cap_last_cap") - if err != nil { - return 0, err - } - - buf := make([]byte, 11) - l, err := f.Read(buf) - f.Close() - if err != nil { - return 0, err - } - buf = buf[:l] - - last, err := strconv.Atoi(strings.TrimSpace(string(buf))) - if err != nil { - return 0, err - } - return Cap(last), nil -}) - -func capUpperMask() uint32 { - last, err := lastCap() - if err != nil || last < 32 { - return 0 - } - return (uint32(1) << (uint(last) - 31)) - 1 -} - -func mkStringCap(c Capabilities, which CapType) (ret string) { - last, err := lastCap() - if err != nil { - return "" - } - for i, first := Cap(0), true; i <= last; i++ { - if !c.Get(which, i) { - continue - } - if first { - first = false - } else { - ret += ", " - } - ret += i.String() - } - return -} - -func mkString(c Capabilities, max CapType) (ret string) { - ret = "{" - for i := CapType(1); i <= max; i <<= 1 { - ret += " " + i.String() + "=\"" - if c.Empty(i) { - ret += "empty" - } else if c.Full(i) { - ret += "full" - } else { - ret += c.StringCap(i) - } - ret += "\"" - } - ret += " }" - return -} - -var capVersion = sync.OnceValues(func() (uint32, error) { - var hdr capHeader - err := capget(&hdr, nil) - return hdr.version, err -}) - -func newPid(pid int) (c Capabilities, retErr error) { - ver, err := capVersion() - if err != nil { - retErr = fmt.Errorf("unable to get capability version from the kernel: %w", err) - return - } - switch ver { - case linuxCapVer1, linuxCapVer2: - retErr = errors.New("old/unsupported capability version (kernel older than 2.6.26?)") - default: - // Either linuxCapVer3, or an unknown/future version (such as v4). - // In the latter case, we fall back to v3 as the latest version known - // to this package, as kernel should be backward-compatible to v3. - p := new(capsV3) - p.hdr.version = linuxCapVer3 - p.hdr.pid = int32(pid) - c = p - } - return -} - -func ignoreEINVAL(err error) error { - if errors.Is(err, syscall.EINVAL) { - err = nil - } - return err -} - -type capsV3 struct { - hdr capHeader - data [2]capData - bounds [2]uint32 - ambient [2]uint32 -} - -func (c *capsV3) Get(which CapType, what Cap) bool { - var i uint - if what > 31 { - i = uint(what) >> 5 - what %= 32 - } - - switch which { - case EFFECTIVE: - return (1< 31 { - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data[i].effective |= 1 << uint(what) - } - if which&PERMITTED != 0 { - c.data[i].permitted |= 1 << uint(what) - } - if which&INHERITABLE != 0 { - c.data[i].inheritable |= 1 << uint(what) - } - if which&BOUNDING != 0 { - c.bounds[i] |= 1 << uint(what) - } - if which&AMBIENT != 0 { - c.ambient[i] |= 1 << uint(what) - } - } -} - -func (c *capsV3) Unset(which CapType, caps ...Cap) { - for _, what := range caps { - var i uint - if what > 31 { - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data[i].effective &= ^(1 << uint(what)) - } - if which&PERMITTED != 0 { - c.data[i].permitted &= ^(1 << uint(what)) - } - if which&INHERITABLE != 0 { - c.data[i].inheritable &= ^(1 << uint(what)) - } - if which&BOUNDING != 0 { - c.bounds[i] &= ^(1 << uint(what)) - } - if which&AMBIENT != 0 { - c.ambient[i] &= ^(1 << uint(what)) - } - } -} - -func (c *capsV3) Fill(kind CapType) { - if kind&CAPS == CAPS { - c.data[0].effective = 0xffffffff - c.data[0].permitted = 0xffffffff - c.data[0].inheritable = 0 - c.data[1].effective = 0xffffffff - c.data[1].permitted = 0xffffffff - c.data[1].inheritable = 0 - } - - if kind&BOUNDS == BOUNDS { - c.bounds[0] = 0xffffffff - c.bounds[1] = 0xffffffff - } - if kind&AMBS == AMBS { - c.ambient[0] = 0xffffffff - c.ambient[1] = 0xffffffff - } -} - -func (c *capsV3) Clear(kind CapType) { - if kind&CAPS == CAPS { - c.data[0].effective = 0 - c.data[0].permitted = 0 - c.data[0].inheritable = 0 - c.data[1].effective = 0 - c.data[1].permitted = 0 - c.data[1].inheritable = 0 - } - - if kind&BOUNDS == BOUNDS { - c.bounds[0] = 0 - c.bounds[1] = 0 - } - if kind&AMBS == AMBS { - c.ambient[0] = 0 - c.ambient[1] = 0 - } -} - -func (c *capsV3) StringCap(which CapType) (ret string) { - return mkStringCap(c, which) -} - -func (c *capsV3) String() (ret string) { - return mkString(c, BOUNDING) -} - -func (c *capsV3) Load() (err error) { - err = capget(&c.hdr, &c.data[0]) - if err != nil { - return - } - - path := "/proc/self/status" - if c.hdr.pid != 0 { - path = fmt.Sprintf("/proc/%d/status", c.hdr.pid) - } - - f, err := os.Open(path) - if err != nil { - return - } - b := bufio.NewReader(f) - for { - line, e := b.ReadString('\n') - if e != nil { - if e != io.EOF { - err = e - } - break - } - if val, ok := strings.CutPrefix(line, "CapBnd:\t"); ok { - _, err = fmt.Sscanf(val, "%08x%08x", &c.bounds[1], &c.bounds[0]) - if err != nil { - break - } - continue - } - if val, ok := strings.CutPrefix(line, "CapAmb:\t"); ok { - _, err = fmt.Sscanf(val, "%08x%08x", &c.ambient[1], &c.ambient[0]) - if err != nil { - break - } - continue - } - } - f.Close() - - return -} - -func (c *capsV3) Apply(kind CapType) error { - if c.hdr.pid != 0 { - return errors.New("unable to modify capabilities of another process") - } - last, err := LastCap() - if err != nil { - return err - } - if kind&BOUNDS == BOUNDS { - var data [2]capData - err = capget(&c.hdr, &data[0]) - if err != nil { - return err - } - if (1< 0, nil -} - -func setAmbient(raise bool, caps ...Cap) error { - op := pr_CAP_AMBIENT_RAISE - if !raise { - op = pr_CAP_AMBIENT_LOWER - } - for _, val := range caps { - err := prctl(pr_CAP_AMBIENT, op, uintptr(val)) - if err != nil { - return err - } - } - return nil -} - -func resetAmbient() error { - return prctl(pr_CAP_AMBIENT, pr_CAP_AMBIENT_CLEAR_ALL, 0) -} - -func getBound(c Cap) (bool, error) { - res, err := prctlRetInt(syscall.PR_CAPBSET_READ, uintptr(c), 0) - if err != nil { - return false, err - } - return res > 0, nil -} - -func dropBound(caps ...Cap) error { - for _, val := range caps { - err := prctl(syscall.PR_CAPBSET_DROP, uintptr(val), 0) - if err != nil { - return err - } - } - return nil -} - -func newFile(path string) (c Capabilities, err error) { - c = &capsFile{path: path} - return -} - -type capsFile struct { - path string - data vfscapData -} - -func (c *capsFile) Get(which CapType, what Cap) bool { - var i uint - if what > 31 { - if c.data.version == 1 { - return false - } - i = uint(what) >> 5 - what %= 32 - } - - switch which { - case EFFECTIVE: - return (1< 31 { - if c.data.version == 1 { - continue - } - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data.effective[i] |= 1 << uint(what) - } - if which&PERMITTED != 0 { - c.data.data[i].permitted |= 1 << uint(what) - } - if which&INHERITABLE != 0 { - c.data.data[i].inheritable |= 1 << uint(what) - } - } -} - -func (c *capsFile) Unset(which CapType, caps ...Cap) { - for _, what := range caps { - var i uint - if what > 31 { - if c.data.version == 1 { - continue - } - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data.effective[i] &= ^(1 << uint(what)) - } - if which&PERMITTED != 0 { - c.data.data[i].permitted &= ^(1 << uint(what)) - } - if which&INHERITABLE != 0 { - c.data.data[i].inheritable &= ^(1 << uint(what)) - } - } -} - -func (c *capsFile) Fill(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective[0] = 0xffffffff - c.data.data[0].permitted = 0xffffffff - c.data.data[0].inheritable = 0 - if c.data.version == 2 { - c.data.effective[1] = 0xffffffff - c.data.data[1].permitted = 0xffffffff - c.data.data[1].inheritable = 0 - } - } -} - -func (c *capsFile) Clear(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective[0] = 0 - c.data.data[0].permitted = 0 - c.data.data[0].inheritable = 0 - if c.data.version == 2 { - c.data.effective[1] = 0 - c.data.data[1].permitted = 0 - c.data.data[1].inheritable = 0 - } - } -} - -func (c *capsFile) StringCap(which CapType) (ret string) { - return mkStringCap(c, which) -} - -func (c *capsFile) String() (ret string) { - return mkString(c, INHERITABLE) -} - -func (c *capsFile) Load() (err error) { - return getVfsCap(c.path, &c.data) -} - -func (c *capsFile) Apply(kind CapType) (err error) { - if kind&CAPS == CAPS { - return setVfsCap(c.path, &c.data) - } - return -} diff --git a/vendor/github.com/moby/sys/capability/capability_noop.go b/vendor/github.com/moby/sys/capability/capability_noop.go deleted file mode 100644 index b766e444f3..0000000000 --- a/vendor/github.com/moby/sys/capability/capability_noop.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2023 The Capability Authors. -// Copyright 2013 Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !linux - -package capability - -import "errors" - -var errNotSup = errors.New("not supported") - -func newPid(_ int) (Capabilities, error) { - return nil, errNotSup -} - -func newFile(_ string) (Capabilities, error) { - return nil, errNotSup -} - -func lastCap() (Cap, error) { - return -1, errNotSup -} - -func getAmbient(_ Cap) (bool, error) { - return false, errNotSup -} - -func setAmbient(_ bool, _ ...Cap) error { - return errNotSup -} - -func resetAmbient() error { - return errNotSup -} - -func getBound(_ Cap) (bool, error) { - return false, errNotSup -} - -func dropBound(_ ...Cap) error { - return errNotSup -} diff --git a/vendor/github.com/moby/sys/capability/enum.go b/vendor/github.com/moby/sys/capability/enum.go deleted file mode 100644 index f88593310e..0000000000 --- a/vendor/github.com/moby/sys/capability/enum.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2024 The Capability Authors. -// Copyright 2013 Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package capability - -import "slices" - -type CapType uint - -func (c CapType) String() string { - switch c { - case EFFECTIVE: - return "effective" - case PERMITTED: - return "permitted" - case INHERITABLE: - return "inheritable" - case BOUNDING: - return "bounding" - case CAPS: - return "caps" - case AMBIENT: - return "ambient" - } - return "unknown" -} - -const ( - EFFECTIVE CapType = 1 << iota - PERMITTED - INHERITABLE - BOUNDING - AMBIENT - - CAPS = EFFECTIVE | PERMITTED | INHERITABLE - BOUNDS = BOUNDING - AMBS = AMBIENT -) - -//go:generate go run enumgen/gen.go -type Cap int - -// POSIX-draft defined capabilities and Linux extensions. -// -// Defined in https://github.com/torvalds/linux/blob/master/include/uapi/linux/capability.h -const ( - // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this - // overrides the restriction of changing file ownership and group - // ownership. - CAP_CHOWN = Cap(0) - - // Override all DAC access, including ACL execute access if - // [_POSIX_ACL] is defined. Excluding DAC access covered by - // CAP_LINUX_IMMUTABLE. - CAP_DAC_OVERRIDE = Cap(1) - - // Overrides all DAC restrictions regarding read and search on files - // and directories, including ACL restrictions if [_POSIX_ACL] is - // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. - CAP_DAC_READ_SEARCH = Cap(2) - - // Overrides all restrictions about allowed operations on files, where - // file owner ID must be equal to the user ID, except where CAP_FSETID - // is applicable. It doesn't override MAC and DAC restrictions. - CAP_FOWNER = Cap(3) - - // Overrides the following restrictions that the effective user ID - // shall match the file owner ID when setting the S_ISUID and S_ISGID - // bits on that file; that the effective group ID (or one of the - // supplementary group IDs) shall match the file owner ID when setting - // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are - // cleared on successful return from chown(2) (not implemented). - CAP_FSETID = Cap(4) - - // Overrides the restriction that the real or effective user ID of a - // process sending a signal must match the real or effective user ID - // of the process receiving the signal. - CAP_KILL = Cap(5) - - // Allows setgid(2) manipulation - // Allows setgroups(2) - // Allows forged gids on socket credentials passing. - CAP_SETGID = Cap(6) - - // Allows set*uid(2) manipulation (including fsuid). - // Allows forged pids on socket credentials passing. - CAP_SETUID = Cap(7) - - // Linux-specific capabilities - - // Without VFS support for capabilities: - // Transfer any capability in your permitted set to any pid, - // remove any capability in your permitted set from any pid - // With VFS support for capabilities (neither of above, but) - // Add any capability from current's capability bounding set - // to the current process' inheritable set - // Allow taking bits out of capability bounding set - // Allow modification of the securebits for a process - CAP_SETPCAP = Cap(8) - - // Allow modification of S_IMMUTABLE and S_APPEND file attributes - CAP_LINUX_IMMUTABLE = Cap(9) - - // Allows binding to TCP/UDP sockets below 1024 - // Allows binding to ATM VCIs below 32 - CAP_NET_BIND_SERVICE = Cap(10) - - // Allow broadcasting, listen to multicast - CAP_NET_BROADCAST = Cap(11) - - // Allow interface configuration - // Allow administration of IP firewall, masquerading and accounting - // Allow setting debug option on sockets - // Allow modification of routing tables - // Allow setting arbitrary process / process group ownership on - // sockets - // Allow binding to any address for transparent proxying (also via NET_RAW) - // Allow setting TOS (type of service) - // Allow setting promiscuous mode - // Allow clearing driver statistics - // Allow multicasting - // Allow read/write of device-specific registers - // Allow activation of ATM control sockets - CAP_NET_ADMIN = Cap(12) - - // Allow use of RAW sockets - // Allow use of PACKET sockets - // Allow binding to any address for transparent proxying (also via NET_ADMIN) - CAP_NET_RAW = Cap(13) - - // Allow locking of shared memory segments - // Allow mlock and mlockall (which doesn't really have anything to do - // with IPC) - CAP_IPC_LOCK = Cap(14) - - // Override IPC ownership checks - CAP_IPC_OWNER = Cap(15) - - // Insert and remove kernel modules - modify kernel without limit - CAP_SYS_MODULE = Cap(16) - - // Allow ioperm/iopl access - // Allow sending USB messages to any device via /proc/bus/usb - CAP_SYS_RAWIO = Cap(17) - - // Allow use of chroot() - CAP_SYS_CHROOT = Cap(18) - - // Allow ptrace() of any process - CAP_SYS_PTRACE = Cap(19) - - // Allow configuration of process accounting - CAP_SYS_PACCT = Cap(20) - - // Allow configuration of the secure attention key - // Allow administration of the random device - // Allow examination and configuration of disk quotas - // Allow setting the domainname - // Allow setting the hostname - // Allow calling bdflush() - // Allow mount() and umount(), setting up new smb connection - // Allow some autofs root ioctls - // Allow nfsservctl - // Allow VM86_REQUEST_IRQ - // Allow to read/write pci config on alpha - // Allow irix_prctl on mips (setstacksize) - // Allow flushing all cache on m68k (sys_cacheflush) - // Allow removing semaphores - // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores - // and shared memory - // Allow locking/unlocking of shared memory segment - // Allow turning swap on/off - // Allow forged pids on socket credentials passing - // Allow setting readahead and flushing buffers on block devices - // Allow setting geometry in floppy driver - // Allow turning DMA on/off in xd driver - // Allow administration of md devices (mostly the above, but some - // extra ioctls) - // Allow tuning the ide driver - // Allow access to the nvram device - // Allow administration of apm_bios, serial and bttv (TV) device - // Allow manufacturer commands in isdn CAPI support driver - // Allow reading non-standardized portions of pci configuration space - // Allow DDI debug ioctl on sbpcd driver - // Allow setting up serial ports - // Allow sending raw qic-117 commands - // Allow enabling/disabling tagged queuing on SCSI controllers and sending - // arbitrary SCSI commands - // Allow setting encryption key on loopback filesystem - // Allow setting zone reclaim policy - // Allow everything under CAP_BPF and CAP_PERFMON for backward compatibility - CAP_SYS_ADMIN = Cap(21) - - // Allow use of reboot() - CAP_SYS_BOOT = Cap(22) - - // Allow raising priority and setting priority on other (different - // UID) processes - // Allow use of FIFO and round-robin (realtime) scheduling on own - // processes and setting the scheduling algorithm used by another - // process. - // Allow setting cpu affinity on other processes - CAP_SYS_NICE = Cap(23) - - // Override resource limits. Set resource limits. - // Override quota limits. - // Override reserved space on ext2 filesystem - // Modify data journaling mode on ext3 filesystem (uses journaling - // resources) - // NOTE: ext2 honors fsuid when checking for resource overrides, so - // you can override using fsuid too - // Override size restrictions on IPC message queues - // Allow more than 64hz interrupts from the real-time clock - // Override max number of consoles on console allocation - // Override max number of keymaps - // Control memory reclaim behavior - CAP_SYS_RESOURCE = Cap(24) - - // Allow manipulation of system clock - // Allow irix_stime on mips - // Allow setting the real-time clock - CAP_SYS_TIME = Cap(25) - - // Allow configuration of tty devices - // Allow vhangup() of tty - CAP_SYS_TTY_CONFIG = Cap(26) - - // Allow the privileged aspects of mknod() - CAP_MKNOD = Cap(27) - - // Allow taking of leases on files - CAP_LEASE = Cap(28) - - CAP_AUDIT_WRITE = Cap(29) - CAP_AUDIT_CONTROL = Cap(30) - CAP_SETFCAP = Cap(31) - - // Override MAC access. - // The base kernel enforces no MAC policy. - // An LSM may enforce a MAC policy, and if it does and it chooses - // to implement capability based overrides of that policy, this is - // the capability it should use to do so. - CAP_MAC_OVERRIDE = Cap(32) - - // Allow MAC configuration or state changes. - // The base kernel requires no MAC configuration. - // An LSM may enforce a MAC policy, and if it does and it chooses - // to implement capability based checks on modifications to that - // policy or the data required to maintain it, this is the - // capability it should use to do so. - CAP_MAC_ADMIN = Cap(33) - - // Allow configuring the kernel's syslog (printk behaviour) - CAP_SYSLOG = Cap(34) - - // Allow triggering something that will wake the system - CAP_WAKE_ALARM = Cap(35) - - // Allow preventing system suspends - CAP_BLOCK_SUSPEND = Cap(36) - - // Allow reading the audit log via multicast netlink socket - CAP_AUDIT_READ = Cap(37) - - // Allow system performance and observability privileged operations - // using perf_events, i915_perf and other kernel subsystems - CAP_PERFMON = Cap(38) - - // CAP_BPF allows the following BPF operations: - // - Creating all types of BPF maps - // - Advanced verifier features - // - Indirect variable access - // - Bounded loops - // - BPF to BPF function calls - // - Scalar precision tracking - // - Larger complexity limits - // - Dead code elimination - // - And potentially other features - // - Loading BPF Type Format (BTF) data - // - Retrieve xlated and JITed code of BPF programs - // - Use bpf_spin_lock() helper - // - // CAP_PERFMON relaxes the verifier checks further: - // - BPF progs can use of pointer-to-integer conversions - // - speculation attack hardening measures are bypassed - // - bpf_probe_read to read arbitrary kernel memory is allowed - // - bpf_trace_printk to print kernel memory is allowed - // - // CAP_SYS_ADMIN is required to use bpf_probe_write_user. - // - // CAP_SYS_ADMIN is required to iterate system wide loaded - // programs, maps, links, BTFs and convert their IDs to file descriptors. - // - // CAP_PERFMON and CAP_BPF are required to load tracing programs. - // CAP_NET_ADMIN and CAP_BPF are required to load networking programs. - CAP_BPF = Cap(39) - - // Allow checkpoint/restore related operations. - // Introduced in kernel 5.9 - CAP_CHECKPOINT_RESTORE = Cap(40) -) - -// List returns the list of all capabilities known to the package. -// -// Deprecated: use [ListKnown] or [ListSupported] instead. -func List() []Cap { - return ListKnown() -} - -// ListKnown returns the list of all capabilities known to the package. -func ListKnown() []Cap { - return list() -} - -// ListSupported returns the list of all capabilities known to the package, -// except those that are not supported by the currently running Linux kernel. -func ListSupported() ([]Cap, error) { - last, err := LastCap() - if err != nil { - return nil, err - } - return slices.DeleteFunc(list(), func(c Cap) bool { - // Remove caps not supported by the kernel. - return c > last - }), nil -} diff --git a/vendor/github.com/moby/sys/capability/enum_gen.go b/vendor/github.com/moby/sys/capability/enum_gen.go deleted file mode 100644 index f72cd43a6e..0000000000 --- a/vendor/github.com/moby/sys/capability/enum_gen.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by go generate; DO NOT EDIT. - -package capability - -func (c Cap) String() string { - switch c { - case CAP_CHOWN: - return "chown" - case CAP_DAC_OVERRIDE: - return "dac_override" - case CAP_DAC_READ_SEARCH: - return "dac_read_search" - case CAP_FOWNER: - return "fowner" - case CAP_FSETID: - return "fsetid" - case CAP_KILL: - return "kill" - case CAP_SETGID: - return "setgid" - case CAP_SETUID: - return "setuid" - case CAP_SETPCAP: - return "setpcap" - case CAP_LINUX_IMMUTABLE: - return "linux_immutable" - case CAP_NET_BIND_SERVICE: - return "net_bind_service" - case CAP_NET_BROADCAST: - return "net_broadcast" - case CAP_NET_ADMIN: - return "net_admin" - case CAP_NET_RAW: - return "net_raw" - case CAP_IPC_LOCK: - return "ipc_lock" - case CAP_IPC_OWNER: - return "ipc_owner" - case CAP_SYS_MODULE: - return "sys_module" - case CAP_SYS_RAWIO: - return "sys_rawio" - case CAP_SYS_CHROOT: - return "sys_chroot" - case CAP_SYS_PTRACE: - return "sys_ptrace" - case CAP_SYS_PACCT: - return "sys_pacct" - case CAP_SYS_ADMIN: - return "sys_admin" - case CAP_SYS_BOOT: - return "sys_boot" - case CAP_SYS_NICE: - return "sys_nice" - case CAP_SYS_RESOURCE: - return "sys_resource" - case CAP_SYS_TIME: - return "sys_time" - case CAP_SYS_TTY_CONFIG: - return "sys_tty_config" - case CAP_MKNOD: - return "mknod" - case CAP_LEASE: - return "lease" - case CAP_AUDIT_WRITE: - return "audit_write" - case CAP_AUDIT_CONTROL: - return "audit_control" - case CAP_SETFCAP: - return "setfcap" - case CAP_MAC_OVERRIDE: - return "mac_override" - case CAP_MAC_ADMIN: - return "mac_admin" - case CAP_SYSLOG: - return "syslog" - case CAP_WAKE_ALARM: - return "wake_alarm" - case CAP_BLOCK_SUSPEND: - return "block_suspend" - case CAP_AUDIT_READ: - return "audit_read" - case CAP_PERFMON: - return "perfmon" - case CAP_BPF: - return "bpf" - case CAP_CHECKPOINT_RESTORE: - return "checkpoint_restore" - } - return "unknown" -} - -func list() []Cap { - return []Cap{ - CAP_CHOWN, - CAP_DAC_OVERRIDE, - CAP_DAC_READ_SEARCH, - CAP_FOWNER, - CAP_FSETID, - CAP_KILL, - CAP_SETGID, - CAP_SETUID, - CAP_SETPCAP, - CAP_LINUX_IMMUTABLE, - CAP_NET_BIND_SERVICE, - CAP_NET_BROADCAST, - CAP_NET_ADMIN, - CAP_NET_RAW, - CAP_IPC_LOCK, - CAP_IPC_OWNER, - CAP_SYS_MODULE, - CAP_SYS_RAWIO, - CAP_SYS_CHROOT, - CAP_SYS_PTRACE, - CAP_SYS_PACCT, - CAP_SYS_ADMIN, - CAP_SYS_BOOT, - CAP_SYS_NICE, - CAP_SYS_RESOURCE, - CAP_SYS_TIME, - CAP_SYS_TTY_CONFIG, - CAP_MKNOD, - CAP_LEASE, - CAP_AUDIT_WRITE, - CAP_AUDIT_CONTROL, - CAP_SETFCAP, - CAP_MAC_OVERRIDE, - CAP_MAC_ADMIN, - CAP_SYSLOG, - CAP_WAKE_ALARM, - CAP_BLOCK_SUSPEND, - CAP_AUDIT_READ, - CAP_PERFMON, - CAP_BPF, - CAP_CHECKPOINT_RESTORE, - } -} diff --git a/vendor/github.com/moby/sys/capability/syscall_linux.go b/vendor/github.com/moby/sys/capability/syscall_linux.go deleted file mode 100644 index 2d8faa85ff..0000000000 --- a/vendor/github.com/moby/sys/capability/syscall_linux.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2024 The Capability Authors. -// Copyright 2013 Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package capability - -import ( - "syscall" - "unsafe" -) - -type capHeader struct { - version uint32 - pid int32 -} - -type capData struct { - effective uint32 - permitted uint32 - inheritable uint32 -} - -func capget(hdr *capHeader, data *capData) (err error) { - _, _, e1 := syscall.RawSyscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) - if e1 != 0 { - err = e1 - } - return -} - -func capset(hdr *capHeader, data *capData) (err error) { - _, _, e1 := syscall.RawSyscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) - if e1 != 0 { - err = e1 - } - return -} - -// not yet in syscall -const ( - pr_CAP_AMBIENT = 47 - pr_CAP_AMBIENT_IS_SET = uintptr(1) - pr_CAP_AMBIENT_RAISE = uintptr(2) - pr_CAP_AMBIENT_LOWER = uintptr(3) - pr_CAP_AMBIENT_CLEAR_ALL = uintptr(4) -) - -func prctl(option int, arg2, arg3 uintptr) (err error) { - _, _, e1 := syscall.RawSyscall(syscall.SYS_PRCTL, uintptr(option), arg2, arg3) - if e1 != 0 { - err = e1 - } - return -} - -func prctlRetInt(option int, arg2, arg3 uintptr) (int, error) { - ret, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, uintptr(option), arg2, arg3) - if err != 0 { - return 0, err - } - return int(ret), nil -} - -const ( - vfsXattrName = "security.capability" - - vfsCapVerMask = 0xff000000 - vfsCapVer1 = 0x01000000 - vfsCapVer2 = 0x02000000 - - vfsCapFlagMask = ^vfsCapVerMask - vfsCapFlageffective = 0x000001 - - vfscapDataSizeV1 = 4 * (1 + 2*1) - vfscapDataSizeV2 = 4 * (1 + 2*2) -) - -type vfscapData struct { - magic uint32 - data [2]struct { - permitted uint32 - inheritable uint32 - } - effective [2]uint32 - version int8 -} - -var _vfsXattrName *byte - -func init() { - _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName) -} - -func getVfsCap(path string, dest *vfscapData) (err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := syscall.RawSyscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0) - if e1 != 0 { - if e1 == syscall.ENODATA { - dest.version = 2 - return - } - err = e1 - } - switch dest.magic & vfsCapVerMask { - case vfsCapVer1: - dest.version = 1 - if r0 != vfscapDataSizeV1 { - return syscall.EINVAL - } - dest.data[1].permitted = 0 - dest.data[1].inheritable = 0 - case vfsCapVer2: - dest.version = 2 - if r0 != vfscapDataSizeV2 { - return syscall.EINVAL - } - default: - return syscall.EINVAL - } - if dest.magic&vfsCapFlageffective != 0 { - dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable - dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable - } else { - dest.effective[0] = 0 - dest.effective[1] = 0 - } - return -} - -func setVfsCap(path string, data *vfscapData) (err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(path) - if err != nil { - return - } - var size uintptr - if data.version == 1 { - data.magic = vfsCapVer1 - size = vfscapDataSizeV1 - } else if data.version == 2 { - data.magic = vfsCapVer2 - if data.effective[0] != 0 || data.effective[1] != 0 { - data.magic |= vfsCapFlageffective - } - size = vfscapDataSizeV2 - } else { - return syscall.EINVAL - } - _, _, e1 := syscall.RawSyscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0) - if e1 != 0 { - err = e1 - } - return -} diff --git a/vendor/github.com/opencontainers/runtime-tools/LICENSE b/vendor/github.com/opencontainers/runtime-tools/LICENSE deleted file mode 100644 index bdc403653e..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 The Linux Foundation. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/config.go b/vendor/github.com/opencontainers/runtime-tools/generate/config.go deleted file mode 100644 index 48f281d286..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/config.go +++ /dev/null @@ -1,194 +0,0 @@ -package generate - -import ( - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -func (g *Generator) initConfig() { - if g.Config == nil { - g.Config = &rspec.Spec{} - } -} - -func (g *Generator) initConfigProcess() { - g.initConfig() - if g.Config.Process == nil { - g.Config.Process = &rspec.Process{} - } -} - -func (g *Generator) initConfigProcessConsoleSize() { - g.initConfigProcess() - if g.Config.Process.ConsoleSize == nil { - g.Config.Process.ConsoleSize = &rspec.Box{} - } -} - -func (g *Generator) initConfigProcessCapabilities() { - g.initConfigProcess() - if g.Config.Process.Capabilities == nil { - g.Config.Process.Capabilities = &rspec.LinuxCapabilities{} - } -} - -func (g *Generator) initConfigRoot() { - g.initConfig() - if g.Config.Root == nil { - g.Config.Root = &rspec.Root{} - } -} - -func (g *Generator) initConfigAnnotations() { - g.initConfig() - if g.Config.Annotations == nil { - g.Config.Annotations = make(map[string]string) - } -} - -func (g *Generator) initConfigHooks() { - g.initConfig() - if g.Config.Hooks == nil { - g.Config.Hooks = &rspec.Hooks{} - } -} - -func (g *Generator) initConfigLinux() { - g.initConfig() - if g.Config.Linux == nil { - g.Config.Linux = &rspec.Linux{} - } -} - -func (g *Generator) initConfigLinuxIntelRdt() { - g.initConfigLinux() - if g.Config.Linux.IntelRdt == nil { - g.Config.Linux.IntelRdt = &rspec.LinuxIntelRdt{} - } -} - -func (g *Generator) initConfigLinuxSysctl() { - g.initConfigLinux() - if g.Config.Linux.Sysctl == nil { - g.Config.Linux.Sysctl = make(map[string]string) - } -} - -func (g *Generator) initConfigLinuxSeccomp() { - g.initConfigLinux() - if g.Config.Linux.Seccomp == nil { - g.Config.Linux.Seccomp = &rspec.LinuxSeccomp{} - } -} - -func (g *Generator) initConfigLinuxResources() { - g.initConfigLinux() - if g.Config.Linux.Resources == nil { - g.Config.Linux.Resources = &rspec.LinuxResources{} - } -} - -func (g *Generator) initConfigLinuxResourcesBlockIO() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.BlockIO == nil { - g.Config.Linux.Resources.BlockIO = &rspec.LinuxBlockIO{} - } -} - -// InitConfigLinuxResourcesCPU initializes CPU of Linux resources -func (g *Generator) InitConfigLinuxResourcesCPU() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.CPU == nil { - g.Config.Linux.Resources.CPU = &rspec.LinuxCPU{} - } -} - -func (g *Generator) initConfigLinuxResourcesMemory() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.Memory == nil { - g.Config.Linux.Resources.Memory = &rspec.LinuxMemory{} - } -} - -func (g *Generator) initConfigLinuxResourcesNetwork() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.Network == nil { - g.Config.Linux.Resources.Network = &rspec.LinuxNetwork{} - } -} - -func (g *Generator) initConfigLinuxResourcesPids() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.Pids == nil { - g.Config.Linux.Resources.Pids = &rspec.LinuxPids{} - } -} - -func (g *Generator) initConfigLinuxResourcesUnified() { - g.initConfigLinuxResources() - if g.Config.Linux.Resources.Unified == nil { - g.Config.Linux.Resources.Unified = map[string]string{} - } -} - -func (g *Generator) initConfigSolaris() { - g.initConfig() - if g.Config.Solaris == nil { - g.Config.Solaris = &rspec.Solaris{} - } -} - -func (g *Generator) initConfigSolarisCappedCPU() { - g.initConfigSolaris() - if g.Config.Solaris.CappedCPU == nil { - g.Config.Solaris.CappedCPU = &rspec.SolarisCappedCPU{} - } -} - -func (g *Generator) initConfigSolarisCappedMemory() { - g.initConfigSolaris() - if g.Config.Solaris.CappedMemory == nil { - g.Config.Solaris.CappedMemory = &rspec.SolarisCappedMemory{} - } -} - -func (g *Generator) initConfigWindows() { - g.initConfig() - if g.Config.Windows == nil { - g.Config.Windows = &rspec.Windows{} - } -} - -func (g *Generator) initConfigWindowsNetwork() { - g.initConfigWindows() - if g.Config.Windows.Network == nil { - g.Config.Windows.Network = &rspec.WindowsNetwork{} - } -} - -func (g *Generator) initConfigWindowsHyperV() { - g.initConfigWindows() - if g.Config.Windows.HyperV == nil { - g.Config.Windows.HyperV = &rspec.WindowsHyperV{} - } -} - -func (g *Generator) initConfigWindowsResources() { - g.initConfigWindows() - if g.Config.Windows.Resources == nil { - g.Config.Windows.Resources = &rspec.WindowsResources{} - } -} - -func (g *Generator) initConfigWindowsResourcesMemory() { - g.initConfigWindowsResources() - if g.Config.Windows.Resources.Memory == nil { - g.Config.Windows.Resources.Memory = &rspec.WindowsMemoryResources{} - } -} - -func (g *Generator) initConfigVM() { - g.initConfig() - if g.Config.VM == nil { - g.Config.VM = &rspec.VM{} - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go deleted file mode 100644 index 44c199e147..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go +++ /dev/null @@ -1,1881 +0,0 @@ -// Package generate implements functions generating container config files. -package generate - -import ( - "encoding/json" - "fmt" - "io" - "os" - "slices" - "strings" - - "github.com/moby/sys/capability" - rspec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/opencontainers/runtime-tools/generate/seccomp" - capsCheck "github.com/opencontainers/runtime-tools/validate/capabilities" -) - -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] - } -) - -const ( - // UnlimitedPidsLimit can be passed to SetLinuxResourcesPidsLimit to - // request unlimited PIDs. - UnlimitedPidsLimit int64 = -1 -) - -// Generator represents a generator for a container config. -type Generator struct { - Config *rspec.Spec - HostSpecific bool - // This is used to keep a cache of the ENVs added to improve - // performance when adding a huge number of ENV variables - envMap map[string]int -} - -// ExportOptions have toggles for exporting only certain parts of the specification -type ExportOptions struct { - Seccomp bool // seccomp toggles if only seccomp should be exported -} - -// New creates a configuration Generator with the default -// configuration for the target operating system. -func New(os string) (generator Generator, err error) { - if os != "linux" && os != "solaris" && os != "windows" && os != "freebsd" { - return generator, fmt.Errorf("no defaults configured for %s", os) - } - - config := rspec.Spec{ - Version: rspec.Version, - Hostname: "mrsdalloway", - } - - if os == "windows" { - config.Process = &rspec.Process{ - Args: []string{ - "cmd", - }, - Cwd: `C:\`, - } - config.Windows = &rspec.Windows{} - } else { - config.Root = &rspec.Root{ - Path: "rootfs", - Readonly: false, - } - config.Process = &rspec.Process{ - Terminal: false, - Args: []string{ - "sh", - }, - } - } - - if os == "linux" || os == "solaris" || os == "freebsd" { - config.Process.User = rspec.User{} - config.Process.Env = []string{ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM=xterm", - } - config.Process.Cwd = "/" - config.Process.Rlimits = []rspec.POSIXRlimit{ - { - Type: "RLIMIT_NOFILE", - Hard: uint64(1024), - Soft: uint64(1024), - }, - } - } - - switch os { - case "linux": - config.Process.Capabilities = &rspec.LinuxCapabilities{ - Bounding: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", - }, - Permitted: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", - }, - Inheritable: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", - }, - Effective: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", - }, - Ambient: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", - }, - } - config.Mounts = []rspec.Mount{ - { - Destination: "/proc", - Type: "proc", - Source: "proc", - Options: []string{"nosuid", "noexec", "nodev"}, - }, - { - Destination: "/dev", - Type: "tmpfs", - Source: "tmpfs", - Options: []string{"nosuid", "strictatime", "mode=755", "size=65536k"}, - }, - { - Destination: "/dev/pts", - Type: "devpts", - Source: "devpts", - Options: []string{"nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"}, - }, - { - Destination: "/dev/shm", - Type: "tmpfs", - Source: "shm", - Options: []string{"nosuid", "noexec", "nodev", "mode=1777", "size=65536k"}, - }, - { - Destination: "/dev/mqueue", - Type: "mqueue", - Source: "mqueue", - Options: []string{"nosuid", "noexec", "nodev"}, - }, - { - Destination: "/sys", - Type: "sysfs", - Source: "sysfs", - Options: []string{"nosuid", "noexec", "nodev", "ro"}, - }, - } - config.Linux = &rspec.Linux{ - Resources: &rspec.LinuxResources{ - Devices: []rspec.LinuxDeviceCgroup{ - { - Allow: false, - Access: "rwm", - }, - }, - }, - Namespaces: []rspec.LinuxNamespace{ - { - Type: "pid", - }, - { - Type: "network", - }, - { - Type: "ipc", - }, - { - Type: "uts", - }, - { - Type: "mount", - }, - }, - Seccomp: seccomp.DefaultProfile(&config), - } - case "freebsd": - config.Mounts = []rspec.Mount{ - { - Destination: "/dev", - Type: "devfs", - Source: "devfs", - Options: []string{"ruleset=4"}, - }, - { - Destination: "/dev/fd", - Type: "fdescfs", - Source: "fdesc", - Options: []string{}, - }, - } - } - - envCache := map[string]int{} - if config.Process != nil { - envCache = createEnvCacheMap(config.Process.Env) - } - - return Generator{Config: &config, envMap: envCache}, nil -} - -// NewFromSpec creates a configuration Generator from a given -// configuration. -func NewFromSpec(config *rspec.Spec) Generator { - envCache := map[string]int{} - if config != nil && config.Process != nil { - envCache = createEnvCacheMap(config.Process.Env) - } - - return Generator{ - Config: config, - envMap: envCache, - } -} - -// NewFromFile loads the template specified in a file into a -// configuration Generator. -func NewFromFile(path string) (Generator, error) { - cf, err := os.Open(path) - if err != nil { - if os.IsNotExist(err) { - return Generator{}, fmt.Errorf("template configuration at %s not found", path) - } - return Generator{}, err - } - defer cf.Close() - - return NewFromTemplate(cf) -} - -// NewFromTemplate loads the template from io.Reader into a -// configuration Generator. -func NewFromTemplate(r io.Reader) (Generator, error) { - var config rspec.Spec - if err := json.NewDecoder(r).Decode(&config); err != nil { - return Generator{}, err - } - - envCache := map[string]int{} - if config.Process != nil { - envCache = createEnvCacheMap(config.Process.Env) - } - - return Generator{ - Config: &config, - envMap: envCache, - }, nil -} - -// createEnvCacheMap creates a hash map with the ENV variables given by the config -func createEnvCacheMap(env []string) map[string]int { - envMap := make(map[string]int, len(env)) - for i, val := range env { - envMap[val] = i - } - return envMap -} - -// SetSpec sets the configuration in the Generator g. -// -// Deprecated: Replace with: -// -// Use generator.Config = config -func (g *Generator) SetSpec(config *rspec.Spec) { - g.Config = config -} - -// Spec gets the configuration from the Generator g. -// -// Deprecated: Replace with generator.Config. -func (g *Generator) Spec() *rspec.Spec { - return g.Config -} - -// Save writes the configuration into w. -func (g *Generator) Save(w io.Writer, exportOpts ExportOptions) (err error) { - var data []byte - - if g.Config.Linux != nil { - buf, err := json.Marshal(g.Config.Linux) - if err != nil { - return err - } - if string(buf) == "{}" { - g.Config.Linux = nil - } - } - - if exportOpts.Seccomp { - data, err = json.MarshalIndent(g.Config.Linux.Seccomp, "", "\t") - } else { - data, err = json.MarshalIndent(g.Config, "", "\t") - } - if err != nil { - return err - } - - _, err = w.Write(data) - if err != nil { - return err - } - - return nil -} - -// SaveToFile writes the configuration into a file. -func (g *Generator) SaveToFile(path string, exportOpts ExportOptions) error { - f, err := os.Create(path) - if err != nil { - return err - } - defer f.Close() - return g.Save(f, exportOpts) -} - -// SetVersion sets g.Config.Version. -func (g *Generator) SetVersion(version string) { - g.initConfig() - g.Config.Version = version -} - -// SetRootPath sets g.Config.Root.Path. -func (g *Generator) SetRootPath(path string) { - g.initConfigRoot() - g.Config.Root.Path = path -} - -// SetRootReadonly sets g.Config.Root.Readonly. -func (g *Generator) SetRootReadonly(b bool) { - g.initConfigRoot() - g.Config.Root.Readonly = b -} - -// SetHostname sets g.Config.Hostname. -func (g *Generator) SetHostname(s string) { - g.initConfig() - g.Config.Hostname = s -} - -// SetOCIVersion sets g.Config.Version. -func (g *Generator) SetOCIVersion(s string) { - g.initConfig() - g.Config.Version = s -} - -// ClearAnnotations clears g.Config.Annotations. -func (g *Generator) ClearAnnotations() { - if g.Config == nil { - return - } - g.Config.Annotations = make(map[string]string) -} - -// AddAnnotation adds an annotation into g.Config.Annotations. -func (g *Generator) AddAnnotation(key, value string) { - g.initConfigAnnotations() - g.Config.Annotations[key] = value -} - -// RemoveAnnotation remove an annotation from g.Config.Annotations. -func (g *Generator) RemoveAnnotation(key string) { - if g.Config == nil || g.Config.Annotations == nil { - return - } - delete(g.Config.Annotations, key) -} - -// RemoveHostname removes g.Config.Hostname, setting it to an empty string. -func (g *Generator) RemoveHostname() { - if g.Config == nil { - return - } - g.Config.Hostname = "" -} - -// SetProcessConsoleSize sets g.Config.Process.ConsoleSize. -func (g *Generator) SetProcessConsoleSize(width, height uint) { - g.initConfigProcessConsoleSize() - g.Config.Process.ConsoleSize.Width = width - g.Config.Process.ConsoleSize.Height = height -} - -// SetProcessUID sets g.Config.Process.User.UID. -func (g *Generator) SetProcessUID(uid uint32) { - g.initConfigProcess() - g.Config.Process.User.UID = uid -} - -// SetProcessUsername sets g.Config.Process.User.Username. -func (g *Generator) SetProcessUsername(username string) { - g.initConfigProcess() - g.Config.Process.User.Username = username -} - -// SetProcessUmask sets g.Config.Process.User.Umask. -func (g *Generator) SetProcessUmask(umask uint32) { - g.initConfigProcess() - u := umask - g.Config.Process.User.Umask = &u -} - -// SetProcessGID sets g.Config.Process.User.GID. -func (g *Generator) SetProcessGID(gid uint32) { - g.initConfigProcess() - g.Config.Process.User.GID = gid -} - -// SetProcessCwd sets g.Config.Process.Cwd. -func (g *Generator) SetProcessCwd(cwd string) { - g.initConfigProcess() - g.Config.Process.Cwd = cwd -} - -// SetProcessNoNewPrivileges sets g.Config.Process.NoNewPrivileges. -func (g *Generator) SetProcessNoNewPrivileges(b bool) { - g.initConfigProcess() - g.Config.Process.NoNewPrivileges = b -} - -// SetProcessTerminal sets g.Config.Process.Terminal. -func (g *Generator) SetProcessTerminal(b bool) { - g.initConfigProcess() - g.Config.Process.Terminal = b -} - -// SetProcessApparmorProfile sets g.Config.Process.ApparmorProfile. -func (g *Generator) SetProcessApparmorProfile(prof string) { - g.initConfigProcess() - g.Config.Process.ApparmorProfile = prof -} - -// SetProcessArgs sets g.Config.Process.Args. -func (g *Generator) SetProcessArgs(args []string) { - g.initConfigProcess() - g.Config.Process.Args = args -} - -// ClearProcessEnv clears g.Config.Process.Env. -func (g *Generator) ClearProcessEnv() { - if g.Config == nil || g.Config.Process == nil { - return - } - g.Config.Process.Env = []string{} - // Clear out the env cache map as well - g.envMap = map[string]int{} -} - -// AddProcessEnv adds name=value into g.Config.Process.Env, or replaces an -// existing entry with the given name. -func (g *Generator) AddProcessEnv(name, value string) { - if name == "" { - return - } - - g.initConfigProcess() - g.addEnv(fmt.Sprintf("%s=%s", name, value), name) -} - -// AddMultipleProcessEnv adds multiple name=value into g.Config.Process.Env, or replaces -// existing entries with the given name. -func (g *Generator) AddMultipleProcessEnv(envs []string) { - g.initConfigProcess() - - for _, val := range envs { - split := strings.SplitN(val, "=", 2) - g.addEnv(val, split[0]) - } -} - -// addEnv looks through adds ENV to the Process and checks envMap for -// any duplicates -// This is called by both AddMultipleProcessEnv and AddProcessEnv -func (g *Generator) addEnv(env, key string) { - if idx, ok := g.envMap[key]; ok { - // The ENV exists in the cache, so change its value in g.Config.Process.Env - g.Config.Process.Env[idx] = env - } else { - // else the env doesn't exist, so add it and add it's index to g.envMap - g.Config.Process.Env = append(g.Config.Process.Env, env) - g.envMap[key] = len(g.Config.Process.Env) - 1 - } -} - -// AddProcessRlimits adds rlimit into g.Config.Process.Rlimits. -func (g *Generator) AddProcessRlimits(rType string, rHard uint64, rSoft uint64) { - g.initConfigProcess() - for i, rlimit := range g.Config.Process.Rlimits { - if rlimit.Type == rType { - g.Config.Process.Rlimits[i].Hard = rHard - g.Config.Process.Rlimits[i].Soft = rSoft - return - } - } - - newRlimit := rspec.POSIXRlimit{ - Type: rType, - Hard: rHard, - Soft: rSoft, - } - g.Config.Process.Rlimits = append(g.Config.Process.Rlimits, newRlimit) -} - -// RemoveProcessRlimits removes a rlimit from g.Config.Process.Rlimits. -func (g *Generator) RemoveProcessRlimits(rType string) { - if g.Config == nil || g.Config.Process == nil { - return - } - for i, rlimit := range g.Config.Process.Rlimits { - if rlimit.Type == rType { - g.Config.Process.Rlimits = append(g.Config.Process.Rlimits[:i], g.Config.Process.Rlimits[i+1:]...) - return - } - } -} - -// ClearProcessRlimits clear g.Config.Process.Rlimits. -func (g *Generator) ClearProcessRlimits() { - if g.Config == nil || g.Config.Process == nil { - return - } - g.Config.Process.Rlimits = []rspec.POSIXRlimit{} -} - -// ClearProcessAdditionalGids clear g.Config.Process.AdditionalGids. -func (g *Generator) ClearProcessAdditionalGids() { - if g.Config == nil || g.Config.Process == nil { - return - } - g.Config.Process.User.AdditionalGids = []uint32{} -} - -// AddProcessAdditionalGid adds an additional gid into g.Config.Process.AdditionalGids. -func (g *Generator) AddProcessAdditionalGid(gid uint32) { //nolint:staticcheck // Ignore ST1003: method AddProcessAdditionalGid should be AddProcessAdditionalGID - g.initConfigProcess() - if slices.Contains(g.Config.Process.User.AdditionalGids, gid) { - return - } - g.Config.Process.User.AdditionalGids = append(g.Config.Process.User.AdditionalGids, gid) -} - -// SetProcessSelinuxLabel sets g.Config.Process.SelinuxLabel. -func (g *Generator) SetProcessSelinuxLabel(label string) { - g.initConfigProcess() - g.Config.Process.SelinuxLabel = label -} - -// SetLinuxCgroupsPath sets g.Config.Linux.CgroupsPath. -func (g *Generator) SetLinuxCgroupsPath(path string) { - g.initConfigLinux() - g.Config.Linux.CgroupsPath = path -} - -// SetLinuxIntelRdtClosID sets g.Config.Linux.IntelRdt.ClosID -func (g *Generator) SetLinuxIntelRdtClosID(clos string) { - g.initConfigLinuxIntelRdt() - g.Config.Linux.IntelRdt.ClosID = clos -} - -// SetLinuxIntelRdtL3CacheSchema sets g.Config.Linux.IntelRdt.L3CacheSchema -func (g *Generator) SetLinuxIntelRdtL3CacheSchema(schema string) { - g.initConfigLinuxIntelRdt() - g.Config.Linux.IntelRdt.L3CacheSchema = schema -} - -// SetLinuxMountLabel sets g.Config.Linux.MountLabel. -func (g *Generator) SetLinuxMountLabel(label string) { - g.initConfigLinux() - g.Config.Linux.MountLabel = label -} - -// SetProcessOOMScoreAdj sets g.Config.Process.OOMScoreAdj. -func (g *Generator) SetProcessOOMScoreAdj(adj int) { - g.initConfigProcess() - g.Config.Process.OOMScoreAdj = &adj -} - -// SetLinuxResourcesBlockIOLeafWeight sets g.Config.Linux.Resources.BlockIO.LeafWeight. -func (g *Generator) SetLinuxResourcesBlockIOLeafWeight(weight uint16) { - g.initConfigLinuxResourcesBlockIO() - g.Config.Linux.Resources.BlockIO.LeafWeight = &weight -} - -// AddLinuxResourcesBlockIOLeafWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight. -func (g *Generator) AddLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64, weight uint16) { - g.initConfigLinuxResourcesBlockIO() - for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { - if weightDevice.Major == major && weightDevice.Minor == minor { - g.Config.Linux.Resources.BlockIO.WeightDevice[i].LeafWeight = &weight - return - } - } - weightDevice := new(rspec.LinuxWeightDevice) - weightDevice.Major = major - weightDevice.Minor = minor - weightDevice.LeafWeight = &weight - g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice) -} - -// DropLinuxResourcesBlockIOLeafWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight -func (g *Generator) DropLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { - if weightDevice.Major == major && weightDevice.Minor == minor { - if weightDevice.Weight != nil { - newWeightDevice := new(rspec.LinuxWeightDevice) - newWeightDevice.Major = major - newWeightDevice.Minor = minor - newWeightDevice.Weight = weightDevice.Weight - g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice - } else { - g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...) - } - return - } - } -} - -// SetLinuxResourcesBlockIOWeight sets g.Config.Linux.Resources.BlockIO.Weight. -func (g *Generator) SetLinuxResourcesBlockIOWeight(weight uint16) { - g.initConfigLinuxResourcesBlockIO() - g.Config.Linux.Resources.BlockIO.Weight = &weight -} - -// AddLinuxResourcesBlockIOWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.Weight. -func (g *Generator) AddLinuxResourcesBlockIOWeightDevice(major int64, minor int64, weight uint16) { - g.initConfigLinuxResourcesBlockIO() - for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { - if weightDevice.Major == major && weightDevice.Minor == minor { - g.Config.Linux.Resources.BlockIO.WeightDevice[i].Weight = &weight - return - } - } - weightDevice := new(rspec.LinuxWeightDevice) - weightDevice.Major = major - weightDevice.Minor = minor - weightDevice.Weight = &weight - g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice) -} - -// DropLinuxResourcesBlockIOWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.Weight -func (g *Generator) DropLinuxResourcesBlockIOWeightDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { - if weightDevice.Major == major && weightDevice.Minor == minor { - if weightDevice.LeafWeight != nil { - newWeightDevice := new(rspec.LinuxWeightDevice) - newWeightDevice.Major = major - newWeightDevice.Minor = minor - newWeightDevice.LeafWeight = weightDevice.LeafWeight - g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice - } else { - g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...) - } - return - } - } -} - -// AddLinuxResourcesBlockIOThrottleReadBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice. -func (g *Generator) AddLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64, rate uint64) { - g.initConfigLinuxResourcesBlockIO() - throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor, rate) - g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices -} - -// DropLinuxResourcesBlockIOThrottleReadBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice. -func (g *Generator) DropLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor) - g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices -} - -// AddLinuxResourcesBlockIOThrottleReadIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice. -func (g *Generator) AddLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64, rate uint64) { - g.initConfigLinuxResourcesBlockIO() - throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor, rate) - g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices -} - -// DropLinuxResourcesBlockIOThrottleReadIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice. -func (g *Generator) DropLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor) - g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices -} - -// AddLinuxResourcesBlockIOThrottleWriteBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice. -func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64, rate uint64) { - g.initConfigLinuxResourcesBlockIO() - throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor, rate) - g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices -} - -// DropLinuxResourcesBlockIOThrottleWriteBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice. -func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor) - g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices -} - -// AddLinuxResourcesBlockIOThrottleWriteIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice. -func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64, rate uint64) { - g.initConfigLinuxResourcesBlockIO() - throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor, rate) - g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices -} - -// DropLinuxResourcesBlockIOThrottleWriteIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice. -func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { - return - } - - throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor) - g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices -} - -// SetLinuxResourcesCPUShares sets g.Config.Linux.Resources.CPU.Shares. -func (g *Generator) SetLinuxResourcesCPUShares(shares uint64) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.Shares = &shares -} - -// SetLinuxResourcesCPUQuota sets g.Config.Linux.Resources.CPU.Quota. -func (g *Generator) SetLinuxResourcesCPUQuota(quota int64) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.Quota = "a -} - -// SetLinuxResourcesCPUPeriod sets g.Config.Linux.Resources.CPU.Period. -func (g *Generator) SetLinuxResourcesCPUPeriod(period uint64) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.Period = &period -} - -// SetLinuxResourcesCPURealtimeRuntime sets g.Config.Linux.Resources.CPU.RealtimeRuntime. -func (g *Generator) SetLinuxResourcesCPURealtimeRuntime(time int64) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.RealtimeRuntime = &time -} - -// SetLinuxResourcesCPURealtimePeriod sets g.Config.Linux.Resources.CPU.RealtimePeriod. -func (g *Generator) SetLinuxResourcesCPURealtimePeriod(period uint64) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.RealtimePeriod = &period -} - -// SetLinuxResourcesCPUCpus sets g.Config.Linux.Resources.CPU.Cpus. -func (g *Generator) SetLinuxResourcesCPUCpus(cpus string) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.Cpus = cpus -} - -// SetLinuxResourcesCPUMems sets g.Config.Linux.Resources.CPU.Mems. -func (g *Generator) SetLinuxResourcesCPUMems(mems string) { - g.InitConfigLinuxResourcesCPU() - g.Config.Linux.Resources.CPU.Mems = mems -} - -// AddLinuxResourcesHugepageLimit adds or sets g.Config.Linux.Resources.HugepageLimits. -func (g *Generator) AddLinuxResourcesHugepageLimit(pageSize string, limit uint64) { - hugepageLimit := rspec.LinuxHugepageLimit{ - Pagesize: pageSize, - Limit: limit, - } - - g.initConfigLinuxResources() - for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits { - if pageLimit.Pagesize == pageSize { - g.Config.Linux.Resources.HugepageLimits[i].Limit = limit - return - } - } - g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits, hugepageLimit) -} - -// DropLinuxResourcesHugepageLimit drops a hugepage limit from g.Config.Linux.Resources.HugepageLimits. -func (g *Generator) DropLinuxResourcesHugepageLimit(pageSize string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil { - return - } - - for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits { - if pageLimit.Pagesize == pageSize { - g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits[:i], g.Config.Linux.Resources.HugepageLimits[i+1:]...) - return - } - } -} - -// SetLinuxResourcesUnified sets the g.Config.Linux.Resources.Unified. -func (g *Generator) SetLinuxResourcesUnified(unified map[string]string) { - g.initConfigLinuxResourcesUnified() - for k, v := range unified { - g.Config.Linux.Resources.Unified[k] = v - } -} - -// AddLinuxResourcesUnified adds or updates the key-value pair from g.Config.Linux.Resources.Unified -func (g *Generator) AddLinuxResourcesUnified(key, val string) { - g.initConfigLinuxResourcesUnified() - g.Config.Linux.Resources.Unified[key] = val -} - -// DropLinuxResourcesUnified drops a key-value pair from g.Config.Linux.Resources.Unified -func (g *Generator) DropLinuxResourcesUnified(key string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.Unified == nil { - return - } - delete(g.Config.Linux.Resources.Unified, key) -} - -// SetLinuxResourcesMemoryLimit sets g.Config.Linux.Resources.Memory.Limit. -func (g *Generator) SetLinuxResourcesMemoryLimit(limit int64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.Limit = &limit -} - -// SetLinuxResourcesMemoryReservation sets g.Config.Linux.Resources.Memory.Reservation. -func (g *Generator) SetLinuxResourcesMemoryReservation(reservation int64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.Reservation = &reservation -} - -// SetLinuxResourcesMemorySwap sets g.Config.Linux.Resources.Memory.Swap. -func (g *Generator) SetLinuxResourcesMemorySwap(swap int64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.Swap = &swap -} - -// SetLinuxResourcesMemoryKernel sets g.Config.Linux.Resources.Memory.Kernel. -func (g *Generator) SetLinuxResourcesMemoryKernel(kernel int64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.Kernel = &kernel //nolint:staticcheck // Ignore SA1019: g.Config.Linux.Resources.Memory.Kernel is deprecated -} - -// SetLinuxResourcesMemoryKernelTCP sets g.Config.Linux.Resources.Memory.KernelTCP. -func (g *Generator) SetLinuxResourcesMemoryKernelTCP(kernelTCP int64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.KernelTCP = &kernelTCP -} - -// SetLinuxResourcesMemorySwappiness sets g.Config.Linux.Resources.Memory.Swappiness. -func (g *Generator) SetLinuxResourcesMemorySwappiness(swappiness uint64) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.Swappiness = &swappiness -} - -// SetLinuxResourcesMemoryDisableOOMKiller sets g.Config.Linux.Resources.Memory.DisableOOMKiller. -func (g *Generator) SetLinuxResourcesMemoryDisableOOMKiller(disable bool) { - g.initConfigLinuxResourcesMemory() - g.Config.Linux.Resources.Memory.DisableOOMKiller = &disable -} - -// SetLinuxResourcesNetworkClassID sets g.Config.Linux.Resources.Network.ClassID. -func (g *Generator) SetLinuxResourcesNetworkClassID(classid uint32) { - g.initConfigLinuxResourcesNetwork() - g.Config.Linux.Resources.Network.ClassID = &classid -} - -// AddLinuxResourcesNetworkPriorities adds or sets g.Config.Linux.Resources.Network.Priorities. -func (g *Generator) AddLinuxResourcesNetworkPriorities(name string, prio uint32) { - g.initConfigLinuxResourcesNetwork() - for i, netPriority := range g.Config.Linux.Resources.Network.Priorities { - if netPriority.Name == name { - g.Config.Linux.Resources.Network.Priorities[i].Priority = prio - return - } - } - interfacePrio := new(rspec.LinuxInterfacePriority) - interfacePrio.Name = name - interfacePrio.Priority = prio - g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities, *interfacePrio) -} - -// DropLinuxResourcesNetworkPriorities drops one item from g.Config.Linux.Resources.Network.Priorities. -func (g *Generator) DropLinuxResourcesNetworkPriorities(name string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.Network == nil { - return - } - - for i, netPriority := range g.Config.Linux.Resources.Network.Priorities { - if netPriority.Name == name { - g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities[:i], g.Config.Linux.Resources.Network.Priorities[i+1:]...) - return - } - } -} - -// SetLinuxResourcesPidsLimit sets g.Config.Linux.Resources.Pids.Limit. -func (g *Generator) SetLinuxResourcesPidsLimit(limit int64) { - g.initConfigLinuxResourcesPids() - g.Config.Linux.Resources.Pids.Limit = &limit -} - -// ClearLinuxSysctl clears g.Config.Linux.Sysctl. -func (g *Generator) ClearLinuxSysctl() { - if g.Config == nil || g.Config.Linux == nil { - return - } - g.Config.Linux.Sysctl = make(map[string]string) -} - -// AddLinuxSysctl adds a new sysctl config into g.Config.Linux.Sysctl. -func (g *Generator) AddLinuxSysctl(key, value string) { - g.initConfigLinuxSysctl() - g.Config.Linux.Sysctl[key] = value -} - -// RemoveLinuxSysctl removes a sysctl config from g.Config.Linux.Sysctl. -func (g *Generator) RemoveLinuxSysctl(key string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Sysctl == nil { - return - } - delete(g.Config.Linux.Sysctl, key) -} - -// ClearLinuxUIDMappings clear g.Config.Linux.UIDMappings. -func (g *Generator) ClearLinuxUIDMappings() { - if g.Config == nil || g.Config.Linux == nil { - return - } - g.Config.Linux.UIDMappings = []rspec.LinuxIDMapping{} -} - -// AddLinuxUIDMapping adds uidMap into g.Config.Linux.UIDMappings. -func (g *Generator) AddLinuxUIDMapping(hid, cid, size uint32) { - idMapping := rspec.LinuxIDMapping{ - HostID: hid, - ContainerID: cid, - Size: size, - } - - g.initConfigLinux() - g.Config.Linux.UIDMappings = append(g.Config.Linux.UIDMappings, idMapping) -} - -// ClearLinuxGIDMappings clear g.Config.Linux.GIDMappings. -func (g *Generator) ClearLinuxGIDMappings() { - if g.Config == nil || g.Config.Linux == nil { - return - } - g.Config.Linux.GIDMappings = []rspec.LinuxIDMapping{} -} - -// AddLinuxGIDMapping adds gidMap into g.Config.Linux.GIDMappings. -func (g *Generator) AddLinuxGIDMapping(hid, cid, size uint32) { - idMapping := rspec.LinuxIDMapping{ - HostID: hid, - ContainerID: cid, - Size: size, - } - - g.initConfigLinux() - g.Config.Linux.GIDMappings = append(g.Config.Linux.GIDMappings, idMapping) -} - -// SetLinuxRootPropagation sets g.Config.Linux.RootfsPropagation. -func (g *Generator) SetLinuxRootPropagation(rp string) error { - switch rp { - case "": - case "private": - case "rprivate": - case "slave": - case "rslave": - case "shared": - case "rshared": - case "unbindable": - case "runbindable": - default: - return fmt.Errorf("rootfs-propagation %q must be empty or one of (r)private|(r)slave|(r)shared|(r)unbindable", rp) - } - g.initConfigLinux() - g.Config.Linux.RootfsPropagation = rp - return nil -} - -// ClearPreStartHooks clear g.Config.Hooks.Prestart. -func (g *Generator) ClearPreStartHooks() { - if g.Config == nil || g.Config.Hooks == nil { - return - } - g.Config.Hooks.Prestart = []rspec.Hook{} //nolint:staticcheck // Ignore SA1019: g.Config.Hooks.Prestart is deprecated -} - -// AddPreStartHook add a prestart hook into g.Config.Hooks.Prestart. -func (g *Generator) AddPreStartHook(preStartHook rspec.Hook) { - g.initConfigHooks() - g.Config.Hooks.Prestart = append(g.Config.Hooks.Prestart, preStartHook) //nolint:staticcheck // Ignore SA1019: g.Config.Hooks.Prestart is deprecated -} - -// ClearPostStopHooks clear g.Config.Hooks.Poststop. -func (g *Generator) ClearPostStopHooks() { - if g.Config == nil || g.Config.Hooks == nil { - return - } - g.Config.Hooks.Poststop = []rspec.Hook{} -} - -// AddPostStopHook adds a poststop hook into g.Config.Hooks.Poststop. -func (g *Generator) AddPostStopHook(postStopHook rspec.Hook) { - g.initConfigHooks() - g.Config.Hooks.Poststop = append(g.Config.Hooks.Poststop, postStopHook) -} - -// ClearPostStartHooks clear g.Config.Hooks.Poststart. -func (g *Generator) ClearPostStartHooks() { - if g.Config == nil || g.Config.Hooks == nil { - return - } - g.Config.Hooks.Poststart = []rspec.Hook{} -} - -// AddPostStartHook adds a poststart hook into g.Config.Hooks.Poststart. -func (g *Generator) AddPostStartHook(postStartHook rspec.Hook) { - g.initConfigHooks() - g.Config.Hooks.Poststart = append(g.Config.Hooks.Poststart, postStartHook) -} - -// AddMount adds a mount into g.Config.Mounts. -func (g *Generator) AddMount(mnt rspec.Mount) { - g.initConfig() - - g.Config.Mounts = append(g.Config.Mounts, mnt) -} - -// RemoveMount removes a mount point on the dest directory -func (g *Generator) RemoveMount(dest string) { - g.initConfig() - - for index, mount := range g.Config.Mounts { - if mount.Destination == dest { - g.Config.Mounts = append(g.Config.Mounts[:index], g.Config.Mounts[index+1:]...) - return - } - } -} - -// Mounts returns the list of mounts -func (g *Generator) Mounts() []rspec.Mount { - g.initConfig() - - return g.Config.Mounts -} - -// ClearMounts clear g.Config.Mounts -func (g *Generator) ClearMounts() { - if g.Config == nil { - return - } - g.Config.Mounts = []rspec.Mount{} -} - -// SetupPrivileged sets up the privilege-related fields inside g.Config. -func (g *Generator) SetupPrivileged(privileged bool) { - if privileged { // Add all capabilities in privileged mode. - var finalCapList []string - capList := capability.ListKnown() - if g.HostSpecific { - capList, _ = capability.ListSupported() - } - for _, cap := range capList { - finalCapList = append(finalCapList, fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))) - } - g.initConfigLinux() - g.initConfigProcessCapabilities() - g.ClearProcessCapabilities() - g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, finalCapList...) - g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, finalCapList...) - g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, finalCapList...) - g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, finalCapList...) - g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, finalCapList...) - g.Config.Process.SelinuxLabel = "" - g.Config.Process.ApparmorProfile = "" - g.Config.Linux.Seccomp = nil - } -} - -// ClearProcessCapabilities clear g.Config.Process.Capabilities. -func (g *Generator) ClearProcessCapabilities() { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return - } - g.Config.Process.Capabilities.Bounding = []string{} - g.Config.Process.Capabilities.Effective = []string{} - g.Config.Process.Capabilities.Inheritable = []string{} - g.Config.Process.Capabilities.Permitted = []string{} - g.Config.Process.Capabilities.Ambient = []string{} -} - -// AddProcessCapability adds a process capability into all 5 capability sets. -func (g *Generator) AddProcessCapability(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundAmbient, foundBounding, foundEffective, foundInheritable, foundPermitted bool - for _, cap := range g.Config.Process.Capabilities.Ambient { - if strings.ToUpper(cap) == cp { - foundAmbient = true - break - } - } - if !foundAmbient { - g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, cp) - } - - for _, cap := range g.Config.Process.Capabilities.Bounding { - if strings.ToUpper(cap) == cp { - foundBounding = true - break - } - } - if !foundBounding { - g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, cp) - } - - for _, cap := range g.Config.Process.Capabilities.Effective { - if strings.ToUpper(cap) == cp { - foundEffective = true - break - } - } - if !foundEffective { - g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, cp) - } - - for _, cap := range g.Config.Process.Capabilities.Inheritable { - if strings.ToUpper(cap) == cp { - foundInheritable = true - break - } - } - if !foundInheritable { - g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, cp) - } - - for _, cap := range g.Config.Process.Capabilities.Permitted { - if strings.ToUpper(cap) == cp { - foundPermitted = true - break - } - } - if !foundPermitted { - g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, cp) - } - - return nil -} - -// AddProcessCapabilityAmbient adds a process capability into g.Config.Process.Capabilities.Ambient. -func (g *Generator) AddProcessCapabilityAmbient(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundAmbient bool - for _, cap := range g.Config.Process.Capabilities.Ambient { - if strings.ToUpper(cap) == cp { - foundAmbient = true - break - } - } - - if !foundAmbient { - g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, cp) - } - - return nil -} - -// AddProcessCapabilityBounding adds a process capability into g.Config.Process.Capabilities.Bounding. -func (g *Generator) AddProcessCapabilityBounding(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundBounding bool - for _, cap := range g.Config.Process.Capabilities.Bounding { - if strings.ToUpper(cap) == cp { - foundBounding = true - break - } - } - if !foundBounding { - g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, cp) - } - - return nil -} - -// AddProcessCapabilityEffective adds a process capability into g.Config.Process.Capabilities.Effective. -func (g *Generator) AddProcessCapabilityEffective(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundEffective bool - for _, cap := range g.Config.Process.Capabilities.Effective { - if strings.ToUpper(cap) == cp { - foundEffective = true - break - } - } - if !foundEffective { - g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, cp) - } - - return nil -} - -// AddProcessCapabilityInheritable adds a process capability into g.Config.Process.Capabilities.Inheritable. -func (g *Generator) AddProcessCapabilityInheritable(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundInheritable bool - for _, cap := range g.Config.Process.Capabilities.Inheritable { - if strings.ToUpper(cap) == cp { - foundInheritable = true - break - } - } - if !foundInheritable { - g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, cp) - } - - return nil -} - -// AddProcessCapabilityPermitted adds a process capability into g.Config.Process.Capabilities.Permitted. -func (g *Generator) AddProcessCapabilityPermitted(c string) error { - cp := strings.ToUpper(c) - if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { - return err - } - - g.initConfigProcessCapabilities() - - var foundPermitted bool - for _, cap := range g.Config.Process.Capabilities.Permitted { - if strings.ToUpper(cap) == cp { - foundPermitted = true - break - } - } - if !foundPermitted { - g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, cp) - } - - return nil -} - -// DropProcessCapability drops a process capability from all 5 capability sets. -func (g *Generator) DropProcessCapability(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Ambient { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Ambient = removeFunc(g.Config.Process.Capabilities.Ambient, i) - } - } - for i, cap := range g.Config.Process.Capabilities.Bounding { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Bounding = removeFunc(g.Config.Process.Capabilities.Bounding, i) - } - } - for i, cap := range g.Config.Process.Capabilities.Effective { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Effective = removeFunc(g.Config.Process.Capabilities.Effective, i) - } - } - for i, cap := range g.Config.Process.Capabilities.Inheritable { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Inheritable = removeFunc(g.Config.Process.Capabilities.Inheritable, i) - } - } - for i, cap := range g.Config.Process.Capabilities.Permitted { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Permitted = removeFunc(g.Config.Process.Capabilities.Permitted, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -// DropProcessCapabilityAmbient drops a process capability from g.Config.Process.Capabilities.Ambient. -func (g *Generator) DropProcessCapabilityAmbient(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Ambient { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Ambient = removeFunc(g.Config.Process.Capabilities.Ambient, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -// DropProcessCapabilityBounding drops a process capability from g.Config.Process.Capabilities.Bounding. -func (g *Generator) DropProcessCapabilityBounding(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Bounding { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Bounding = removeFunc(g.Config.Process.Capabilities.Bounding, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -// DropProcessCapabilityEffective drops a process capability from g.Config.Process.Capabilities.Effective. -func (g *Generator) DropProcessCapabilityEffective(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Effective { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Effective = removeFunc(g.Config.Process.Capabilities.Effective, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -// DropProcessCapabilityInheritable drops a process capability from g.Config.Process.Capabilities.Inheritable. -func (g *Generator) DropProcessCapabilityInheritable(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Inheritable { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Inheritable = removeFunc(g.Config.Process.Capabilities.Inheritable, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -// DropProcessCapabilityPermitted drops a process capability from g.Config.Process.Capabilities.Permitted. -func (g *Generator) DropProcessCapabilityPermitted(c string) error { - if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { - return nil - } - - cp := strings.ToUpper(c) - for i, cap := range g.Config.Process.Capabilities.Permitted { - if strings.ToUpper(cap) == cp { - g.Config.Process.Capabilities.Permitted = removeFunc(g.Config.Process.Capabilities.Permitted, i) - } - } - - return capsCheck.CapValid(cp, false) -} - -func mapStrToNamespace(ns string, path string) (rspec.LinuxNamespace, error) { - switch ns { - case "network": - return rspec.LinuxNamespace{Type: rspec.NetworkNamespace, Path: path}, nil - case "pid": - return rspec.LinuxNamespace{Type: rspec.PIDNamespace, Path: path}, nil - case "mount": - return rspec.LinuxNamespace{Type: rspec.MountNamespace, Path: path}, nil - case "ipc": - return rspec.LinuxNamespace{Type: rspec.IPCNamespace, Path: path}, nil - case "uts": - return rspec.LinuxNamespace{Type: rspec.UTSNamespace, Path: path}, nil - case "user": - return rspec.LinuxNamespace{Type: rspec.UserNamespace, Path: path}, nil - case "cgroup": - return rspec.LinuxNamespace{Type: rspec.CgroupNamespace, Path: path}, nil - default: - return rspec.LinuxNamespace{}, fmt.Errorf("unrecognized namespace %q", ns) - } -} - -// ClearLinuxNamespaces clear g.Config.Linux.Namespaces. -func (g *Generator) ClearLinuxNamespaces() { - if g.Config == nil || g.Config.Linux == nil { - return - } - g.Config.Linux.Namespaces = []rspec.LinuxNamespace{} -} - -// AddOrReplaceLinuxNamespace adds or replaces a namespace inside -// g.Config.Linux.Namespaces. -func (g *Generator) AddOrReplaceLinuxNamespace(ns string, path string) error { - namespace, err := mapStrToNamespace(ns, path) - if err != nil { - return err - } - - g.initConfigLinux() - for i, ns := range g.Config.Linux.Namespaces { - if ns.Type == namespace.Type { - g.Config.Linux.Namespaces[i] = namespace - return nil - } - } - g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces, namespace) - return nil -} - -// RemoveLinuxNamespace removes a namespace from g.Config.Linux.Namespaces. -func (g *Generator) RemoveLinuxNamespace(ns string) error { - namespace, err := mapStrToNamespace(ns, "") - if err != nil { - return err - } - - if g.Config == nil || g.Config.Linux == nil { - return nil - } - for i, ns := range g.Config.Linux.Namespaces { - if ns.Type == namespace.Type { - g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces[:i], g.Config.Linux.Namespaces[i+1:]...) - return nil - } - } - return nil -} - -// AddDevice - add a device into g.Config.Linux.Devices -func (g *Generator) AddDevice(device rspec.LinuxDevice) { - g.initConfigLinux() - - for i, dev := range g.Config.Linux.Devices { - if dev.Path == device.Path { - g.Config.Linux.Devices[i] = device - return - } - } - - g.Config.Linux.Devices = append(g.Config.Linux.Devices, device) -} - -// RemoveDevice remove a device from g.Config.Linux.Devices -func (g *Generator) RemoveDevice(path string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil { - return - } - - for i, device := range g.Config.Linux.Devices { - if device.Path == path { - g.Config.Linux.Devices = append(g.Config.Linux.Devices[:i], g.Config.Linux.Devices[i+1:]...) - return - } - } -} - -// ClearLinuxDevices clears g.Config.Linux.Devices -func (g *Generator) ClearLinuxDevices() { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil { - return - } - - g.Config.Linux.Devices = []rspec.LinuxDevice{} -} - -// AddLinuxResourcesDevice - add a device into g.Config.Linux.Resources.Devices -func (g *Generator) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { - g.initConfigLinuxResources() - - device := rspec.LinuxDeviceCgroup{ - Allow: allow, - Type: devType, - Access: access, - Major: major, - Minor: minor, - } - g.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices, device) -} - -// RemoveLinuxResourcesDevice - remove a device from g.Config.Linux.Resources.Devices -func (g *Generator) RemoveLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { - if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil { - return - } - for i, device := range g.Config.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.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices[:i], g.Config.Linux.Resources.Devices[i+1:]...) - return - } - } -} - -// SetSyscallAction adds rules for syscalls with the specified action -func (g *Generator) SetSyscallAction(arguments seccomp.SyscallOpts) error { - g.initConfigLinuxSeccomp() - return seccomp.ParseSyscallFlag(arguments, g.Config.Linux.Seccomp) -} - -// SetDefaultSeccompAction sets the default action for all syscalls not defined -// and then removes any syscall rules with this action already specified. -func (g *Generator) SetDefaultSeccompAction(action string) error { - g.initConfigLinuxSeccomp() - return seccomp.ParseDefaultAction(action, g.Config.Linux.Seccomp) -} - -// SetDefaultSeccompActionForce only sets the default action for all syscalls not defined -func (g *Generator) SetDefaultSeccompActionForce(action string) error { - g.initConfigLinuxSeccomp() - return seccomp.ParseDefaultActionForce(action, g.Config.Linux.Seccomp) -} - -// SetDomainName sets g.Config.Domainname -func (g *Generator) SetDomainName(domain string) { - g.initConfig() - g.Config.Domainname = domain -} - -// SetSeccompArchitecture sets the supported seccomp architectures -func (g *Generator) SetSeccompArchitecture(architecture string) error { - g.initConfigLinuxSeccomp() - return seccomp.ParseArchitectureFlag(architecture, g.Config.Linux.Seccomp) -} - -// RemoveSeccompRule removes rules for any specified syscalls -func (g *Generator) RemoveSeccompRule(arguments string) error { - g.initConfigLinuxSeccomp() - return seccomp.RemoveAction(arguments, g.Config.Linux.Seccomp) -} - -// RemoveAllSeccompRules removes all syscall rules -func (g *Generator) RemoveAllSeccompRules() error { - g.initConfigLinuxSeccomp() - return seccomp.RemoveAllSeccompRules(g.Config.Linux.Seccomp) -} - -// AddLinuxMaskedPaths adds masked paths into g.Config.Linux.MaskedPaths. -func (g *Generator) AddLinuxMaskedPaths(path string) { - g.initConfigLinux() - g.Config.Linux.MaskedPaths = append(g.Config.Linux.MaskedPaths, path) -} - -// AddLinuxReadonlyPaths adds readonly paths into g.Config.Linux.MaskedPaths. -func (g *Generator) AddLinuxReadonlyPaths(path string) { - g.initConfigLinux() - g.Config.Linux.ReadonlyPaths = append(g.Config.Linux.ReadonlyPaths, path) -} - -func addOrReplaceBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64, rate uint64) []rspec.LinuxThrottleDevice { - throttleDevices := tmpList - for i, throttleDevice := range throttleDevices { - if throttleDevice.Major == major && throttleDevice.Minor == minor { - throttleDevices[i].Rate = rate - return throttleDevices - } - } - throttleDevice := new(rspec.LinuxThrottleDevice) - throttleDevice.Major = major - throttleDevice.Minor = minor - throttleDevice.Rate = rate - throttleDevices = append(throttleDevices, *throttleDevice) - - return throttleDevices -} - -func dropBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64) []rspec.LinuxThrottleDevice { - throttleDevices := tmpList - for i, throttleDevice := range throttleDevices { - if throttleDevice.Major == major && throttleDevice.Minor == minor { - throttleDevices = append(throttleDevices[:i], throttleDevices[i+1:]...) - return throttleDevices - } - } - - return throttleDevices -} - -// AddSolarisAnet adds network into g.Config.Solaris.Anet -func (g *Generator) AddSolarisAnet(anet rspec.SolarisAnet) { - g.initConfigSolaris() - g.Config.Solaris.Anet = append(g.Config.Solaris.Anet, anet) -} - -// SetSolarisCappedCPUNcpus sets g.Config.Solaris.CappedCPU.Ncpus -func (g *Generator) SetSolarisCappedCPUNcpus(ncpus string) { - g.initConfigSolarisCappedCPU() - g.Config.Solaris.CappedCPU.Ncpus = ncpus -} - -// SetSolarisCappedMemoryPhysical sets g.Config.Solaris.CappedMemory.Physical -func (g *Generator) SetSolarisCappedMemoryPhysical(physical string) { - g.initConfigSolarisCappedMemory() - g.Config.Solaris.CappedMemory.Physical = physical -} - -// SetSolarisCappedMemorySwap sets g.Config.Solaris.CappedMemory.Swap -func (g *Generator) SetSolarisCappedMemorySwap(swap string) { - g.initConfigSolarisCappedMemory() - g.Config.Solaris.CappedMemory.Swap = swap -} - -// SetSolarisLimitPriv sets g.Config.Solaris.LimitPriv -func (g *Generator) SetSolarisLimitPriv(limitPriv string) { - g.initConfigSolaris() - g.Config.Solaris.LimitPriv = limitPriv -} - -// SetSolarisMaxShmMemory sets g.Config.Solaris.MaxShmMemory -func (g *Generator) SetSolarisMaxShmMemory(memory string) { - g.initConfigSolaris() - g.Config.Solaris.MaxShmMemory = memory -} - -// SetSolarisMilestone sets g.Config.Solaris.Milestone -func (g *Generator) SetSolarisMilestone(milestone string) { - g.initConfigSolaris() - g.Config.Solaris.Milestone = milestone -} - -// SetVMHypervisorPath sets g.Config.VM.Hypervisor.Path -func (g *Generator) SetVMHypervisorPath(path string) error { - if !strings.HasPrefix(path, "/") { - return fmt.Errorf("hypervisorPath %v is not an absolute path", path) - } - g.initConfigVM() - g.Config.VM.Hypervisor.Path = path - return nil -} - -// SetVMHypervisorParameters sets g.Config.VM.Hypervisor.Parameters -func (g *Generator) SetVMHypervisorParameters(parameters []string) { - g.initConfigVM() - g.Config.VM.Hypervisor.Parameters = parameters -} - -// SetVMKernelPath sets g.Config.VM.Kernel.Path -func (g *Generator) SetVMKernelPath(path string) error { - if !strings.HasPrefix(path, "/") { - return fmt.Errorf("kernelPath %v is not an absolute path", path) - } - g.initConfigVM() - g.Config.VM.Kernel.Path = path - return nil -} - -// SetVMKernelParameters sets g.Config.VM.Kernel.Parameters -func (g *Generator) SetVMKernelParameters(parameters []string) { - g.initConfigVM() - g.Config.VM.Kernel.Parameters = parameters -} - -// SetVMKernelInitRD sets g.Config.VM.Kernel.InitRD -func (g *Generator) SetVMKernelInitRD(initrd string) error { - if !strings.HasPrefix(initrd, "/") { - return fmt.Errorf("kernelInitrd %v is not an absolute path", initrd) - } - g.initConfigVM() - g.Config.VM.Kernel.InitRD = initrd - return nil -} - -// SetVMImagePath sets g.Config.VM.Image.Path -func (g *Generator) SetVMImagePath(path string) error { - if !strings.HasPrefix(path, "/") { - return fmt.Errorf("imagePath %v is not an absolute path", path) - } - g.initConfigVM() - g.Config.VM.Image.Path = path - return nil -} - -// SetVMImageFormat sets g.Config.VM.Image.Format -func (g *Generator) SetVMImageFormat(format string) error { - switch format { - case "raw": - case "qcow2": - case "vdi": - case "vmdk": - case "vhd": - default: - return fmt.Errorf("Commonly supported formats are: raw, qcow2, vdi, vmdk, vhd") - } - g.initConfigVM() - g.Config.VM.Image.Format = format - return nil -} - -// SetWindowsHypervUntilityVMPath sets g.Config.Windows.HyperV.UtilityVMPath. -func (g *Generator) SetWindowsHypervUntilityVMPath(path string) { - g.initConfigWindowsHyperV() - g.Config.Windows.HyperV.UtilityVMPath = path -} - -// SetWindowsIgnoreFlushesDuringBoot sets g.Config.Windows.IgnoreFlushesDuringBoot. -func (g *Generator) SetWindowsIgnoreFlushesDuringBoot(ignore bool) { - g.initConfigWindows() - g.Config.Windows.IgnoreFlushesDuringBoot = ignore -} - -// AddWindowsLayerFolders adds layer folders into g.Config.Windows.LayerFolders. -func (g *Generator) AddWindowsLayerFolders(folder string) { - g.initConfigWindows() - g.Config.Windows.LayerFolders = append(g.Config.Windows.LayerFolders, folder) -} - -// AddWindowsDevices adds or sets g.Config.Windwos.Devices -func (g *Generator) AddWindowsDevices(id, idType string) error { - if idType != "class" { - return fmt.Errorf("Invalid idType value: %s. Windows only supports a value of class", idType) - } - device := rspec.WindowsDevice{ - ID: id, - IDType: idType, - } - - g.initConfigWindows() - for i, device := range g.Config.Windows.Devices { - if device.ID == id { - g.Config.Windows.Devices[i].IDType = idType - return nil - } - } - g.Config.Windows.Devices = append(g.Config.Windows.Devices, device) - return nil -} - -// SetWindowsNetwork sets g.Config.Windows.Network. -func (g *Generator) SetWindowsNetwork(network rspec.WindowsNetwork) { - g.initConfigWindows() - g.Config.Windows.Network = &network -} - -// SetWindowsNetworkAllowUnqualifiedDNSQuery sets g.Config.Windows.Network.AllowUnqualifiedDNSQuery -func (g *Generator) SetWindowsNetworkAllowUnqualifiedDNSQuery(setting bool) { - g.initConfigWindowsNetwork() - g.Config.Windows.Network.AllowUnqualifiedDNSQuery = setting -} - -// SetWindowsNetworkNamespace sets g.Config.Windows.Network.NetworkNamespace -func (g *Generator) SetWindowsNetworkNamespace(path string) { - g.initConfigWindowsNetwork() - g.Config.Windows.Network.NetworkNamespace = path -} - -// SetWindowsResourcesCPU sets g.Config.Windows.Resources.CPU. -func (g *Generator) SetWindowsResourcesCPU(cpu rspec.WindowsCPUResources) { - g.initConfigWindowsResources() - g.Config.Windows.Resources.CPU = &cpu -} - -// SetWindowsResourcesMemoryLimit sets g.Config.Windows.Resources.Memory.Limit. -func (g *Generator) SetWindowsResourcesMemoryLimit(limit uint64) { - g.initConfigWindowsResourcesMemory() - g.Config.Windows.Resources.Memory.Limit = &limit -} - -// SetWindowsResourcesStorage sets g.Config.Windows.Resources.Storage. -func (g *Generator) SetWindowsResourcesStorage(storage rspec.WindowsStorageResources) { - g.initConfigWindowsResources() - g.Config.Windows.Resources.Storage = &storage -} - -// SetWindowsServicing sets g.Config.Windows.Servicing. -func (g *Generator) SetWindowsServicing(servicing bool) { - g.initConfigWindows() - g.Config.Windows.Servicing = servicing -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go deleted file mode 100644 index f28d8f5875..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go +++ /dev/null @@ -1,7 +0,0 @@ -package seccomp - -const ( - seccompOverwrite = "overwrite" - seccompAppend = "append" - nothing = "nothing" -) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go deleted file mode 100644 index a845af5136..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go +++ /dev/null @@ -1,137 +0,0 @@ -package seccomp - -import ( - "fmt" - "strconv" - "strings" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -// SyscallOpts contain options for parsing syscall rules -type SyscallOpts struct { - Action string - Syscall string - Index string - Value string - ValueTwo string - Operator string -} - -// ParseSyscallFlag takes a SyscallOpts struct and the seccomp configuration -// and sets the new syscall rule accordingly -func ParseSyscallFlag(args SyscallOpts, config *rspec.LinuxSeccomp) error { - var arguments []string - if args.Index != "" && args.Value != "" && args.ValueTwo != "" && args.Operator != "" { - arguments = []string{ - args.Action, args.Syscall, args.Index, args.Value, - args.ValueTwo, args.Operator, - } - } else { - arguments = []string{args.Action, args.Syscall} - } - - action, _ := parseAction(arguments[0]) - if action == config.DefaultAction && args.argsAreEmpty() { - // default already set, no need to make changes - return nil - } - - var newSyscall rspec.LinuxSyscall - numOfArgs := len(arguments) - if numOfArgs == 6 || numOfArgs == 2 { - argStruct, err := parseArguments(arguments[1:]) - if err != nil { - return err - } - newSyscall = newSyscallStruct(arguments[1], action, argStruct) - } else { - return fmt.Errorf("incorrect number of arguments to ParseSyscall: %d", numOfArgs) - } - - descison, err := decideCourseOfAction(&newSyscall, config.Syscalls) - if err != nil { - return err - } - delimDescison := strings.Split(descison, ":") - - if delimDescison[0] == seccompAppend { - config.Syscalls = append(config.Syscalls, newSyscall) - } - - if delimDescison[0] == seccompOverwrite { - indexForOverwrite, err := strconv.ParseInt(delimDescison[1], 10, 32) - if err != nil { - return err - } - config.Syscalls[indexForOverwrite] = newSyscall - } - - return nil -} - -var actions = map[string]rspec.LinuxSeccompAction{ - "allow": rspec.ActAllow, - "errno": rspec.ActErrno, - "kill": rspec.ActKill, - "trace": rspec.ActTrace, - "trap": rspec.ActTrap, -} - -// Take passed action, return the SCMP_ACT_ version of it -func parseAction(action string) (rspec.LinuxSeccompAction, error) { - a, ok := actions[action] - if !ok { - return "", fmt.Errorf("unrecognized action: %s", action) - } - return a, nil -} - -// ParseDefaultAction sets the default action of the seccomp configuration -// and then removes any rules that were already specified with this action -func ParseDefaultAction(action string, config *rspec.LinuxSeccomp) error { - if action == "" { - return nil - } - - defaultAction, err := parseAction(action) - if err != nil { - return err - } - config.DefaultAction = defaultAction - err = RemoveAllMatchingRules(config, defaultAction) - if err != nil { - return err - } - return nil -} - -// ParseDefaultActionForce simply sets the default action of the seccomp configuration -func ParseDefaultActionForce(action string, config *rspec.LinuxSeccomp) error { - if action == "" { - return nil - } - - defaultAction, err := parseAction(action) - if err != nil { - return err - } - config.DefaultAction = defaultAction - return nil -} - -func newSyscallStruct(name string, action rspec.LinuxSeccompAction, args []rspec.LinuxSeccompArg) rspec.LinuxSyscall { - syscallStruct := rspec.LinuxSyscall{ - Names: []string{name}, - Action: action, - Args: args, - } - return syscallStruct -} - -func (s SyscallOpts) argsAreEmpty() bool { - return (s.Index == "" && - s.Value == "" && - s.ValueTwo == "" && - s.Operator == "") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go deleted file mode 100644 index 9b2bdfd2fa..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go +++ /dev/null @@ -1,55 +0,0 @@ -package seccomp - -import ( - "fmt" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -// ParseArchitectureFlag takes the raw string passed with the --arch flag, parses it -// and updates the Seccomp config accordingly -func ParseArchitectureFlag(architectureArg string, config *rspec.LinuxSeccomp) error { - correctedArch, err := parseArch(architectureArg) - if err != nil { - return err - } - - shouldAppend := true - for _, alreadySpecified := range config.Architectures { - if correctedArch == alreadySpecified { - shouldAppend = false - } - } - if shouldAppend { - config.Architectures = append(config.Architectures, correctedArch) - } - return nil -} - -func parseArch(arch string) (rspec.Arch, error) { - arches := map[string]rspec.Arch{ - "x86": rspec.ArchX86, - "amd64": rspec.ArchX86_64, - "x32": rspec.ArchX32, - "arm": rspec.ArchARM, - "arm64": rspec.ArchAARCH64, - "mips": rspec.ArchMIPS, - "mips64": rspec.ArchMIPS64, - "mips64n32": rspec.ArchMIPS64N32, - "mipsel": rspec.ArchMIPSEL, - "mipsel64": rspec.ArchMIPSEL64, - "mipsel64n32": rspec.ArchMIPSEL64N32, - "parisc": rspec.ArchPARISC, - "parisc64": rspec.ArchPARISC64, - "ppc": rspec.ArchPPC, - "ppc64": rspec.ArchPPC64, - "ppc64le": rspec.ArchPPC64LE, - "s390": rspec.ArchS390, - "s390x": rspec.ArchS390X, - } - a, ok := arches[arch] - if !ok { - return "", fmt.Errorf("unrecognized architecture: %s", arch) - } - return a, nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go deleted file mode 100644 index 2b4c394e67..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go +++ /dev/null @@ -1,73 +0,0 @@ -package seccomp - -import ( - "fmt" - "strconv" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -// parseArguments takes a list of arguments (delimArgs). It parses and fills out -// the argument information and returns a slice of arg structs -func parseArguments(delimArgs []string) ([]rspec.LinuxSeccompArg, error) { - nilArgSlice := []rspec.LinuxSeccompArg{} - numberOfArgs := len(delimArgs) - - // No parameters passed with syscall - if numberOfArgs == 1 { - return nilArgSlice, nil - } - - // Correct number of parameters passed with syscall - if numberOfArgs == 5 { - syscallIndex, err := strconv.ParseUint(delimArgs[1], 10, 0) - if err != nil { - return nilArgSlice, err - } - - syscallValue, err := strconv.ParseUint(delimArgs[2], 10, 64) - if err != nil { - return nilArgSlice, err - } - - syscallValueTwo, err := strconv.ParseUint(delimArgs[3], 10, 64) - if err != nil { - return nilArgSlice, err - } - - syscallOp, err := parseOperator(delimArgs[4]) - if err != nil { - return nilArgSlice, err - } - - argStruct := rspec.LinuxSeccompArg{ - Index: uint(syscallIndex), - Value: syscallValue, - ValueTwo: syscallValueTwo, - Op: syscallOp, - } - - argSlice := []rspec.LinuxSeccompArg{} - argSlice = append(argSlice, argStruct) - return argSlice, nil - } - - return nilArgSlice, fmt.Errorf("incorrect number of arguments passed with syscall: %d", numberOfArgs) -} - -func parseOperator(operator string) (rspec.LinuxSeccompOperator, error) { - operators := map[string]rspec.LinuxSeccompOperator{ - "NE": rspec.OpNotEqual, - "LT": rspec.OpLessThan, - "LE": rspec.OpLessEqual, - "EQ": rspec.OpEqualTo, - "GE": rspec.OpGreaterEqual, - "GT": rspec.OpGreaterThan, - "ME": rspec.OpMaskedEqual, - } - o, ok := operators[operator] - if !ok { - return "", fmt.Errorf("unrecognized operator: %s", operator) - } - return o, nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go deleted file mode 100644 index 59537d49c4..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go +++ /dev/null @@ -1,52 +0,0 @@ -package seccomp - -import ( - "fmt" - "reflect" - "strings" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -// RemoveAction takes the argument string that was passed with the --remove flag, -// parses it, and updates the Seccomp config accordingly -func RemoveAction(arguments string, config *rspec.LinuxSeccomp) error { - if config == nil { - return fmt.Errorf("Cannot remove action from nil Seccomp pointer") - } - - syscallsToRemove := strings.Split(arguments, ",") - - for counter, syscallStruct := range config.Syscalls { - if reflect.DeepEqual(syscallsToRemove, syscallStruct.Names) { - config.Syscalls = append(config.Syscalls[:counter], config.Syscalls[counter+1:]...) - } - } - - return nil -} - -// RemoveAllSeccompRules removes all seccomp syscall rules -func RemoveAllSeccompRules(config *rspec.LinuxSeccomp) error { - if config == nil { - return fmt.Errorf("Cannot remove action from nil Seccomp pointer") - } - newSyscallSlice := []rspec.LinuxSyscall{} - config.Syscalls = newSyscallSlice - return nil -} - -// RemoveAllMatchingRules will remove any syscall rules that match the specified action -func RemoveAllMatchingRules(config *rspec.LinuxSeccomp, seccompAction rspec.LinuxSeccompAction) error { - if config == nil { - return fmt.Errorf("Cannot remove action from nil Seccomp pointer") - } - - for _, syscall := range config.Syscalls { - if reflect.DeepEqual(syscall.Action, seccompAction) { - RemoveAction(strings.Join(syscall.Names, ","), config) - } - } - - return nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go deleted file mode 100644 index 64ec8a1fac..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go +++ /dev/null @@ -1,603 +0,0 @@ -package seccomp - -import ( - "runtime" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -func arches() []rspec.Arch { - native := runtime.GOARCH - - switch native { - case "amd64": - return []rspec.Arch{rspec.ArchX86_64, rspec.ArchX86, rspec.ArchX32} - case "arm64": - return []rspec.Arch{rspec.ArchARM, rspec.ArchAARCH64} - case "mips64": - return []rspec.Arch{rspec.ArchMIPS, rspec.ArchMIPS64, rspec.ArchMIPS64N32} - case "mips64n32": - return []rspec.Arch{rspec.ArchMIPS, rspec.ArchMIPS64, rspec.ArchMIPS64N32} - case "mipsel64": - return []rspec.Arch{rspec.ArchMIPSEL, rspec.ArchMIPSEL64, rspec.ArchMIPSEL64N32} - case "mipsel64n32": - return []rspec.Arch{rspec.ArchMIPSEL, rspec.ArchMIPSEL64, rspec.ArchMIPSEL64N32} - case "s390x": - return []rspec.Arch{rspec.ArchS390, rspec.ArchS390X} - default: - return []rspec.Arch{} - } -} - -// DefaultProfile defines the whitelist for the default seccomp profile. -func DefaultProfile(rs *rspec.Spec) *rspec.LinuxSeccomp { - syscalls := []rspec.LinuxSyscall{ - { - Names: []string{ - "accept", - "accept4", - "access", - "alarm", - "bind", - "brk", - "capget", - "capset", - "chdir", - "chmod", - "chown", - "chown32", - "clock_getres", - "clock_gettime", - "clock_nanosleep", - "close", - "connect", - "copy_file_range", - "creat", - "dup", - "dup2", - "dup3", - "epoll_create", - "epoll_create1", - "epoll_ctl", - "epoll_ctl_old", - "epoll_pwait", - "epoll_wait", - "epoll_wait_old", - "eventfd", - "eventfd2", - "execve", - "execveat", - "exit", - "exit_group", - "faccessat", - "fadvise64", - "fadvise64_64", - "fallocate", - "fanotify_mark", - "fchdir", - "fchmod", - "fchmodat", - "fchown", - "fchown32", - "fchownat", - "fcntl", - "fcntl64", - "fdatasync", - "fgetxattr", - "flistxattr", - "flock", - "fork", - "fremovexattr", - "fsetxattr", - "fstat", - "fstat64", - "fstatat64", - "fstatfs", - "fstatfs64", - "fsync", - "ftruncate", - "ftruncate64", - "futex", - "futimesat", - "getcpu", - "getcwd", - "getdents", - "getdents64", - "getegid", - "getegid32", - "geteuid", - "geteuid32", - "getgid", - "getgid32", - "getgroups", - "getgroups32", - "getitimer", - "getpeername", - "getpgid", - "getpgrp", - "getpid", - "getppid", - "getpriority", - "getrandom", - "getresgid", - "getresgid32", - "getresuid", - "getresuid32", - "getrlimit", - "get_robust_list", - "getrusage", - "getsid", - "getsockname", - "getsockopt", - "get_thread_area", - "gettid", - "gettimeofday", - "getuid", - "getuid32", - "getxattr", - "inotify_add_watch", - "inotify_init", - "inotify_init1", - "inotify_rm_watch", - "io_cancel", - "ioctl", - "io_destroy", - "io_getevents", - "ioprio_get", - "ioprio_set", - "io_setup", - "io_submit", - "ipc", - "kill", - "landlock_add_rule", - "landlock_create_ruleset", - "landlock_restrict_self", - "lchown", - "lchown32", - "lgetxattr", - "link", - "linkat", - "listen", - "listxattr", - "llistxattr", - "_llseek", - "lremovexattr", - "lseek", - "lsetxattr", - "lstat", - "lstat64", - "madvise", - "memfd_create", - "mincore", - "mkdir", - "mkdirat", - "mknod", - "mknodat", - "mlock", - "mlock2", - "mlockall", - "mmap", - "mmap2", - "mprotect", - "mq_getsetattr", - "mq_notify", - "mq_open", - "mq_timedreceive", - "mq_timedsend", - "mq_unlink", - "mremap", - "msgctl", - "msgget", - "msgrcv", - "msgsnd", - "msync", - "munlock", - "munlockall", - "munmap", - "nanosleep", - "newfstatat", - "_newselect", - "open", - "openat", - "pause", - "pipe", - "pipe2", - "poll", - "ppoll", - "prctl", - "pread64", - "preadv", - "prlimit64", - "pselect6", - "pwrite64", - "pwritev", - "read", - "readahead", - "readlink", - "readlinkat", - "readv", - "recv", - "recvfrom", - "recvmmsg", - "recvmsg", - "remap_file_pages", - "removexattr", - "rename", - "renameat", - "renameat2", - "restart_syscall", - "rmdir", - "rt_sigaction", - "rt_sigpending", - "rt_sigprocmask", - "rt_sigqueueinfo", - "rt_sigreturn", - "rt_sigsuspend", - "rt_sigtimedwait", - "rt_tgsigqueueinfo", - "sched_getaffinity", - "sched_getattr", - "sched_getparam", - "sched_get_priority_max", - "sched_get_priority_min", - "sched_getscheduler", - "sched_rr_get_interval", - "sched_setaffinity", - "sched_setattr", - "sched_setparam", - "sched_setscheduler", - "sched_yield", - "seccomp", - "select", - "semctl", - "semget", - "semop", - "semtimedop", - "send", - "sendfile", - "sendfile64", - "sendmmsg", - "sendmsg", - "sendto", - "setfsgid", - "setfsgid32", - "setfsuid", - "setfsuid32", - "setgid", - "setgid32", - "setgroups", - "setgroups32", - "setitimer", - "setpgid", - "setpriority", - "setregid", - "setregid32", - "setresgid", - "setresgid32", - "setresuid", - "setresuid32", - "setreuid", - "setreuid32", - "setrlimit", - "set_robust_list", - "setsid", - "setsockopt", - "set_thread_area", - "set_tid_address", - "setuid", - "setuid32", - "setxattr", - "shmat", - "shmctl", - "shmdt", - "shmget", - "shutdown", - "sigaltstack", - "signalfd", - "signalfd4", - "sigreturn", - "socket", - "socketcall", - "socketpair", - "splice", - "stat", - "stat64", - "statfs", - "statfs64", - "statx", - "symlink", - "symlinkat", - "sync", - "sync_file_range", - "syncfs", - "sysinfo", - "syslog", - "tee", - "tgkill", - "time", - "timer_create", - "timer_delete", - "timerfd_create", - "timerfd_gettime", - "timerfd_settime", - "timer_getoverrun", - "timer_gettime", - "timer_settime", - "times", - "tkill", - "truncate", - "truncate64", - "ugetrlimit", - "umask", - "uname", - "unlink", - "unlinkat", - "utime", - "utimensat", - "utimes", - "vfork", - "vmsplice", - "wait4", - "waitid", - "waitpid", - "write", - "writev", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - { - Names: []string{"personality"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{ - { - Index: 0, - Value: 0x0, - Op: rspec.OpEqualTo, - }, - }, - }, - { - Names: []string{"personality"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{ - { - Index: 0, - Value: 0x0008, - Op: rspec.OpEqualTo, - }, - }, - }, - { - Names: []string{"personality"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{ - { - Index: 0, - Value: 0xffffffff, - Op: rspec.OpEqualTo, - }, - }, - }, - } - var sysCloneFlagsIndex uint - - capSysAdmin := false - caps := make(map[string]bool) - - for _, cap := range rs.Process.Capabilities.Bounding { - caps[cap] = true - } - for _, cap := range rs.Process.Capabilities.Effective { - caps[cap] = true - } - for _, cap := range rs.Process.Capabilities.Inheritable { - caps[cap] = true - } - for _, cap := range rs.Process.Capabilities.Permitted { - caps[cap] = true - } - for _, cap := range rs.Process.Capabilities.Ambient { - caps[cap] = true - } - - for cap := range caps { - switch cap { - case "CAP_DAC_READ_SEARCH": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"open_by_handle_at"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_ADMIN": - capSysAdmin = true - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "bpf", - "clone", - "fanotify_init", - "lookup_dcookie", - "mount", - "name_to_handle_at", - "perf_event_open", - "setdomainname", - "sethostname", - "setns", - "umount", - "umount2", - "unshare", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_BOOT": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"reboot"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_CHROOT": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"chroot"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_MODULE": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "delete_module", - "init_module", - "finit_module", - "query_module", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_PACCT": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"acct"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_PTRACE": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "kcmp", - "process_vm_readv", - "process_vm_writev", - "ptrace", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_RAWIO": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "iopl", - "ioperm", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_TIME": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "settimeofday", - "stime", - "adjtimex", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "CAP_SYS_TTY_CONFIG": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"vhangup"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - } - } - - if !capSysAdmin { - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"clone"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{ - { - Index: sysCloneFlagsIndex, - Value: CloneNewNS | CloneNewUTS | CloneNewIPC | CloneNewUser | CloneNewPID | CloneNewNet | CloneNewCgroup, - ValueTwo: 0, - Op: rspec.OpMaskedEqual, - }, - }, - }, - }...) - } - - arch := runtime.GOARCH - switch arch { - case "arm", "arm64": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "breakpoint", - "cacheflush", - "set_tls", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "amd64", "x32": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"arch_prctl"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - fallthrough - case "x86": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"modify_ldt"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - case "s390", "s390x": - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{ - "s390_pci_mmio_read", - "s390_pci_mmio_write", - "s390_runtime_instr", - }, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{}, - }, - }...) - /* Flags parameter of the clone syscall is the 2nd on s390 */ - syscalls = append(syscalls, []rspec.LinuxSyscall{ - { - Names: []string{"clone"}, - Action: rspec.ActAllow, - Args: []rspec.LinuxSeccompArg{ - { - Index: 1, - Value: 2080505856, - ValueTwo: 0, - Op: rspec.OpMaskedEqual, - }, - }, - }, - }...) - } - - return &rspec.LinuxSeccomp{ - DefaultAction: rspec.ActErrno, - Architectures: arches(), - Syscalls: syscalls, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go deleted file mode 100644 index aac5c2bbe0..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build linux - -package seccomp - -import "golang.org/x/sys/unix" - -// System values passed through on linux -const ( - CloneNewIPC = unix.CLONE_NEWIPC - CloneNewNet = unix.CLONE_NEWNET - CloneNewNS = unix.CLONE_NEWNS - CloneNewPID = unix.CLONE_NEWPID - CloneNewUser = unix.CLONE_NEWUSER - CloneNewUTS = unix.CLONE_NEWUTS - CloneNewCgroup = unix.CLONE_NEWCGROUP -) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go deleted file mode 100644 index a8d582672c..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build !linux - -package seccomp - -// These are copied from linux/amd64 syscall values, as a reference for other -// platforms to have access to -const ( - CloneNewIPC = 0x8000000 - CloneNewNet = 0x40000000 - CloneNewNS = 0x20000 - CloneNewPID = 0x20000000 - CloneNewUser = 0x10000000 - CloneNewUTS = 0x4000000 - CloneNewCgroup = 0x02000000 -) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go deleted file mode 100644 index 5e84653a94..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go +++ /dev/null @@ -1,124 +0,0 @@ -package seccomp - -import ( - "fmt" - "reflect" - "strconv" - "strings" - - rspec "github.com/opencontainers/runtime-spec/specs-go" -) - -// Determine if a new syscall rule should be appended, overwrite an existing rule -// or if no action should be taken at all -func decideCourseOfAction(newSyscall *rspec.LinuxSyscall, syscalls []rspec.LinuxSyscall) (string, error) { - ruleForSyscallAlreadyExists := false - - var sliceOfDeterminedActions []string - for i, syscall := range syscalls { - if sameName(&syscall, newSyscall) { - ruleForSyscallAlreadyExists = true - - if identical(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing) - } - - if sameAction(newSyscall, &syscall) { - if bothHaveArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) - } - if onlyOneHasArgs(newSyscall, &syscall) { - if firstParamOnlyHasArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) - } else { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing) - } - } - } - - if !sameAction(newSyscall, &syscall) { - if bothHaveArgs(newSyscall, &syscall) { - if sameArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) - } - if !sameArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) - } - } - if onlyOneHasArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) - } - if neitherHasArgs(newSyscall, &syscall) { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) - } - } - } - } - - if !ruleForSyscallAlreadyExists { - sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) - } - - // Nothing has highest priority - for _, determinedAction := range sliceOfDeterminedActions { - if determinedAction == nothing { - return determinedAction, nil - } - } - - // Overwrite has second highest priority - for _, determinedAction := range sliceOfDeterminedActions { - if strings.Contains(determinedAction, seccompOverwrite) { - return determinedAction, nil - } - } - - // Append has the lowest priority - for _, determinedAction := range sliceOfDeterminedActions { - if determinedAction == seccompAppend { - return determinedAction, nil - } - } - - return "", fmt.Errorf("Trouble determining action: %s", sliceOfDeterminedActions) -} - -func hasArguments(config *rspec.LinuxSyscall) bool { - nilSyscall := new(rspec.LinuxSyscall) - return !sameArgs(nilSyscall, config) -} - -func identical(config1, config2 *rspec.LinuxSyscall) bool { - return reflect.DeepEqual(config1, config2) -} - -func sameName(config1, config2 *rspec.LinuxSyscall) bool { - return reflect.DeepEqual(config1.Names, config2.Names) -} - -func sameAction(config1, config2 *rspec.LinuxSyscall) bool { - return config1.Action == config2.Action -} - -func sameArgs(config1, config2 *rspec.LinuxSyscall) bool { - return reflect.DeepEqual(config1.Args, config2.Args) -} - -func bothHaveArgs(config1, config2 *rspec.LinuxSyscall) bool { - return hasArguments(config1) && hasArguments(config2) -} - -func onlyOneHasArgs(config1, config2 *rspec.LinuxSyscall) bool { - conf1 := hasArguments(config1) - conf2 := hasArguments(config2) - - return (conf1 && !conf2) || (!conf1 && conf2) -} - -func neitherHasArgs(config1, config2 *rspec.LinuxSyscall) bool { - return !hasArguments(config1) && !hasArguments(config2) -} - -func firstParamOnlyHasArgs(config1, config2 *rspec.LinuxSyscall) bool { - return !hasArguments(config1) && hasArguments(config2) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/lastcap.go b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/lastcap.go deleted file mode 100644 index 092795726d..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/lastcap.go +++ /dev/null @@ -1,16 +0,0 @@ -package capabilities - -import ( - "github.com/moby/sys/capability" -) - -// LastCap returns last cap of system. -// -// Deprecated: use github.com/moby/sys/capability.LastCap instead. -func LastCap() capability.Cap { - last, err := capability.LastCap() - if err != nil { - return -1 - } - return last -} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go deleted file mode 100644 index 572e70810b..0000000000 --- a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go +++ /dev/null @@ -1,45 +0,0 @@ -package capabilities - -import ( - "fmt" - "strings" - "sync" - - "github.com/moby/sys/capability" -) - -// CapValid checks whether a capability is valid. If hostSpecific is set, -// it also checks that the capability is supported on the current host. -func CapValid(c string, hostSpecific bool) error { - if !strings.HasPrefix(c, "CAP_") { - return fmt.Errorf("capability %s must start with CAP_", c) - } - - if _, ok := knownCaps()[c]; !ok { - return fmt.Errorf("invalid capability: %s", c) - } - if !hostSpecific { - return nil - } - if _, ok := supportedCaps()[c]; !ok { - return fmt.Errorf("%s is not supported on the current host", c) - } - return nil -} - -func capSet(list []capability.Cap) map[string]struct{} { - m := make(map[string]struct{}, len(list)) - for _, c := range list { - m["CAP_"+strings.ToUpper(c.String())] = struct{}{} - } - return m -} - -var knownCaps = sync.OnceValue(func() map[string]struct{} { - return capSet(capability.ListKnown()) -}) - -var supportedCaps = sync.OnceValue(func() map[string]struct{} { - list, _ := capability.ListSupported() - return capSet(list) -}) diff --git a/vendor/modules.txt b/vendor/modules.txt index b960dd1b5c..5ab74d79fe 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -405,8 +405,6 @@ github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities -# github.com/hashicorp/errwrap v1.1.0 -## explicit # github.com/intel/goresctrl v0.13.0 ## explicit; go 1.25.0 github.com/intel/goresctrl/pkg/blockio @@ -451,9 +449,6 @@ github.com/moby/locker ## explicit; go 1.13 github.com/moby/spdystream github.com/moby/spdystream/spdy -# github.com/moby/sys/capability v0.4.0 -## explicit; go 1.21 -github.com/moby/sys/capability # github.com/moby/sys/mountinfo v0.7.2 ## explicit; go 1.17 github.com/moby/sys/mountinfo @@ -491,11 +486,6 @@ github.com/opencontainers/image-spec/specs-go/v1 ## explicit github.com/opencontainers/runtime-spec/specs-go github.com/opencontainers/runtime-spec/specs-go/features -# github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 -## explicit; go 1.21 -github.com/opencontainers/runtime-tools/generate -github.com/opencontainers/runtime-tools/generate/seccomp -github.com/opencontainers/runtime-tools/validate/capabilities # github.com/opencontainers/selinux v1.15.1 ## explicit; go 1.22 github.com/opencontainers/selinux/go-selinux @@ -1038,8 +1028,9 @@ sigs.k8s.io/structured-merge-diff/v6/value # sigs.k8s.io/yaml v1.6.0 ## explicit; go 1.22 sigs.k8s.io/yaml -# tags.cncf.io/container-device-interface v1.1.0 +# tags.cncf.io/container-device-interface v1.1.1-0.20260720132747-49ac08dcf160 ## explicit; go 1.21 +tags.cncf.io/container-device-interface/internal/ociedit tags.cncf.io/container-device-interface/internal/validation tags.cncf.io/container-device-interface/internal/validation/k8s tags.cncf.io/container-device-interface/pkg/cdi diff --git a/vendor/tags.cncf.io/container-device-interface/internal/ociedit/spec_editor.go b/vendor/tags.cncf.io/container-device-interface/internal/ociedit/spec_editor.go new file mode 100644 index 0000000000..28e97e5bf2 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/internal/ociedit/spec_editor.go @@ -0,0 +1,247 @@ +/* + Copyright 2026 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package ociedit + +import ( + "errors" + "slices" + "strings" + + oci "github.com/opencontainers/runtime-spec/specs-go" +) + +// SpecEditor is the internal boundary between CDI edits and OCI spec mutation. +// It deliberately models only the operations CDI needs, so a future external +// generator can be wired in without leaking that dependency elsewhere. +type SpecEditor interface { + AddMultipleProcessEnv([]string) + RemoveDevice(string) + AddDevice(oci.LinuxDevice) + AddLinuxResourcesDevice(bool, string, *int64, *int64, string) + SetLinuxNetDevice(string, *oci.LinuxNetDevice) + RemoveMount(string) + AddMount(oci.Mount) + Mounts() []oci.Mount + SetMounts([]oci.Mount) + AddPreStartHook(oci.Hook) + AddPostStartHook(oci.Hook) + AddPostStopHook(oci.Hook) + AddCreateRuntimeHook(oci.Hook) + AddCreateContainerHook(oci.Hook) + AddStartContainerHook(oci.Hook) + SetLinuxIntelRdt(*oci.LinuxIntelRdt) + AddProcessAdditionalGID(uint32) + ClearLinuxDevices() +} + +// NewSpecEditor returns CDI's native OCI spec editor. +func NewSpecEditor(spec *oci.Spec) (SpecEditor, error) { + if spec == nil { + return nil, errors.New("can't edit nil OCI Spec") + } + + envCache := map[string]int{} + if spec.Process != nil { + envCache = createEnvCacheMap(spec.Process.Env) + } + return &nativeSpecEditor{ + spec: spec, + envMap: envCache, + }, nil +} + +type nativeSpecEditor struct { + spec *oci.Spec + envMap map[string]int +} + +func createEnvCacheMap(env []string) map[string]int { + envMap := make(map[string]int, len(env)) + for i, val := range env { + val, _, _ = strings.Cut(val, "=") + envMap[val] = i + } + return envMap +} + +func (e *nativeSpecEditor) initProcess() { + if e.spec.Process == nil { + e.spec.Process = &oci.Process{} + } +} + +func (e *nativeSpecEditor) initHooks() { + if e.spec.Hooks == nil { + e.spec.Hooks = &oci.Hooks{} + } +} + +func (e *nativeSpecEditor) initLinux() { + if e.spec.Linux == nil { + e.spec.Linux = &oci.Linux{} + } +} + +func (e *nativeSpecEditor) initLinuxResources() { + e.initLinux() + if e.spec.Linux.Resources == nil { + e.spec.Linux.Resources = &oci.LinuxResources{} + } +} + +func (e *nativeSpecEditor) initLinuxNetDevices() { + e.initLinux() + if e.spec.Linux.NetDevices == nil { + e.spec.Linux.NetDevices = map[string]oci.LinuxNetDevice{} + } +} + +func (e *nativeSpecEditor) AddMultipleProcessEnv(envs []string) { + e.initProcess() + + for _, val := range envs { + key, _, _ := strings.Cut(val, "=") + e.addEnv(val, key) + } +} + +func (e *nativeSpecEditor) addEnv(env, key string) { + if idx, ok := e.envMap[key]; ok { + e.spec.Process.Env[idx] = env + return + } + + e.spec.Process.Env = append(e.spec.Process.Env, env) + e.envMap[key] = len(e.spec.Process.Env) - 1 +} + +func (e *nativeSpecEditor) RemoveDevice(path string) { + if e.spec == nil || e.spec.Linux == nil || e.spec.Linux.Devices == nil { + return + } + + for i, device := range e.spec.Linux.Devices { + if device.Path == path { + e.spec.Linux.Devices = append(e.spec.Linux.Devices[:i], e.spec.Linux.Devices[i+1:]...) + return + } + } +} + +func (e *nativeSpecEditor) AddDevice(device oci.LinuxDevice) { + e.initLinux() + + for i, dev := range e.spec.Linux.Devices { + if dev.Path == device.Path { + e.spec.Linux.Devices[i] = device + return + } + } + + e.spec.Linux.Devices = append(e.spec.Linux.Devices, device) +} + +func (e *nativeSpecEditor) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + e.initLinuxResources() + e.spec.Linux.Resources.Devices = append(e.spec.Linux.Resources.Devices, oci.LinuxDeviceCgroup{ + Allow: allow, + Type: devType, + Major: major, + Minor: minor, + Access: access, + }) +} + +func (e *nativeSpecEditor) SetLinuxNetDevice(hostIf string, netDev *oci.LinuxNetDevice) { + if netDev == nil { + return + } + + e.initLinuxNetDevices() + e.spec.Linux.NetDevices[hostIf] = *netDev +} + +func (e *nativeSpecEditor) RemoveMount(dest string) { + for i, mount := range e.spec.Mounts { + if mount.Destination == dest { + e.spec.Mounts = append(e.spec.Mounts[:i], e.spec.Mounts[i+1:]...) + return + } + } +} + +func (e *nativeSpecEditor) AddMount(mnt oci.Mount) { + e.spec.Mounts = append(e.spec.Mounts, mnt) +} + +func (e *nativeSpecEditor) Mounts() []oci.Mount { + return e.spec.Mounts +} + +func (e *nativeSpecEditor) SetMounts(mounts []oci.Mount) { + e.spec.Mounts = mounts +} + +func (e *nativeSpecEditor) AddPreStartHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.Prestart = append(e.spec.Hooks.Prestart, hook) //nolint:staticcheck // CDI still supports OCI prestart hooks. +} + +func (e *nativeSpecEditor) AddPostStartHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.Poststart = append(e.spec.Hooks.Poststart, hook) +} + +func (e *nativeSpecEditor) AddPostStopHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.Poststop = append(e.spec.Hooks.Poststop, hook) +} + +func (e *nativeSpecEditor) AddCreateRuntimeHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.CreateRuntime = append(e.spec.Hooks.CreateRuntime, hook) +} + +func (e *nativeSpecEditor) AddCreateContainerHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.CreateContainer = append(e.spec.Hooks.CreateContainer, hook) +} + +func (e *nativeSpecEditor) AddStartContainerHook(hook oci.Hook) { + e.initHooks() + e.spec.Hooks.StartContainer = append(e.spec.Hooks.StartContainer, hook) +} + +func (e *nativeSpecEditor) SetLinuxIntelRdt(rdt *oci.LinuxIntelRdt) { + e.initLinux() + e.spec.Linux.IntelRdt = rdt +} + +func (e *nativeSpecEditor) AddProcessAdditionalGID(gid uint32) { + e.initProcess() + if slices.Contains(e.spec.Process.User.AdditionalGids, gid) { + return + } + e.spec.Process.User.AdditionalGids = append(e.spec.Process.User.AdditionalGids, gid) +} + +func (e *nativeSpecEditor) ClearLinuxDevices() { + if e.spec == nil || e.spec.Linux == nil || e.spec.Linux.Devices == nil { + return + } + e.spec.Linux.Devices = []oci.LinuxDevice{} +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go index f498049c6e..1971e1f142 100644 --- a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go @@ -25,7 +25,7 @@ import ( "strings" oci "github.com/opencontainers/runtime-spec/specs-go" - ocigen "github.com/opencontainers/runtime-tools/generate" + "tags.cncf.io/container-device-interface/internal/ociedit" cdi "tags.cncf.io/container-device-interface/specs-go" ) @@ -42,6 +42,9 @@ const ( PoststartHook = "poststart" // PoststopHook is the name of the OCI "poststop" hook. PoststopHook = "poststop" + + // NoPermissions requests empty cgroup permissions for a device. + NoPermissions = "none" ) var ( @@ -77,9 +80,12 @@ func (e *ContainerEdits) Apply(spec *oci.Spec) error { return nil } - specgen := ocigen.NewFromSpec(spec) + editor, err := ociedit.NewSpecEditor(spec) + if err != nil { + return fmt.Errorf("error creating spec editor: %w", err) + } if len(e.Env) > 0 { - specgen.AddMultipleProcessEnv(e.Env) + editor.AddMultipleProcessEnv(e.Env) } for _, d := range e.DeviceNodes { @@ -101,93 +107,76 @@ func (e *ContainerEdits) Apply(spec *oci.Spec) error { } } - specgen.RemoveDevice(dev.Path) - specgen.AddDevice(dev) + editor.RemoveDevice(dev.Path) + editor.AddDevice(dev) if dev.Type == "b" || dev.Type == "c" { access := d.Permissions - if access == "" { + switch access { + case "": access = "rwm" + case NoPermissions: + access = "" } - specgen.AddLinuxResourcesDevice(true, dev.Type, &dev.Major, &dev.Minor, access) + editor.AddLinuxResourcesDevice(true, dev.Type, &dev.Major, &dev.Minor, access) } } if len(e.NetDevices) > 0 { - // specgen is currently missing functionality to set Linux NetDevices, - // so we use a locally rolled function for now. for _, dev := range e.NetDevices { - specgenAddLinuxNetDevice(&specgen, dev.HostInterfaceName, (&LinuxNetDevice{dev}).toOCI()) + editor.SetLinuxNetDevice(dev.HostInterfaceName, (&LinuxNetDevice{dev}).toOCI()) } } if len(e.Mounts) > 0 { for _, m := range e.Mounts { - specgen.RemoveMount(m.ContainerPath) - specgen.AddMount((&Mount{m}).toOCI()) + mnt := &Mount{m} + + editor.RemoveMount(m.ContainerPath) + + if !specHasUserNamespace(spec) { + editor.AddMount(mnt.toOCI()) + } else { + editor.AddMount(mnt.toOCI(withIDMapForBindMount())) + } } - sortMounts(&specgen) + sortMounts(editor) } for _, h := range e.Hooks { ociHook := (&Hook{h}).toOCI() switch h.HookName { case PrestartHook: - specgen.AddPreStartHook(ociHook) + editor.AddPreStartHook(ociHook) case PoststartHook: - specgen.AddPostStartHook(ociHook) + editor.AddPostStartHook(ociHook) case PoststopHook: - specgen.AddPostStopHook(ociHook) - // TODO: Maybe runtime-tools/generate should be updated with these... + editor.AddPostStopHook(ociHook) case CreateRuntimeHook: - ensureOCIHooks(spec) - spec.Hooks.CreateRuntime = append(spec.Hooks.CreateRuntime, ociHook) + editor.AddCreateRuntimeHook(ociHook) case CreateContainerHook: - ensureOCIHooks(spec) - spec.Hooks.CreateContainer = append(spec.Hooks.CreateContainer, ociHook) + editor.AddCreateContainerHook(ociHook) case StartContainerHook: - ensureOCIHooks(spec) - spec.Hooks.StartContainer = append(spec.Hooks.StartContainer, ociHook) + editor.AddStartContainerHook(ociHook) default: return fmt.Errorf("unknown hook name %q", h.HookName) } } if e.IntelRdt != nil { - // The specgen is missing functionality to set all parameters so we - // just piggy-back on it to initialize all structs and the copy over. - specgen.SetLinuxIntelRdtClosID(e.IntelRdt.ClosID) - spec.Linux.IntelRdt = (&IntelRdt{e.IntelRdt}).toOCI() + editor.SetLinuxIntelRdt((&IntelRdt{e.IntelRdt}).toOCI()) } for _, additionalGID := range e.AdditionalGIDs { if additionalGID == 0 { continue } - specgen.AddProcessAdditionalGid(additionalGID) + editor.AddProcessAdditionalGID(additionalGID) } return nil } -func specgenAddLinuxNetDevice(specgen *ocigen.Generator, hostIf string, netDev *oci.LinuxNetDevice) { - if specgen == nil || netDev == nil { - return - } - ensureLinuxNetDevices(specgen.Config) - specgen.Config.Linux.NetDevices[hostIf] = *netDev -} - -// Ensure OCI Spec Linux NetDevices map is not nil. -func ensureLinuxNetDevices(spec *oci.Spec) { - if spec.Linux == nil { - spec.Linux = &oci.Linux{} - } - if spec.Linux.NetDevices == nil { - spec.Linux.NetDevices = map[string]oci.LinuxNetDevice{} - } -} - // Validate container edits. func (e *ContainerEdits) Validate() error { if e == nil || e.ContainerEdits == nil { @@ -354,12 +343,14 @@ func (d *DeviceNode) Validate() error { if _, ok := validTypes[d.Type]; !ok { return fmt.Errorf("device %q: invalid type %q", d.Path, d.Type) } - for _, bit := range d.Permissions { - if bit != 'r' && bit != 'w' && bit != 'm' { - return fmt.Errorf("device %q: invalid permissions %q", - d.Path, d.Permissions) - } + switch { + case d.Permissions == "": + case d.Permissions == NoPermissions: + case strings.Trim(d.Permissions, "rwm") != "": + return fmt.Errorf("device %q: invalid permissions %q", + d.Path, d.Permissions) } + return nil } @@ -422,19 +413,11 @@ func (i *IntelRdt) Validate() error { return nil } -// Ensure OCI Spec hooks are not nil so we can add hooks. -func ensureOCIHooks(spec *oci.Spec) { - if spec.Hooks == nil { - spec.Hooks = &oci.Hooks{} - } -} - // sortMounts sorts the mounts in the given OCI Spec. -func sortMounts(specgen *ocigen.Generator) { - mounts := specgen.Mounts() - specgen.ClearMounts() +func sortMounts(editor ociedit.SpecEditor) { + mounts := editor.Mounts() sort.Stable(orderedMounts(mounts)) - specgen.Config.Mounts = mounts + editor.SetMounts(mounts) } // orderedMounts defines how to sort an OCI Spec Mount slice. @@ -465,3 +448,16 @@ func (m orderedMounts) Swap(i, j int) { func (m orderedMounts) parts(i int) int { return strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator)) } + +// specHasUserNamespace returns true if the OCI Spec has a Linux UserNamespace. +func specHasUserNamespace(spec *oci.Spec) bool { + if spec == nil || spec.Linux == nil { + return false + } + for _, ns := range spec.Linux.Namespaces { + if ns.Type == oci.UserNamespace { + return true + } + } + return false +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go index f37499fcf2..68ffafe9e6 100644 --- a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go @@ -30,14 +30,46 @@ func (h *Hook) toOCI() spec.Hook { } } +// Additional OCI mount option to apply to injected mounts. +type ociMountOption func(*spec.Mount) + +// withIDMapForBindMount adds any necessary ID mapping options for a bind mount. +func withIDMapForBindMount() ociMountOption { + return func(m *spec.Mount) { + option := "" + if m.Type == "bind" { + option = "idmap" + } + + for _, o := range m.Options { + switch o { + case "idmap", "ridmap": + return + case "bind": + option = "idmap" + case "rbind": + option = "ridmap" + } + } + + if option != "" { + m.Options = append(m.Options, option) + } + } +} + // toOCI returns the opencontainers runtime Spec Mount for this Mount. -func (m *Mount) toOCI() spec.Mount { - return spec.Mount{ +func (m *Mount) toOCI(options ...ociMountOption) spec.Mount { + om := spec.Mount{ Source: m.HostPath, Destination: m.ContainerPath, Options: m.Options, Type: m.Type, } + for _, o := range options { + o(&om) + } + return om } // toOCI returns the opencontainers runtime Spec LinuxDevice for this DeviceNode. diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go index b192f962c8..df64c21972 100644 --- a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go @@ -43,6 +43,10 @@ var ( // WithSpecDirs returns an option to override the CDI Spec directories. func WithSpecDirs(dirs ...string) Option { + // If no spec dirs are specified use the default spec dirs. + if len(dirs) == 0 { + return WithSpecDirs(DefaultSpecDirs...) + } return func(c *Cache) { specDirs := make([]string, len(dirs)) for i, dir := range dirs { diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go b/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go index 5325989541..6a3aedd1fe 100644 --- a/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go +++ b/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go @@ -150,6 +150,9 @@ func validateVendorOrClassName(name string) error { if !IsLetter(rune(name[0])) { return fmt.Errorf("%q, should start with letter", name) } + if len(name) == 1 { + return nil + } for _, c := range string(name[1 : len(name)-1]) { switch { case IsAlphaNumeric(c):