diff --git a/Makefile b/Makefile index 41e80d32c2a..a2d0bb3fae0 100644 --- a/Makefile +++ b/Makefile @@ -80,8 +80,6 @@ ifeq ($(NATIVE_GOOS),freebsd) SED=gsed GREP=ggrep MAN_L= mandoc -# FreeBSD needs CNI until netavark is supported -BUILDTAGS += cni else SED=sed GREP=grep diff --git a/cmd/rootlessport/main.go b/cmd/rootlessport/main.go index 107f5403e74..f60a321640c 100644 --- a/cmd/rootlessport/main.go +++ b/cmd/rootlessport/main.go @@ -14,12 +14,12 @@ import ( "path/filepath" "strings" - "github.com/containernetworking/plugins/pkg/ns" rkport "github.com/rootless-containers/rootlesskit/v2/pkg/port" rkbuiltin "github.com/rootless-containers/rootlesskit/v2/pkg/port/builtin" rkportutil "github.com/rootless-containers/rootlesskit/v2/pkg/port/portutil" "github.com/sirupsen/logrus" "go.podman.io/common/libnetwork/types" + "go.podman.io/common/pkg/netns" "go.podman.io/common/pkg/rootlessport" "golang.org/x/sys/unix" ) @@ -137,11 +137,11 @@ func parent() error { cmd.Stdout = &logrusWriter{prefix: "child"} cmd.Stderr = cmd.Stdout cmd.Env = append(os.Environ(), reexecChildEnvOpaque+"="+string(opaqueJSON)) - childNS, err := ns.GetNS(cfg.NetNSPath) + childNS, err := netns.GetNS(cfg.NetNSPath) if err != nil { return err } - if err := childNS.Do(func(_ ns.NetNS) error { + if err := childNS.Do(func(_ netns.NetNS) error { logrus.Infof("Starting child driver in child netns (%q %v)", cmd.Path, cmd.Args) return cmd.Start() }); err != nil { @@ -194,7 +194,8 @@ outer: return err } - // we only need to have a socket to reload ports when we run under rootless cni + // we only need to have a socket to reload ports when we are using + // rootless bridge networking (RootlessCNI is set when netStatus != nil) if cfg.RootlessCNI { socketfile := filepath.Join(socketDir, cfg.ContainerID) // make sure to remove the file if it exists to prevent EADDRINUSE diff --git a/contrib/tmpfile/podman.conf b/contrib/tmpfile/podman.conf index afb3d5bb2b6..42fe0ca3f58 100644 --- a/contrib/tmpfile/podman.conf +++ b/contrib/tmpfile/podman.conf @@ -13,7 +13,6 @@ x /tmp/run-*/libpod R! /tmp/run-*/libpod D! /var/lib/containers/storage/tmp 0700 root root D! /run/podman 0700 root root -D! /var/lib/cni/networks # Remove /var/tmp/container_images* podman temporary directories on each # boot which are created when pulling or saving images. R! /var/tmp/container_images* diff --git a/go.mod b/go.mod index cffc27fd75e..08f2408fa16 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,13 @@ module github.com/containers/podman/v6 // Warning: if there is a "toolchain" directive anywhere in this file (and most of the // time there shouldn't be), its version must be an exact match to the "go" directive. -go 1.25.0 +go 1.25.5 require ( github.com/Microsoft/go-winio v0.6.2 github.com/blang/semver/v4 v4.0.0 github.com/checkpoint-restore/checkpointctl v1.5.0 github.com/checkpoint-restore/go-criu/v7 v7.2.0 - github.com/containernetworking/plugins v1.9.0 github.com/containers/buildah v1.42.1-0.20260216192603-e473f9d26ec6 github.com/containers/gvisor-tap-vsock v0.8.8 github.com/containers/libhvee v0.10.1-0.20250829163521-178d10e67860 @@ -65,9 +64,9 @@ require ( github.com/stretchr/testify v1.11.1 github.com/vbauerster/mpb/v8 v8.12.0 github.com/vishvananda/netlink v1.3.1 - go.podman.io/common v0.67.1-0.20260313003550-7415b6a27ee6 - go.podman.io/image/v5 v5.39.2-0.20260313003550-7415b6a27ee6 - go.podman.io/storage v1.62.1-0.20260313003550-7415b6a27ee6 + go.podman.io/common v0.67.1-0.20260316162257-e70c309aabae + go.podman.io/image/v5 v5.39.2-0.20260316162257-e70c309aabae + go.podman.io/storage v1.62.1-0.20260316162257-e70c309aabae golang.org/x/crypto v0.49.0 golang.org/x/net v0.51.0 golang.org/x/sync v0.20.0 @@ -82,7 +81,7 @@ require ( ) require ( - cyphar.com/go-pathrs v0.2.1 // indirect + cyphar.com/go-pathrs v0.2.4 // indirect dario.cat/mergo v1.0.2 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/BurntSushi/toml v1.6.0 // indirect @@ -99,23 +98,22 @@ require ( github.com/containerd/platforms v1.0.0-rc.2 // indirect github.com/containerd/stargz-snapshotter/estargz v0.18.2 // indirect github.com/containerd/typeurl/v2 v2.2.3 // indirect - github.com/containernetworking/cni v1.3.0 // indirect + github.com/containernetworking/plugins v1.9.0 // indirect github.com/containers/common v0.64.2 // indirect github.com/containers/libtrust v0.0.0-20230121012942-c1716e8a8d01 // indirect github.com/containers/luksy v0.0.0-20251208191447-ca096313c38f // indirect - github.com/coreos/go-oidc/v3 v3.16.0 // indirect + github.com/coreos/go-oidc/v3 v3.17.0 // indirect github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect github.com/cyberphone/json-canonicalization v0.0.0-20241213102144-19d51d7fe467 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/digitalocean/go-libvirt v0.0.0-20220804181439-8648fbde413e // indirect github.com/disiqueira/gotree/v3 v3.0.2 // indirect github.com/distribution/reference v0.6.0 // indirect - github.com/docker/docker v28.5.2+incompatible // indirect github.com/docker/docker-credential-helpers v0.9.5 // indirect github.com/ebitengine/purego v0.10.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/fsouza/go-dockerclient v1.12.3 // indirect + github.com/fsouza/go-dockerclient v1.13.0 // indirect github.com/go-jose/go-jose/v4 v4.1.3 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -124,7 +122,7 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/go-containerregistry v0.20.6 // indirect + github.com/google/go-containerregistry v0.20.7 // indirect github.com/google/go-intervals v0.0.2 // indirect github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect @@ -139,16 +137,16 @@ require ( github.com/mdlayher/socket v0.5.1 // indirect github.com/miekg/pkcs11 v1.1.1 // indirect github.com/mistifyio/go-zfs/v4 v4.0.0 // indirect - github.com/moby/buildkit v0.26.3 // indirect - github.com/moby/go-archive v0.1.0 // indirect + github.com/moby/buildkit v0.28.0 // indirect + github.com/moby/go-archive v0.2.0 // indirect + github.com/moby/moby/v2 v2.0.0-beta.6 // indirect github.com/moby/patternmatcher v0.6.0 // indirect github.com/moby/sys/mountinfo v0.7.2 // indirect github.com/moby/sys/sequential v0.6.0 // indirect github.com/moby/sys/userns v0.1.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/morikuni/aec v1.0.0 // indirect - github.com/opencontainers/runc v1.4.0 // indirect + github.com/opencontainers/runc v1.4.1 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pkg/sftp v1.13.10 // indirect @@ -158,9 +156,9 @@ require ( github.com/proglottis/gpgme v0.1.6 // indirect github.com/seccomp/libseccomp-golang v0.11.1 // indirect github.com/secure-systems-lab/go-securesystemslib v0.10.0 // indirect - github.com/sigstore/fulcio v1.8.1 // indirect + github.com/sigstore/fulcio v1.8.5 // indirect github.com/sigstore/protobuf-specs v0.5.0 // indirect - github.com/sigstore/sigstore v1.9.6-0.20251111174640-d8ab8afb1326 // indirect + github.com/sigstore/sigstore v1.10.4 // indirect github.com/skeema/knownhosts v1.3.2 // indirect github.com/smallstep/pkcs7 v0.1.1 // indirect github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect @@ -190,3 +188,5 @@ require ( gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect tags.cncf.io/container-device-interface/specs-go v1.1.0 // indirect ) + +replace github.com/containers/buildah => github.com/lsm5/buildah v0.0.0-20260317084505-caaea7f2d096 diff --git a/go.sum b/go.sum index 1a7a2915919..e143a8daf4e 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cyphar.com/go-pathrs v0.2.1 h1:9nx1vOgwVvX1mNBWDu93+vaceedpbsDqo+XuBGL40b8= -cyphar.com/go-pathrs v0.2.1/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc= +cyphar.com/go-pathrs v0.2.4 h1:iD/mge36swa1UFKdINkr1Frkpp6wZsy3YYEildj9cLY= +cyphar.com/go-pathrs v0.2.4/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc= dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= @@ -55,8 +55,6 @@ github.com/containernetworking/cni v1.3.0 h1:v6EpN8RznAZj9765HhXQrtXgX+ECGebEYEm github.com/containernetworking/cni v1.3.0/go.mod h1:Bs8glZjjFfGPHMw6hQu82RUgEPNGEaBb9KS5KtNMnJ4= github.com/containernetworking/plugins v1.9.0 h1:Mg3SXBdRGkdXyFC4lcwr6u2ZB2SDeL6LC3U+QrEANuQ= github.com/containernetworking/plugins v1.9.0/go.mod h1:JG3BxoJifxxHBhG3hFyxyhid7JgRVBu/wtooGEvWf1c= -github.com/containers/buildah v1.42.1-0.20260216192603-e473f9d26ec6 h1:j8qnAjmrLf6x47qChpQZla1JzdMZ2BEmhTFlE0e9EUU= -github.com/containers/buildah v1.42.1-0.20260216192603-e473f9d26ec6/go.mod h1:rnvz1cLM9/wTR4BYODd62GHIwTrWzQsn5J1+qEbjgJ8= github.com/containers/common v0.64.2 h1:1xepE7QwQggUXxmyQ1Dbh6Cn0yd7ktk14sN3McSWf5I= github.com/containers/common v0.64.2/go.mod h1:o29GfYy4tefUuShm8mOn2AiL5Mpzdio+viHI7n24KJ4= github.com/containers/gvisor-tap-vsock v0.8.8 h1:5FznbOYMIuaCv8B6zQ7M6wjqP63Lasy0A6GpViEnjTg= @@ -73,8 +71,8 @@ github.com/containers/psgo v1.10.0 h1:r9cEzAMVRtC0sw4ayIPjbd9EgF9pPaTCqKgDHhS0D/ github.com/containers/psgo v1.10.0/go.mod h1:e44fw+1A7eJH1y0eWAo3P7sjfftXDlfF4AY498h+svQ= github.com/containers/winquit v1.1.0 h1:jArun04BNDQvt2W0Y78kh9TazN2EIEMG5Im6/JY7+pE= github.com/containers/winquit v1.1.0/go.mod h1:PsPeZlnbkmGGIToMPHF1zhWjBUkd8aHjMOr/vFcPxw8= -github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow= -github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= +github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc= +github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= @@ -104,8 +102,6 @@ github.com/docker/cli v29.3.0+incompatible h1:z3iWveU7h19Pqx7alZES8j+IeFQZ1lhTwb github.com/docker/cli v29.3.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM= -github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker-credential-helpers v0.9.5 h1:EFNN8DHvaiK8zVqFA2DT6BjXE0GzfLOZ38ggPTKePkY= github.com/docker/docker-credential-helpers v0.9.5/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c= github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94= @@ -125,8 +121,8 @@ github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSw github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/fsouza/go-dockerclient v1.12.3 h1:CEsX4/msyMEekHAR9Pf8XniZBtwGo0Kl+mLPQ/AnSys= -github.com/fsouza/go-dockerclient v1.12.3/go.mod h1:gl0t2KUfrsLbm4tw5/ySsJkkFpi7Fz9gXzY2BKLEvZA= +github.com/fsouza/go-dockerclient v1.13.0 h1:i6VWBKrFprrqDDK6rEYw0Zp5KsN+cVlqZ/ODaIX2erM= +github.com/fsouza/go-dockerclient v1.13.0/go.mod h1:slZeNd4OpH+YfOrTc4+fkjtq8fwKymehRReLvUVFfpI= github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= @@ -158,8 +154,8 @@ github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6 github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.20.6 h1:cvWX87UxxLgaH76b4hIvya6Dzz9qHB31qAwjAohdSTU= -github.com/google/go-containerregistry v0.20.6/go.mod h1:T0x8MuoAoKX/873bkeSfLD2FAkwCDf9/HZgsFJ02E2Y= +github.com/google/go-containerregistry v0.20.7 h1:24VGNpS0IwrOZ2ms2P1QE3Xa5X9p4phx0aUgzYzHW6I= +github.com/google/go-containerregistry v0.20.7/go.mod h1:Lx5LCZQjLH1QBaMPeGwsME9biPeo1lPx6lbGj/UmzgM= github.com/google/go-intervals v0.0.2 h1:FGrVEiUnTRKR8yE04qzXYaJMtnIYqobR5QbblK3ixcM= github.com/google/go-intervals v0.0.2/go.mod h1:MkaR3LNRfeKLPmqgJYs4E66z5InYjmCjbbr4TQlcT6Y= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -223,6 +219,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/linuxkit/virtsock v0.0.0-20241009230534-cb6a20cc0422 h1:XvRuyDDRvi+UDxHN/M4MW4HxjmNVMmUKQj/+AbgsYgk= github.com/linuxkit/virtsock v0.0.0-20241009230534-cb6a20cc0422/go.mod h1:JLgfq4XMVbvfNlAXla/41lZnp21O72a/wWHGJefAvgQ= +github.com/lsm5/buildah v0.0.0-20260317084505-caaea7f2d096 h1:hYBxMWR8SeYIVIUm9zAfOQV2t7hWDKMO/ju0PP70YwY= +github.com/lsm5/buildah v0.0.0-20260317084505-caaea7f2d096/go.mod h1:kFd6qpK0J6WQXwEGR/NMNwnyHg0GtDJCtPny8rG4Ako= github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 h1:7UMa6KCCMjZEMDtTVdcGu0B1GmmC7QJKiCCjyTAWQy0= github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k= github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= @@ -251,16 +249,18 @@ github.com/miekg/pkcs11 v1.1.1 h1:Ugu9pdy6vAYku5DEpVWVFPYnzV+bxB+iRdbuFSu7TvU= github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/mistifyio/go-zfs/v4 v4.0.0 h1:sU0+5dX45tdDK5xNZ3HBi95nxUc48FS92qbIZEvpAg4= github.com/mistifyio/go-zfs/v4 v4.0.0/go.mod h1:weotFtXTHvBwhr9Mv96KYnDkTPBOHFUbm9cBmQpesL0= -github.com/moby/buildkit v0.26.3 h1:D+ruZVAk/3ipRq5XRxBH9/DIFpRjSlTtMbghT5gQP9g= -github.com/moby/buildkit v0.26.3/go.mod h1:4T4wJzQS4kYWIfFRjsbJry4QoxDBjK+UGOEOs1izL7w= +github.com/moby/buildkit v0.28.0 h1:rKulfRRSduHJPNpLTk481fHElqN9tps0VUx8YV/5zsA= +github.com/moby/buildkit v0.28.0/go.mod h1:RCuOcj/bVsCriBG8NeFzRxjiCFQKnKP7KOVlNTS18t4= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/go-archive v0.1.0 h1:Kk/5rdW/g+H8NHdJW2gsXyZ7UnzvJNOy6VKJqueWdcQ= -github.com/moby/go-archive v0.1.0/go.mod h1:G9B+YoujNohJmrIYFBpSd54GTUB4lt9S+xVQvsJyFuo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= github.com/moby/moby/api v1.54.0 h1:7kbUgyiKcoBhm0UrWbdrMs7RX8dnwzURKVbZGy2GnL0= github.com/moby/moby/api v1.54.0/go.mod h1:8mb+ReTlisw4pS6BRzCMts5M49W5M7bKt1cJy/YbAqc= github.com/moby/moby/client v0.3.0 h1:UUGL5okry+Aomj3WhGt9Aigl3ZOxZGqR7XPo+RLPlKs= github.com/moby/moby/client v0.3.0/go.mod h1:HJgFbJRvogDQjbM8fqc1MCEm4mIAGMLjXbgwoZp6jCQ= +github.com/moby/moby/v2 v2.0.0-beta.6 h1:esIpPmQk4oZyPkbu+5hDAE+as2LEKaYxQcWSC5zUGiM= +github.com/moby/moby/v2 v2.0.0-beta.6/go.mod h1:nrC3bakOe44FcxsHAuvxsIHWtS4Vcf8Kn1j44kcZRLs= github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk= github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= github.com/moby/sys/capability v0.4.0 h1:4D4mI6KlNtWMCM1Z/K0i7RV1FkX+DBDHKVJpCndZoHk= @@ -281,8 +281,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc= github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= @@ -295,8 +293,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= -github.com/opencontainers/runc v1.4.0 h1:FG1Hw0GBYPsNki+mBz1QOrSzbwbAcerhrAD2r097QCc= -github.com/opencontainers/runc v1.4.0/go.mod h1:sch3Bh3c1NlyAkALoAUz5Br9ubMLZzFcxuovZbnkErk= +github.com/opencontainers/runc v1.4.1 h1:eg1A930KKiZ3IShaYHPRiDi6uMrHMnd7OiElHBLgqfY= +github.com/opencontainers/runc v1.4.1/go.mod h1:ufk5PTTsy5pnGBAvTh50e+eqGk01pYH2YcVxh557Qlk= github.com/opencontainers/runtime-spec v1.3.0 h1:YZupQUdctfhpZy3TM39nN9Ika5CBWT5diQ8ibYCRkxg= github.com/opencontainers/runtime-spec v1.3.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-tools v0.9.1-0.20251205004911-5e639034dcdc h1:82NlZLiQEB6Wp+nmASMlkHsEXz3Q0pXJbK7QO6ck5lo= @@ -339,12 +337,12 @@ github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI= github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= -github.com/sigstore/fulcio v1.8.1 h1:PmoQv3XmhjR2BWFWw5LcMUXJPmhyizOIL7HeYnpio58= -github.com/sigstore/fulcio v1.8.1/go.mod h1:7tP3KW9eCGlPYRj5N4MSuUOat7CkeIHuXZ2jAUQ+Rwc= +github.com/sigstore/fulcio v1.8.5 h1:HYTD1/L5wlBp8JxsWxUf8hmfaNBBF/x3r3p5l6tZwbA= +github.com/sigstore/fulcio v1.8.5/go.mod h1:tSLYK3JsKvJpDW1BsIsVHZgHj+f8TjXARzqIUWSsSPQ= github.com/sigstore/protobuf-specs v0.5.0 h1:F8YTI65xOHw70NrvPwJ5PhAzsvTnuJMGLkA4FIkofAY= github.com/sigstore/protobuf-specs v0.5.0/go.mod h1:+gXR+38nIa2oEupqDdzg4qSBT0Os+sP7oYv6alWewWc= -github.com/sigstore/sigstore v1.9.6-0.20251111174640-d8ab8afb1326 h1:s39MsSDVn8LhePV5adidcOjjKHaplLxpHM1mvbC24l4= -github.com/sigstore/sigstore v1.9.6-0.20251111174640-d8ab8afb1326/go.mod h1:xSCb7eki7lCdi+mNh4I4MVpKPP2cWGtDYmSPPmX/K70= +github.com/sigstore/sigstore v1.10.4 h1:ytOmxMgLdcUed3w1SbbZOgcxqwMG61lh1TmZLN+WeZE= +github.com/sigstore/sigstore v1.10.4/go.mod h1:tDiyrdOref3q6qJxm2G+JHghqfmvifB7hw+EReAfnbI= github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/skeema/knownhosts v1.3.2 h1:EDL9mgf4NzwMXCTfaxSD/o/a5fxDw/xL9nkU28JjdBg= @@ -433,12 +431,12 @@ go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4A go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= -go.podman.io/common v0.67.1-0.20260313003550-7415b6a27ee6 h1:2W+x/bT6mWCYUhYnZqLjpaVwQ13qP2/ruXgGJwbP56k= -go.podman.io/common v0.67.1-0.20260313003550-7415b6a27ee6/go.mod h1:0SZygTu/+zU+jD4oLtamBoZXiGrD3uJdDhlgYWl9x3U= -go.podman.io/image/v5 v5.39.2-0.20260313003550-7415b6a27ee6 h1:GR9v4x4Er9blWVddAi8yETG6MA81leh/z/HP+HmVdfo= -go.podman.io/image/v5 v5.39.2-0.20260313003550-7415b6a27ee6/go.mod h1:P9wOtKQ6IMXhcrIp7LXGnluaHRgRZEK8Dyh1biyFpkg= -go.podman.io/storage v1.62.1-0.20260313003550-7415b6a27ee6 h1:jhj6/WSU9omBCMY3woPF8HL6c+LT8CXS3RV/TotHXIk= -go.podman.io/storage v1.62.1-0.20260313003550-7415b6a27ee6/go.mod h1:zkm6ScbnKEMuDwswj+IFjtjXbI8g/MFDdljd6R5mf6U= +go.podman.io/common v0.67.1-0.20260316162257-e70c309aabae h1:VoUmnazJGnPqWoGYF3YzRU0ZgA9DQ3qg1bYCqhkYUyg= +go.podman.io/common v0.67.1-0.20260316162257-e70c309aabae/go.mod h1:sugHfpSU9btZ6KRTruHrfbzTO8HbOCX9s++p7kmdbOQ= +go.podman.io/image/v5 v5.39.2-0.20260316162257-e70c309aabae h1:jBTnK7tFX0O7b5wuo2b+JunSLxJE0rSsTvhiTGtfNf8= +go.podman.io/image/v5 v5.39.2-0.20260316162257-e70c309aabae/go.mod h1:eSTQb66cEeMtWaj3y4mfDsMB7t068tG+UjbPLWj60ho= +go.podman.io/storage v1.62.1-0.20260316162257-e70c309aabae h1:2cNSnB3KSKTtmd+PBqAHsQmNjhOkmh2Ne0mhhMRrMRo= +go.podman.io/storage v1.62.1-0.20260316162257-e70c309aabae/go.mod h1:k8lWBDknm4IJEfY9Gy3P/wRFT8aWvtk+rPtD8FKxIBE= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= diff --git a/libpod/container.go b/libpod/container.go index 68e22468063..bc664fda2d4 100644 --- a/libpod/container.go +++ b/libpod/container.go @@ -1465,9 +1465,9 @@ func (c *Container) NetworkMode() string { if ns.Path != "" { networkMode = fmt.Sprintf("ns:%s", ns.Path) } else { - // We're making a network ns, but not - // configuring with Slirp or CNI. That - // means it's --net=none + // We're making a network ns, but not + // configuring with Slirp. That means + // it's --net=none networkMode = "none" } break diff --git a/libpod/container_internal_common.go b/libpod/container_internal_common.go index 1ffeaceb661..cb22ea440cb 100644 --- a/libpod/container_internal_common.go +++ b/libpod/container_internal_common.go @@ -1600,7 +1600,7 @@ func (c *Container) restore(ctx context.Context, options ContainerCheckpointOpti perNetOpts.StaticIPs = append(perNetOpts.StaticIPs, netAddress.IPNet.IP) } } - // Normally interfaces have a length of 1, only for some special cni configs we could get more. + // Normally interfaces have a length of 1, only for some special configs we could get more. // For now just use the first interface to get the ips this should be good enough for most cases. break } diff --git a/libpod/networking_linux.go b/libpod/networking_linux.go index 759100ef77f..034d090a1e1 100644 --- a/libpod/networking_linux.go +++ b/libpod/networking_linux.go @@ -6,7 +6,6 @@ import ( "fmt" "net" - "github.com/containernetworking/plugins/pkg/ns" "github.com/containers/podman/v6/libpod/define" "github.com/containers/podman/v6/pkg/rootless" "github.com/opencontainers/runtime-spec/specs-go" @@ -173,7 +172,7 @@ func getContainerNetIO(ctr *Container) (map[string]define.ContainerNetworkStats, return nil, nil } - err := ns.WithNetNSPath(netNSPath, func(_ ns.NetNS) error { + err := netns.WithNetNSPath(netNSPath, func(_ netns.NetNS) error { links, err := netlink.LinkList() if err != nil { return fmt.Errorf("retrieving all network interfaces: %w", err) @@ -218,7 +217,7 @@ func (c *Container) joinedNetworkNSPath() (string, bool) { func (c *Container) inspectJoinedNetworkNS(networkns string) (q types.StatusBlock, retErr error) { var result types.StatusBlock - err := ns.WithNetNSPath(networkns, func(_ ns.NetNS) error { + err := netns.WithNetNSPath(networkns, func(_ netns.NetNS) error { ifaces, err := net.Interfaces() if err != nil { return err diff --git a/pkg/bindings/test/common_test.go b/pkg/bindings/test/common_test.go index 0bf60309d8c..7a8a1cbfa66 100644 --- a/pkg/bindings/test/common_test.go +++ b/pkg/bindings/test/common_test.go @@ -83,10 +83,6 @@ func (b *bindingTest) runPodman(command []string) *Session { if ok { cmd = append(cmd, "--cgroup-manager", val) } - val, ok = os.LookupEnv("CNI_CONFIG_DIR") - if ok { - cmd = append(cmd, "--network-config-dir", val) - } val, ok = os.LookupEnv("CONMON") if ok { cmd = append(cmd, "--conmon", val) diff --git a/test/buildah-bud/apply-podman-deltas b/test/buildah-bud/apply-podman-deltas index dc80701bf9b..6729be2c764 100755 --- a/test/buildah-bud/apply-podman-deltas +++ b/test/buildah-bud/apply-podman-deltas @@ -282,6 +282,9 @@ skip_if_remote "http_proxy env is not sent via remote API" \ skip_if_remote "--metadata-file not supported in remote mode" \ "bud cache by format" +skip_if_remote "BUILDAH_ISOLATION env var not propagated via podman-remote" \ + "build-conflicting-isolation-chroot-and-network" + ############################################################################### # BEGIN tests which are skipped due to actual podman or podman-remote bugs. @@ -338,7 +341,9 @@ skip_if_remote "FIXME: 2025-04-01 git related errors returning wrong exit code" skip "process substitution with overlay context not supported" \ "build-with-timestamp-applies-to-oci-archive" \ "build-with-timestamp-applies-to-oci-archive-with-base" \ - "build-with-run-mount" + "build-with-run-mount" \ + "use-secret-to-env-variable" \ + "use-secret-to-env-variable-and-file-path" # END temporary workarounds that must be reevaluated periodically ############################################################################### diff --git a/test/buildah-bud/buildah-tests.diff b/test/buildah-bud/buildah-tests.diff index e746000b481..5db2ca4cf7f 100644 --- a/test/buildah-bud/buildah-tests.diff +++ b/test/buildah-bud/buildah-tests.diff @@ -1,4 +1,4 @@ -From 1ca19690f26005148482b1fbeff0aa52a67ee898 Mon Sep 17 00:00:00 2001 +From 53c97f858285ff043b4121988433f2312482eba9 Mon Sep 17 00:00:00 2001 From: Ed Santiago Date: Thu, 6 Oct 2022 17:32:59 -0600 Subject: [PATCH] tweaks for running buildah tests under podman @@ -6,15 +6,16 @@ Subject: [PATCH] tweaks for running buildah tests under podman Signed-off-by: Ed Santiago Signed-off-by: Paul Holzinger Signed-off-by: Danish Prakash +Signed-off-by: Lokesh Mandvekar --- tests/helpers.bash | 166 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 162 insertions(+), 4 deletions(-) diff --git a/tests/helpers.bash b/tests/helpers.bash -index d08221a52759..5e9c818092cb 100644 +index 5ba4f5a..6a41f10 100644 --- a/tests/helpers.bash +++ b/tests/helpers.bash -@@ -85,6 +85,42 @@ EOF +@@ -86,6 +86,42 @@ EOF BUILDAH_REGISTRY_OPTS="${regconfopt} ${regconfdir} --short-name-alias-conf ${TEST_SCRATCH_DIR}/cache/shortnames.conf" COPY_REGISTRY_OPTS="${BUILDAH_REGISTRY_OPTS}" PODMAN_REGISTRY_OPTS="${regconfopt}" @@ -55,12 +56,12 @@ index d08221a52759..5e9c818092cb 100644 + die "podman server never came up: $PODMAN_SOCK_FILE" + fi } - + function starthttpd() { # directoryspecs [working-directory-or-"" [certfile, keyfile]] -@@ -154,6 +190,22 @@ function teardown_tests() { +@@ -155,6 +191,22 @@ function teardown_tests() { stop_git_daemon stop_registry - + + if [[ -n "$PODMAN_SERVER_PID" ]]; then + echo "teardown: stopping podman server $PODMAN_SERVER_PID" + kill $PODMAN_SERVER_PID @@ -80,9 +81,9 @@ index d08221a52759..5e9c818092cb 100644 # Workaround for #1991 - buildah + overlayfs leaks mount points. # Many tests leave behind /var/tmp/.../root/overlay and sub-mounts; # let's find those and clean them up, otherwise 'rm -rf' fails. -@@ -275,7 +327,12 @@ function copy() { +@@ -276,7 +328,12 @@ function copy() { } - + function podman() { - command ${PODMAN_BINARY:-podman} ${PODMAN_REGISTRY_OPTS} ${ROOTDIR_OPTS} "$@" + local cmd=${PODMAN_BINARY:-podman} @@ -92,12 +93,12 @@ index d08221a52759..5e9c818092cb 100644 + fi + command $cmd $opts "$@" } - + # There are various scenarios where we would like to execute `tests` as rootless user, however certain commands like `buildah mount` -@@ -382,8 +439,86 @@ function run_buildah() { +@@ -383,8 +440,86 @@ function run_buildah() { --retry) retry=3; shift;; # retry network flakes esac - + + local podman_or_buildah=${BUILDAH_BINARY} + local _opts="${ROOTDIR_OPTS} ${BUILDAH_REGISTRY_OPTS}" + local copydown=: @@ -179,12 +180,12 @@ index d08221a52759..5e9c818092cb 100644 # Remember command args, for possible use in later diagnostic messages - MOST_RECENT_BUILDAH_COMMAND="buildah $*" + MOST_RECENT_BUILDAH_COMMAND="$cmd_basename $*" - + # If session is rootless and `buildah mount` is invoked, perform unshare, # since normal user cannot mount a filesystem unless they're in a user namespace along with its own mount namespace. -@@ -397,8 +532,8 @@ function run_buildah() { +@@ -398,8 +533,8 @@ function run_buildah() { retry=$(( retry - 1 )) - + # stdout is only emitted upon error; this echo is to help a debugger - echo "${_LOG_PROMPT} ${BUILDAH_BINARY} $*" - run env CONTAINERS_CONF=${CONTAINERS_CONF:-$(dirname ${BASH_SOURCE})/containers.conf} timeout --foreground --kill=10 $BUILDAH_TIMEOUT ${BUILDAH_BINARY} ${BUILDAH_REGISTRY_OPTS} ${ROOTDIR_OPTS} "$@" @@ -193,20 +194,20 @@ index d08221a52759..5e9c818092cb 100644 # without "quotes", multiple lines are glommed together into one if [ -n "$output" ]; then echo "$output" -@@ -425,6 +560,9 @@ function run_buildah() { +@@ -426,6 +561,9 @@ function run_buildah() { false fi - + + if [[ "$status" -eq 0 ]] ; then + eval ${copydown} + fi if [ -n "$expected_rc" ]; then if [ "$status" -eq "$expected_rc" ]; then return -@@ -753,6 +891,26 @@ function skip_if_no_unshare() { - fi +@@ -772,6 +910,26 @@ function skip_unless_arch() { + skip "test requires one of these architectures: $* (current: $goarch)" } - + +#################### +# skip_if_remote # (only applicable for podman) +#################### @@ -231,5 +232,5 @@ index d08221a52759..5e9c818092cb 100644 # start_git_daemon # ###################### -- -2.51.1 +2.53.0 diff --git a/test/e2e/network_create_test.go b/test/e2e/network_create_test.go index fdeed23ebde..132c7696f63 100644 --- a/test/e2e/network_create_test.go +++ b/test/e2e/network_create_test.go @@ -624,7 +624,7 @@ var _ = Describe("Podman network create", func() { // can only check this as root if !isRootless() { - // make sure cni/netavark created bridge with expected name + // make sure netavark created bridge with expected name bridge, err := net.InterfaceByName(bridgeName) Expect(err).ToNot(HaveOccurred()) Expect(bridge.Name).To(Equal(bridgeName)) @@ -656,7 +656,7 @@ var _ = Describe("Podman network create", func() { containerIP, _, err := net.ParseCIDR(try.OutputToString()) Expect(err).ToNot(HaveOccurred()) - // Note as of today (June 2023) we always get the first ip from netavark and cni but let's not depend on that. + // Note as of today (June 2023) we always get the first ip from netavark but let's not depend on that. // All we care about is the ip is from the range which allows for both. Expect(containerIP.String()).To(Or(Equal("10.11.16.11"), Equal("10.11.16.12")), "ip address must be in --ip-range") }) diff --git a/test/e2e/run_networking_test.go b/test/e2e/run_networking_test.go index bdaf048479a..931227267b5 100644 --- a/test/e2e/run_networking_test.go +++ b/test/e2e/run_networking_test.go @@ -13,12 +13,12 @@ import ( "sync" "syscall" - "github.com/containernetworking/plugins/pkg/ns" . "github.com/containers/podman/v6/test/utils" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/vishvananda/netlink" + "go.podman.io/common/pkg/netns" "go.podman.io/storage/pkg/stringid" ) @@ -790,7 +790,7 @@ EXPOSE 2004-2005/tcp`, ALPINE) }) It("podman run --uidmap /etc/hosts contains --hostname", func() { - SkipIfRootless("uidmap population of cninetworks not supported for rootless users") + SkipIfRootless("uidmap population of networks not supported for rootless users") session := podmanTest.Podman([]string{"run", "--uidmap", "0:100000:1000", "--rm", "--hostname", "foohostname", ALPINE, "grep", "foohostname", "/etc/hosts"}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) @@ -884,7 +884,7 @@ EXPOSE 2004-2005/tcp`, ALPINE) } setupNetworkNs := func(networkNSName string) { - _ = ns.WithNetNSPath("/run/netns/"+networkNSName, func(_ ns.NetNS) error { + _ = netns.WithNetNSPath("/run/netns/"+networkNSName, func(_ netns.NetNS) error { loopbackup() linkup("eth0", "46:7f:45:6e:4f:c8", []string{"10.25.40.0/24", "fd04:3e42:4a4e:3381::/64"}) linkup("eth1", "56:6e:35:5d:3e:a8", []string{"10.88.0.0/16"}) diff --git a/troubleshooting.md b/troubleshooting.md index e7be7bc77e6..35418d9defd 100644 --- a/troubleshooting.md +++ b/troubleshooting.md @@ -779,25 +779,6 @@ And now this should work: $ podman-remote info ``` -### 29) Rootless CNI networking fails in RHEL with Podman v2.2.1 to v3.0.1. - -A failure is encountered when trying to use networking on a rootless -container in Podman v2.2.1 through v3.0.1 on RHEL. This error does not -occur on other Linux distributions. - -#### Symptom - -A rootless container is created using a CNI network, but the `podman run` command -returns an error that an image must be built. - -#### Solution - -In order to use a CNI network in a rootless container on RHEL, -an Infra container image for CNI-in-slirp4netns must be created. The -instructions for building the Infra container image can be found for -v2.2.1 [here](https://github.com/containers/podman/tree/v2.2.1-rhel/contrib/rootless-cni-infra), -and for v3.0.1 [here](https://github.com/containers/podman/tree/v3.0.1-rhel/contrib/rootless-cni-infra). - ### 30) Container related firewall rules are lost after reloading firewalld Container network can't be reached after `firewall-cmd --reload` and `systemctl restart firewalld` Running `podman network reload` will fix it but it has to be done manually. diff --git a/vendor/cyphar.com/go-pathrs/.golangci.yml b/vendor/cyphar.com/go-pathrs/.golangci.yml index 2778a3268ef..a28cbd2a4fd 100644 --- a/vendor/cyphar.com/go-pathrs/.golangci.yml +++ b/vendor/cyphar.com/go-pathrs/.golangci.yml @@ -1,8 +1,8 @@ # SPDX-License-Identifier: MPL-2.0 # # libpathrs: safe path resolution on Linux -# Copyright (C) 2019-2025 Aleksa Sarai # Copyright (C) 2019-2025 SUSE LLC +# Copyright (C) 2026 Aleksa Sarai # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this diff --git a/vendor/cyphar.com/go-pathrs/doc.go b/vendor/cyphar.com/go-pathrs/doc.go index a7ee4bc487f..c3b4eedd0f8 100644 --- a/vendor/cyphar.com/go-pathrs/doc.go +++ b/vendor/cyphar.com/go-pathrs/doc.go @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this diff --git a/vendor/cyphar.com/go-pathrs/handle_linux.go b/vendor/cyphar.com/go-pathrs/handle_linux.go index 3221ef67389..6ed0b7af7ad 100644 --- a/vendor/cyphar.com/go-pathrs/handle_linux.go +++ b/vendor/cyphar.com/go-pathrs/handle_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -30,11 +30,9 @@ import ( // you can try to use [Root.Open] or [Root.OpenFile]. // // It is critical that perform all relevant operations through this [Handle] -// (rather than fetching the file descriptor yourself with [Handle.IntoRaw]), +// (rather than fetching the underlying [os.File] yourself with [Handle.IntoFile]), // because the security properties of libpathrs depend on users doing all // relevant filesystem operations through libpathrs. -// -// [os.File]: https://pkg.go.dev/os#File type Handle struct { inner *os.File } @@ -43,7 +41,7 @@ type Handle struct { // handle will be copied by this method, so the original handle should still be // freed by the caller. // -// This is effectively the inverse operation of [Handle.IntoRaw], and is used +// This is effectively the inverse operation of [Handle.IntoFile], and is used // for "deserialising" pathrs root handles. func HandleFromFile(file *os.File) (*Handle, error) { newFile, err := fdutils.DupFile(file) @@ -92,8 +90,6 @@ func (h *Handle) OpenFile(flags int) (*os.File, error) { // calling [Handle.Close] will also close any copies of the returned [os.File]. // If you want to get an independent copy, use [Handle.Clone] followed by // [Handle.IntoFile] on the cloned [Handle]. -// -// [os.File]: https://pkg.go.dev/os#File func (h *Handle) IntoFile() *os.File { // TODO: Figure out if we really don't want to make a copy. // TODO: We almost certainly want to clear r.inner here, but we can't do diff --git a/vendor/cyphar.com/go-pathrs/internal/fdutils/fd_linux.go b/vendor/cyphar.com/go-pathrs/internal/fdutils/fd_linux.go index 41aea3e4b3d..418b298149e 100644 --- a/vendor/cyphar.com/go-pathrs/internal/fdutils/fd_linux.go +++ b/vendor/cyphar.com/go-pathrs/internal/fdutils/fd_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this diff --git a/vendor/cyphar.com/go-pathrs/internal/libpathrs/error_unix.go b/vendor/cyphar.com/go-pathrs/internal/libpathrs/error_unix.go index c9f416de01f..8f610ca564e 100644 --- a/vendor/cyphar.com/go-pathrs/internal/libpathrs/error_unix.go +++ b/vendor/cyphar.com/go-pathrs/internal/libpathrs/error_unix.go @@ -5,8 +5,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this diff --git a/vendor/cyphar.com/go-pathrs/internal/libpathrs/libpathrs_linux.go b/vendor/cyphar.com/go-pathrs/internal/libpathrs/libpathrs_linux.go index c07b80e3071..d54497a5b70 100644 --- a/vendor/cyphar.com/go-pathrs/internal/libpathrs/libpathrs_linux.go +++ b/vendor/cyphar.com/go-pathrs/internal/libpathrs/libpathrs_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -100,7 +100,7 @@ func InRootReadlink(rootFd uintptr, path string) (string, error) { size := 128 for { linkBuf := make([]byte, size) - n := C.pathrs_inroot_readlink(C.int(rootFd), cPath, C.cast_ptr(unsafe.Pointer(&linkBuf[0])), C.ulong(len(linkBuf))) + n := C.pathrs_inroot_readlink(C.int(rootFd), cPath, C.cast_ptr(unsafe.Pointer(&linkBuf[0])), C.size_t(len(linkBuf))) switch { case int(n) < C.__PATHRS_MAX_ERR_VALUE: return "", fetchError(n) @@ -301,7 +301,7 @@ func ProcReadlinkat(procRootFd int, base ProcBase, path string) (string, error) linkBuf := make([]byte, size) n := C.pathrs_proc_readlinkat( C.int(procRootFd), cBase, cPath, - C.cast_ptr(unsafe.Pointer(&linkBuf[0])), C.ulong(len(linkBuf))) + C.cast_ptr(unsafe.Pointer(&linkBuf[0])), C.size_t(len(linkBuf))) switch { case int(n) < C.__PATHRS_MAX_ERR_VALUE: return "", fetchError(n) diff --git a/vendor/cyphar.com/go-pathrs/procfs/procfs_linux.go b/vendor/cyphar.com/go-pathrs/procfs/procfs_linux.go index 5533c427cb7..915e9ccdb58 100644 --- a/vendor/cyphar.com/go-pathrs/procfs/procfs_linux.go +++ b/vendor/cyphar.com/go-pathrs/procfs/procfs_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -56,16 +56,15 @@ var ( // *before* you call wait(2)or any equivalent method that could reap // zombies). func ProcPid(pid int) ProcBase { - if pid < 0 || pid >= 1<<31 { + if pid < 0 || uint64(pid) >= 1<<31 { panic("invalid ProcBasePid value") // TODO: should this be an error? } - return ProcBase{inner: libpathrs.ProcPid(uint32(pid))} + pid32 := uint32(pid) //nolint:gosec // G115 false positive + return ProcBase{inner: libpathrs.ProcPid(pid32)} } // ThreadCloser is a callback that needs to be called when you are done // operating on an [os.File] fetched using [Handle.OpenThreadSelf]. -// -// [os.File]: https://pkg.go.dev/os#File type ThreadCloser func() // Handle is a wrapper around an *os.File handle to "/proc", which can be @@ -181,8 +180,6 @@ func (proc *Handle) OpenRoot(path string, flags int) (*os.File, error) { // Unlike [Handle.OpenThreadSelf], this method does not involve locking // the goroutine to the current OS thread and so is simpler to use and // theoretically has slightly less overhead. -// -// [runtime.LockOSThread]: https://pkg.go.dev/runtime#LockOSThread func (proc *Handle) OpenSelf(path string, flags int) (*os.File, error) { file, closer, err := proc.open(ProcSelf, path, flags) if closer != nil { @@ -228,10 +225,6 @@ func (proc *Handle) OpenPid(pid int, path string, flags int) (*os.File, error) { // callback MUST be called AFTER you have finished using the returned // [os.File]. This callback is completely separate to [os.File.Close], so it // must be called regardless of how you close the handle. -// -// [runtime.LockOSThread]: https://pkg.go.dev/runtime#LockOSThread -// [os.File]: https://pkg.go.dev/os#File -// [os.File.Close]: https://pkg.go.dev/os#File.Close func (proc *Handle) OpenThreadSelf(path string, flags int) (*os.File, ThreadCloser, error) { return proc.open(ProcThreadSelf, path, flags) } diff --git a/vendor/cyphar.com/go-pathrs/root_linux.go b/vendor/cyphar.com/go-pathrs/root_linux.go index edc9e4c87f9..5bc2e907170 100644 --- a/vendor/cyphar.com/go-pathrs/root_linux.go +++ b/vendor/cyphar.com/go-pathrs/root_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -54,8 +54,6 @@ func OpenRoot(path string) (*Root, error) { // still be closed by the caller. // // This is effectively the inverse operation of [Root.IntoFile]. -// -// [os.File]: https://pkg.go.dev/os#File func RootFromFile(file *os.File) (*Root, error) { newFile, err := fdutils.DupFile(file) if err != nil { @@ -109,8 +107,6 @@ func (r *Root) ResolveNoFollow(path string) (*Handle, error) { // ergonomic to use. // // This is effectively equivalent to [os.Open]. -// -// [os.Open]: https://pkg.go.dev/os#Open func (r *Root) Open(path string) (*os.File, error) { return r.OpenFile(path, os.O_RDONLY) } @@ -127,8 +123,6 @@ func (r *Root) Open(path string) (*os.File, error) { // // This is effectively equivalent to [os.OpenFile], except that os.O_CREAT is // not supported. -// -// [os.OpenFile]: https://pkg.go.dev/os#OpenFile func (r *Root) OpenFile(path string, flags int) (*os.File, error) { return fdutils.WithFileFd(r.inner, func(rootFd uintptr) (*os.File, error) { fd, err := libpathrs.InRootOpen(rootFd, path, flags) @@ -145,8 +139,6 @@ func (r *Root) OpenFile(path string, flags int) (*os.File, error) { // // Unlike [os.Create], if the file already exists an error is created rather // than the file being opened and truncated. -// -// [os.Create]: https://pkg.go.dev/os#Create func (r *Root) Create(path string, flags int, mode os.FileMode) (*os.File, error) { unixMode, err := toUnixMode(mode, false) if err != nil { @@ -194,8 +186,6 @@ func (r *Root) RemoveFile(path string) error { // directory tree. // // This is effectively equivalent to [os.Remove]. -// -// [os.Remove]: https://pkg.go.dev/os#Remove func (r *Root) Remove(path string) error { // In order to match os.Remove's implementation we need to also do both // syscalls unconditionally and adjust the error based on whether @@ -219,8 +209,6 @@ func (r *Root) Remove(path string) error { // RemoveAll recursively deletes a path and all of its children. // // This is effectively equivalent to [os.RemoveAll]. -// -// [os.RemoveAll]: https://pkg.go.dev/os#RemoveAll func (r *Root) RemoveAll(path string) error { _, err := fdutils.WithFileFd(r.inner, func(rootFd uintptr) (struct{}, error) { err := libpathrs.InRootRemoveAll(rootFd, path) @@ -233,8 +221,6 @@ func (r *Root) RemoveAll(path string) error { // mode is used for the new directory (the process's umask applies). // // This is effectively equivalent to [os.Mkdir]. -// -// [os.Mkdir]: https://pkg.go.dev/os#Mkdir func (r *Root) Mkdir(path string, mode os.FileMode) error { unixMode, err := toUnixMode(mode, false) if err != nil { @@ -253,8 +239,6 @@ func (r *Root) Mkdir(path string, mode os.FileMode) error { // directories created by this function (the process's umask applies). // // This is effectively equivalent to [os.MkdirAll]. -// -// [os.MkdirAll]: https://pkg.go.dev/os#MkdirAll func (r *Root) MkdirAll(path string, mode os.FileMode) (*Handle, error) { unixMode, err := toUnixMode(mode, false) if err != nil { @@ -278,9 +262,7 @@ func (r *Root) MkdirAll(path string, mode os.FileMode) (*Handle, error) { // directory tree. The provided mode is used for the new directory (the // process's umask applies). // -// This is effectively equivalent to [unix.Mknod]. -// -// [unix.Mknod]: https://pkg.go.dev/golang.org/x/sys/unix#Mknod +// This is effectively equivalent to [golang.org/x/sys/unix.Mknod]. func (r *Root) Mknod(path string, mode os.FileMode, dev uint64) error { unixMode, err := toUnixMode(mode, true) if err != nil { @@ -298,8 +280,6 @@ func (r *Root) Mknod(path string, mode os.FileMode, dev uint64) error { // created at path and is a link to target. // // This is effectively equivalent to [os.Symlink]. -// -// [os.Symlink]: https://pkg.go.dev/os#Symlink func (r *Root) Symlink(path, target string) error { _, err := fdutils.WithFileFd(r.inner, func(rootFd uintptr) (struct{}, error) { err := libpathrs.InRootSymlink(rootFd, path, target) @@ -314,8 +294,6 @@ func (r *Root) Symlink(path, target string) error { // host). // // This is effectively equivalent to [os.Link]. -// -// [os.Link]: https://pkg.go.dev/os#Link func (r *Root) Hardlink(path, target string) error { _, err := fdutils.WithFileFd(r.inner, func(rootFd uintptr) (struct{}, error) { err := libpathrs.InRootHardlink(rootFd, path, target) @@ -327,8 +305,6 @@ func (r *Root) Hardlink(path, target string) error { // Readlink returns the target of a symlink with a [Root]'s directory tree. // // This is effectively equivalent to [os.Readlink]. -// -// [os.Readlink]: https://pkg.go.dev/os#Readlink func (r *Root) Readlink(path string) (string, error) { return fdutils.WithFileFd(r.inner, func(rootFd uintptr) (string, error) { return libpathrs.InRootReadlink(rootFd, path) @@ -345,8 +321,6 @@ func (r *Root) Readlink(path string) (string, error) { // calling [Root.Close] will also close any copies of the returned [os.File]. // If you want to get an independent copy, use [Root.Clone] followed by // [Root.IntoFile] on the cloned [Root]. -// -// [os.File]: https://pkg.go.dev/os#File func (r *Root) IntoFile() *os.File { // TODO: Figure out if we really don't want to make a copy. // TODO: We almost certainly want to clear r.inner here, but we can't do diff --git a/vendor/cyphar.com/go-pathrs/utils_linux.go b/vendor/cyphar.com/go-pathrs/utils_linux.go index 2208d608f8d..b4e7e08e7df 100644 --- a/vendor/cyphar.com/go-pathrs/utils_linux.go +++ b/vendor/cyphar.com/go-pathrs/utils_linux.go @@ -3,8 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 /* * libpathrs: safe path resolution on Linux - * Copyright (C) 2019-2025 Aleksa Sarai * Copyright (C) 2019-2025 SUSE LLC + * Copyright (C) 2026 Aleksa Sarai * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this diff --git a/vendor/github.com/containernetworking/cni/LICENSE b/vendor/github.com/containernetworking/cni/LICENSE deleted file mode 100644 index 8f71f43fee3..00000000000 --- a/vendor/github.com/containernetworking/cni/LICENSE +++ /dev/null @@ -1,202 +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 - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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/containernetworking/cni/libcni/api.go b/vendor/github.com/containernetworking/cni/libcni/api.go deleted file mode 100644 index 6ac26949e6f..00000000000 --- a/vendor/github.com/containernetworking/cni/libcni/api.go +++ /dev/null @@ -1,900 +0,0 @@ -// Copyright 2015 CNI 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 libcni - -// Note this is the actual implementation of the CNI specification, which -// is reflected in the SPEC.md file. -// it is typically bundled into runtime providers (i.e. containerd or cri-o would use this -// before calling runc or hcsshim). It is also bundled into CNI providers as well, for example, -// to add an IP to a container, to parse the configuration of the CNI and so on. - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/containernetworking/cni/pkg/invoke" - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/create" - "github.com/containernetworking/cni/pkg/utils" - "github.com/containernetworking/cni/pkg/version" -) - -var ( - CacheDir = "/var/lib/cni" - // slightly awkward wording to preserve anyone matching on error strings - ErrorCheckNotSupp = fmt.Errorf("does not support the CHECK command") -) - -const ( - CNICacheV1 = "cniCacheV1" -) - -// A RuntimeConf holds the arguments to one invocation of a CNI plugin -// excepting the network configuration, with the nested exception that -// the `runtimeConfig` from the network configuration is included -// here. -type RuntimeConf struct { - ContainerID string - NetNS string - IfName string - Args [][2]string - // A dictionary of capability-specific data passed by the runtime - // to plugins as top-level keys in the 'runtimeConfig' dictionary - // of the plugin's stdin data. libcni will ensure that only keys - // in this map which match the capabilities of the plugin are passed - // to the plugin - CapabilityArgs map[string]interface{} - - // DEPRECATED. Will be removed in a future release. - CacheDir string -} - -// Use PluginConfig instead of NetworkConfig, the NetworkConfig -// backwards-compat alias will be removed in a future release. -type NetworkConfig = PluginConfig - -type PluginConfig struct { - Network *types.PluginConf - Bytes []byte -} - -type NetworkConfigList struct { - Name string - CNIVersion string - DisableCheck bool - DisableGC bool - LoadOnlyInlinedPlugins bool - Plugins []*PluginConfig - Bytes []byte -} - -type NetworkAttachment struct { - ContainerID string - Network string - IfName string - Config []byte - NetNS string - CniArgs [][2]string - CapabilityArgs map[string]interface{} -} - -type GCArgs struct { - ValidAttachments []types.GCAttachment -} - -type CNI interface { - AddNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) (types.Result, error) - CheckNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error - DelNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error - GetNetworkListCachedResult(net *NetworkConfigList, rt *RuntimeConf) (types.Result, error) - GetNetworkListCachedConfig(net *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) - - AddNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) (types.Result, error) - CheckNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error - DelNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error - GetNetworkCachedResult(net *PluginConfig, rt *RuntimeConf) (types.Result, error) - GetNetworkCachedConfig(net *PluginConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) - - ValidateNetworkList(ctx context.Context, net *NetworkConfigList) ([]string, error) - ValidateNetwork(ctx context.Context, net *PluginConfig) ([]string, error) - - GCNetworkList(ctx context.Context, net *NetworkConfigList, args *GCArgs) error - GetStatusNetworkList(ctx context.Context, net *NetworkConfigList) error - - GetCachedAttachments(containerID string) ([]*NetworkAttachment, error) - - GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) -} - -type CNIConfig struct { - Path []string - exec invoke.Exec - cacheDir string -} - -// CNIConfig implements the CNI interface -var _ CNI = &CNIConfig{} - -// NewCNIConfig returns a new CNIConfig object that will search for plugins -// in the given paths and use the given exec interface to run those plugins, -// or if the exec interface is not given, will use a default exec handler. -func NewCNIConfig(path []string, exec invoke.Exec) *CNIConfig { - return NewCNIConfigWithCacheDir(path, "", exec) -} - -// NewCNIConfigWithCacheDir returns a new CNIConfig object that will search for plugins -// in the given paths use the given exec interface to run those plugins, -// or if the exec interface is not given, will use a default exec handler. -// The given cache directory will be used for temporary data storage when needed. -func NewCNIConfigWithCacheDir(path []string, cacheDir string, exec invoke.Exec) *CNIConfig { - return &CNIConfig{ - Path: path, - cacheDir: cacheDir, - exec: exec, - } -} - -func buildOneConfig(name, cniVersion string, orig *PluginConfig, prevResult types.Result, rt *RuntimeConf) (*PluginConfig, error) { - var err error - - inject := map[string]interface{}{ - "name": name, - "cniVersion": cniVersion, - } - // Add previous plugin result - if prevResult != nil { - inject["prevResult"] = prevResult - } - - // Ensure every config uses the same name and version - orig, err = InjectConf(orig, inject) - if err != nil { - return nil, err - } - if rt != nil { - return injectRuntimeConfig(orig, rt) - } - - return orig, nil -} - -// This function takes a libcni RuntimeConf structure and injects values into -// a "runtimeConfig" dictionary in the CNI network configuration JSON that -// will be passed to the plugin on stdin. -// -// Only "capabilities arguments" passed by the runtime are currently injected. -// These capabilities arguments are filtered through the plugin's advertised -// capabilities from its config JSON, and any keys in the CapabilityArgs -// matching plugin capabilities are added to the "runtimeConfig" dictionary -// sent to the plugin via JSON on stdin. For example, if the plugin's -// capabilities include "portMappings", and the CapabilityArgs map includes a -// "portMappings" key, that key and its value are added to the "runtimeConfig" -// dictionary to be passed to the plugin's stdin. -func injectRuntimeConfig(orig *PluginConfig, rt *RuntimeConf) (*PluginConfig, error) { - var err error - - rc := make(map[string]interface{}) - for capability, supported := range orig.Network.Capabilities { - if !supported { - continue - } - if data, ok := rt.CapabilityArgs[capability]; ok { - rc[capability] = data - } - } - - if len(rc) > 0 { - orig, err = InjectConf(orig, map[string]interface{}{"runtimeConfig": rc}) - if err != nil { - return nil, err - } - } - - return orig, nil -} - -// ensure we have a usable exec if the CNIConfig was not given one -func (c *CNIConfig) ensureExec() invoke.Exec { - if c.exec == nil { - c.exec = &invoke.DefaultExec{ - RawExec: &invoke.RawExec{Stderr: os.Stderr}, - PluginDecoder: version.PluginDecoder{}, - } - } - return c.exec -} - -type cachedInfo struct { - Kind string `json:"kind"` - ContainerID string `json:"containerId"` - Config []byte `json:"config"` - IfName string `json:"ifName"` - NetworkName string `json:"networkName"` - NetNS string `json:"netns,omitempty"` - CniArgs [][2]string `json:"cniArgs,omitempty"` - CapabilityArgs map[string]interface{} `json:"capabilityArgs,omitempty"` - RawResult map[string]interface{} `json:"result,omitempty"` - Result types.Result `json:"-"` -} - -// getCacheDir returns the cache directory in this order: -// 1) global cacheDir from CNIConfig object -// 2) deprecated cacheDir from RuntimeConf object -// 3) fall back to default cache directory -func (c *CNIConfig) getCacheDir(rt *RuntimeConf) string { - if c.cacheDir != "" { - return c.cacheDir - } - if rt.CacheDir != "" { - return rt.CacheDir - } - return CacheDir -} - -func (c *CNIConfig) getCacheFilePath(netName string, rt *RuntimeConf) (string, error) { - if netName == "" || rt.ContainerID == "" || rt.IfName == "" { - return "", fmt.Errorf("cache file path requires network name (%q), container ID (%q), and interface name (%q)", netName, rt.ContainerID, rt.IfName) - } - return filepath.Join(c.getCacheDir(rt), "results", fmt.Sprintf("%s-%s-%s", netName, rt.ContainerID, rt.IfName)), nil -} - -func (c *CNIConfig) cacheAdd(result types.Result, config []byte, netName string, rt *RuntimeConf) error { - cached := cachedInfo{ - Kind: CNICacheV1, - ContainerID: rt.ContainerID, - Config: config, - IfName: rt.IfName, - NetworkName: netName, - NetNS: rt.NetNS, - CniArgs: rt.Args, - CapabilityArgs: rt.CapabilityArgs, - } - - // We need to get type.Result into cachedInfo as JSON map - // Marshal to []byte, then Unmarshal into cached.RawResult - data, err := json.Marshal(result) - if err != nil { - return err - } - - err = json.Unmarshal(data, &cached.RawResult) - if err != nil { - return err - } - - newBytes, err := json.Marshal(&cached) - if err != nil { - return err - } - - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(fname), 0o700); err != nil { - return err - } - - return os.WriteFile(fname, newBytes, 0o600) -} - -func (c *CNIConfig) cacheDel(netName string, rt *RuntimeConf) error { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - // Ignore error - return nil - } - return os.Remove(fname) -} - -func (c *CNIConfig) getCachedConfig(netName string, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - var bytes []byte - - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, nil, err - } - bytes, err = os.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil, nil - } - - unmarshaled := cachedInfo{} - if err := json.Unmarshal(bytes, &unmarshaled); err != nil { - return nil, nil, fmt.Errorf("failed to unmarshal cached network %q config: %w", netName, err) - } - if unmarshaled.Kind != CNICacheV1 { - return nil, nil, fmt.Errorf("read cached network %q config has wrong kind: %v", netName, unmarshaled.Kind) - } - - newRt := *rt - if unmarshaled.CniArgs != nil { - newRt.Args = unmarshaled.CniArgs - } - newRt.CapabilityArgs = unmarshaled.CapabilityArgs - - return unmarshaled.Config, &newRt, nil -} - -func (c *CNIConfig) getLegacyCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, err - } - data, err := os.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil - } - - // Load the cached result - result, err := create.CreateFromBytes(data) - if err != nil { - return nil, err - } - - // Convert to the config version to ensure plugins get prevResult - // in the same version as the config. The cached result version - // should match the config version unless the config was changed - // while the container was running. - result, err = result.GetAsVersion(cniVersion) - if err != nil { - return nil, fmt.Errorf("failed to convert cached result to config version %q: %w", cniVersion, err) - } - return result, nil -} - -func (c *CNIConfig) getCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, err - } - fdata, err := os.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil - } - - cachedInfo := cachedInfo{} - if err := json.Unmarshal(fdata, &cachedInfo); err != nil || cachedInfo.Kind != CNICacheV1 { - return c.getLegacyCachedResult(netName, cniVersion, rt) - } - - newBytes, err := json.Marshal(&cachedInfo.RawResult) - if err != nil { - return nil, fmt.Errorf("failed to marshal cached network %q config: %w", netName, err) - } - - // Load the cached result - result, err := create.CreateFromBytes(newBytes) - if err != nil { - return nil, err - } - - // Convert to the config version to ensure plugins get prevResult - // in the same version as the config. The cached result version - // should match the config version unless the config was changed - // while the container was running. - result, err = result.GetAsVersion(cniVersion) - if err != nil { - return nil, fmt.Errorf("failed to convert cached result to config version %q: %w", cniVersion, err) - } - return result, nil -} - -// GetNetworkListCachedResult returns the cached Result of the previous -// AddNetworkList() operation for a network list, or an error. -func (c *CNIConfig) GetNetworkListCachedResult(list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) { - return c.getCachedResult(list.Name, list.CNIVersion, rt) -} - -// GetNetworkCachedResult returns the cached Result of the previous -// AddNetwork() operation for a network, or an error. -func (c *CNIConfig) GetNetworkCachedResult(net *PluginConfig, rt *RuntimeConf) (types.Result, error) { - return c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) -} - -// GetNetworkListCachedConfig copies the input RuntimeConf to output -// RuntimeConf with fields updated with info from the cached Config. -func (c *CNIConfig) GetNetworkListCachedConfig(list *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - return c.getCachedConfig(list.Name, rt) -} - -// GetNetworkCachedConfig copies the input RuntimeConf to output -// RuntimeConf with fields updated with info from the cached Config. -func (c *CNIConfig) GetNetworkCachedConfig(net *PluginConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - return c.getCachedConfig(net.Network.Name, rt) -} - -// GetCachedAttachments returns a list of network attachments from the cache. -// The returned list will be filtered by the containerID if the value is not empty. -func (c *CNIConfig) GetCachedAttachments(containerID string) ([]*NetworkAttachment, error) { - dirPath := filepath.Join(c.getCacheDir(&RuntimeConf{}), "results") - entries, err := os.ReadDir(dirPath) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, err - } - - fileNames := make([]string, 0, len(entries)) - for _, e := range entries { - fileNames = append(fileNames, e.Name()) - } - sort.Strings(fileNames) - - attachments := []*NetworkAttachment{} - for _, fname := range fileNames { - if len(containerID) > 0 { - part := fmt.Sprintf("-%s-", containerID) - pos := strings.Index(fname, part) - if pos <= 0 || pos+len(part) >= len(fname) { - continue - } - } - - cacheFile := filepath.Join(dirPath, fname) - bytes, err := os.ReadFile(cacheFile) - if err != nil { - continue - } - - cachedInfo := cachedInfo{} - - if err := json.Unmarshal(bytes, &cachedInfo); err != nil { - continue - } - if cachedInfo.Kind != CNICacheV1 { - continue - } - if len(containerID) > 0 && cachedInfo.ContainerID != containerID { - continue - } - if cachedInfo.IfName == "" || cachedInfo.NetworkName == "" { - continue - } - - attachments = append(attachments, &NetworkAttachment{ - ContainerID: cachedInfo.ContainerID, - Network: cachedInfo.NetworkName, - IfName: cachedInfo.IfName, - Config: cachedInfo.Config, - NetNS: cachedInfo.NetNS, - CniArgs: cachedInfo.CniArgs, - CapabilityArgs: cachedInfo.CapabilityArgs, - }) - } - return attachments, nil -} - -func (c *CNIConfig) addNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) (types.Result, error) { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return nil, err - } - if err := utils.ValidateContainerID(rt.ContainerID); err != nil { - return nil, err - } - if err := utils.ValidateNetworkName(name); err != nil { - return nil, err - } - if err := utils.ValidateInterfaceName(rt.IfName); err != nil { - return nil, err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return nil, err - } - - return invoke.ExecPluginWithResult(ctx, pluginPath, newConf.Bytes, c.args("ADD", rt), c.exec) -} - -// AddNetworkList executes a sequence of plugins with the ADD command -func (c *CNIConfig) AddNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) { - var err error - var result types.Result - for _, net := range list.Plugins { - result, err = c.addNetwork(ctx, list.Name, list.CNIVersion, net, result, rt) - if err != nil { - return nil, fmt.Errorf("plugin %s failed (add): %w", pluginDescription(net.Network), err) - } - } - - if err = c.cacheAdd(result, list.Bytes, list.Name, rt); err != nil { - return nil, fmt.Errorf("failed to set network %q cached result: %w", list.Name, err) - } - - return result, nil -} - -func (c *CNIConfig) checkNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return err - } - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("CHECK", rt), c.exec) -} - -// CheckNetworkList executes a sequence of plugins with the CHECK command -func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error { - // CHECK was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil { - return err - } else if !gtet { - return fmt.Errorf("configuration version %q %w", list.CNIVersion, ErrorCheckNotSupp) - } - - if list.DisableCheck { - return nil - } - - cachedResult, err := c.getCachedResult(list.Name, list.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %w", list.Name, err) - } - - for _, net := range list.Plugins { - if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil { - return err - } - } - - return nil -} - -func (c *CNIConfig) delNetwork(ctx context.Context, name, cniVersion string, net *PluginConfig, prevResult types.Result, rt *RuntimeConf) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return err - } - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("DEL", rt), c.exec) -} - -// DelNetworkList executes a sequence of plugins with the DEL command -func (c *CNIConfig) DelNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error { - var cachedResult types.Result - - // Cached result on DEL was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil { - return err - } else if gtet { - if cachedResult, err = c.getCachedResult(list.Name, list.CNIVersion, rt); err != nil { - _ = c.cacheDel(list.Name, rt) - cachedResult = nil - } - } - - for i := len(list.Plugins) - 1; i >= 0; i-- { - net := list.Plugins[i] - if err := c.delNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil { - return fmt.Errorf("plugin %s failed (delete): %w", pluginDescription(net.Network), err) - } - } - - _ = c.cacheDel(list.Name, rt) - - return nil -} - -func pluginDescription(net *types.PluginConf) string { - if net == nil { - return "" - } - pluginType := net.Type - out := fmt.Sprintf("type=%q", pluginType) - name := net.Name - if name != "" { - out += fmt.Sprintf(" name=%q", name) - } - return out -} - -// AddNetwork executes the plugin with the ADD command -func (c *CNIConfig) AddNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) (types.Result, error) { - result, err := c.addNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, nil, rt) - if err != nil { - return nil, err - } - - if err = c.cacheAdd(result, net.Bytes, net.Network.Name, rt); err != nil { - return nil, fmt.Errorf("failed to set network %q cached result: %w", net.Network.Name, err) - } - - return result, nil -} - -// CheckNetwork executes the plugin with the CHECK command -func (c *CNIConfig) CheckNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error { - // CHECK was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil { - return err - } else if !gtet { - return fmt.Errorf("configuration version %q %w", net.Network.CNIVersion, ErrorCheckNotSupp) - } - - cachedResult, err := c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err) - } - return c.checkNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt) -} - -// DelNetwork executes the plugin with the DEL command -func (c *CNIConfig) DelNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error { - var cachedResult types.Result - - // Cached result on DEL was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil { - return err - } else if gtet { - cachedResult, err = c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err) - } - } - - if err := c.delNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt); err != nil { - return err - } - _ = c.cacheDel(net.Network.Name, rt) - return nil -} - -// ValidateNetworkList checks that a configuration is reasonably valid. -// - all the specified plugins exist on disk -// - every plugin supports the desired version. -// -// Returns a list of all capabilities supported by the configuration, or error -func (c *CNIConfig) ValidateNetworkList(ctx context.Context, list *NetworkConfigList) ([]string, error) { - version := list.CNIVersion - - // holding map for seen caps (in case of duplicates) - caps := map[string]interface{}{} - - errs := []error{} - for _, net := range list.Plugins { - if err := c.validatePlugin(ctx, net.Network.Type, version); err != nil { - errs = append(errs, err) - } - for c, enabled := range net.Network.Capabilities { - if !enabled { - continue - } - caps[c] = struct{}{} - } - } - - if len(errs) > 0 { - return nil, fmt.Errorf("%v", errs) - } - - // make caps list - cc := make([]string, 0, len(caps)) - for c := range caps { - cc = append(cc, c) - } - - return cc, nil -} - -// ValidateNetwork checks that a configuration is reasonably valid. -// It uses the same logic as ValidateNetworkList) -// Returns a list of capabilities -func (c *CNIConfig) ValidateNetwork(ctx context.Context, net *PluginConfig) ([]string, error) { - caps := []string{} - for c, ok := range net.Network.Capabilities { - if ok { - caps = append(caps, c) - } - } - if err := c.validatePlugin(ctx, net.Network.Type, net.Network.CNIVersion); err != nil { - return nil, err - } - return caps, nil -} - -// validatePlugin checks that an individual plugin's configuration is sane -func (c *CNIConfig) validatePlugin(ctx context.Context, pluginName, expectedVersion string) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(pluginName, c.Path) - if err != nil { - return err - } - if expectedVersion == "" { - expectedVersion = "0.1.0" - } - - vi, err := invoke.GetVersionInfo(ctx, pluginPath, c.exec) - if err != nil { - return err - } - for _, vers := range vi.SupportedVersions() { - if vers == expectedVersion { - return nil - } - } - return fmt.Errorf("plugin %s does not support config version %q", pluginName, expectedVersion) -} - -// GetVersionInfo reports which versions of the CNI spec are supported by -// the given plugin. -func (c *CNIConfig) GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(pluginType, c.Path) - if err != nil { - return nil, err - } - - return invoke.GetVersionInfo(ctx, pluginPath, c.exec) -} - -// GCNetworkList will do two things -// - dump the list of cached attachments, and issue deletes as necessary -// - issue a GC to the underlying plugins (if the version is high enough) -func (c *CNIConfig) GCNetworkList(ctx context.Context, list *NetworkConfigList, args *GCArgs) error { - // If DisableGC is set, then don't bother GCing at all. - if list.DisableGC { - return nil - } - - // First, get the list of cached attachments - cachedAttachments, err := c.GetCachedAttachments("") - if err != nil { - return nil - } - - var validAttachments map[types.GCAttachment]interface{} - if args != nil { - validAttachments = make(map[types.GCAttachment]interface{}, len(args.ValidAttachments)) - for _, a := range args.ValidAttachments { - validAttachments[a] = nil - } - } - - var errs []error - - for _, cachedAttachment := range cachedAttachments { - if cachedAttachment.Network != list.Name { - continue - } - // we found this attachment - gca := types.GCAttachment{ - ContainerID: cachedAttachment.ContainerID, - IfName: cachedAttachment.IfName, - } - if _, ok := validAttachments[gca]; ok { - continue - } - // otherwise, this attachment wasn't valid and we should issue a CNI DEL - rt := RuntimeConf{ - ContainerID: cachedAttachment.ContainerID, - NetNS: cachedAttachment.NetNS, - IfName: cachedAttachment.IfName, - Args: cachedAttachment.CniArgs, - CapabilityArgs: cachedAttachment.CapabilityArgs, - } - if err := c.DelNetworkList(ctx, list, &rt); err != nil { - errs = append(errs, fmt.Errorf("failed to delete stale attachment %s %s: %w", rt.ContainerID, rt.IfName, err)) - } - } - - // now, if the version supports it, issue a GC - if gt, _ := version.GreaterThanOrEqualTo(list.CNIVersion, "1.1.0"); gt { - inject := map[string]interface{}{ - "name": list.Name, - "cniVersion": list.CNIVersion, - } - if args != nil { - inject["cni.dev/valid-attachments"] = args.ValidAttachments - // #1101: spec used incorrect variable name - inject["cni.dev/attachments"] = args.ValidAttachments - } - - for _, plugin := range list.Plugins { - // build config here - pluginConfig, err := InjectConf(plugin, inject) - if err != nil { - errs = append(errs, fmt.Errorf("failed to generate configuration to GC plugin %s: %w", plugin.Network.Type, err)) - } - if err := c.gcNetwork(ctx, pluginConfig); err != nil { - errs = append(errs, fmt.Errorf("failed to GC plugin %s: %w", plugin.Network.Type, err)) - } - } - } - - return errors.Join(errs...) -} - -func (c *CNIConfig) gcNetwork(ctx context.Context, net *PluginConfig) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - args := c.args("GC", &RuntimeConf{}) - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, net.Bytes, args, c.exec) -} - -func (c *CNIConfig) GetStatusNetworkList(ctx context.Context, list *NetworkConfigList) error { - // If the version doesn't support status, abort. - if gt, _ := version.GreaterThanOrEqualTo(list.CNIVersion, "1.1.0"); !gt { - return nil - } - - inject := map[string]interface{}{ - "name": list.Name, - "cniVersion": list.CNIVersion, - } - - for _, plugin := range list.Plugins { - // build config here - pluginConfig, err := InjectConf(plugin, inject) - if err != nil { - return fmt.Errorf("failed to generate configuration to get plugin STATUS %s: %w", plugin.Network.Type, err) - } - if err := c.getStatusNetwork(ctx, pluginConfig); err != nil { - return err // Don't collect errors here, so we return a clean error code. - } - } - return nil -} - -func (c *CNIConfig) getStatusNetwork(ctx context.Context, net *PluginConfig) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - args := c.args("STATUS", &RuntimeConf{}) - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, net.Bytes, args, c.exec) -} - -// ===== -func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args { - return &invoke.Args{ - Command: action, - ContainerID: rt.ContainerID, - NetNS: rt.NetNS, - PluginArgs: rt.Args, - IfName: rt.IfName, - Path: strings.Join(c.Path, string(os.PathListSeparator)), - } -} diff --git a/vendor/github.com/containernetworking/cni/libcni/conf.go b/vendor/github.com/containernetworking/cni/libcni/conf.go deleted file mode 100644 index 7f8482e75e1..00000000000 --- a/vendor/github.com/containernetworking/cni/libcni/conf.go +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright 2015 CNI 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 libcni - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "slices" - "sort" - "strings" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/version" -) - -type NotFoundError struct { - Dir string - Name string -} - -func (e NotFoundError) Error() string { - return fmt.Sprintf(`no net configuration with name "%s" in %s`, e.Name, e.Dir) -} - -type NoConfigsFoundError struct { - Dir string -} - -func (e NoConfigsFoundError) Error() string { - return fmt.Sprintf(`no net configurations found in %s`, e.Dir) -} - -// This will not validate that the plugins actually belong to the netconfig by ensuring -// that they are loaded from a directory named after the networkName, relative to the network config. -// -// Since here we are just accepting raw bytes, the caller is responsible for ensuring that the plugin -// config provided here actually "belongs" to the networkconfig in question. -func NetworkPluginConfFromBytes(pluginConfBytes []byte) (*PluginConfig, error) { - // TODO why are we creating a struct that holds both the byte representation and the deserialized - // representation, and returning that, instead of just returning the deserialized representation? - conf := &PluginConfig{Bytes: pluginConfBytes, Network: &types.PluginConf{}} - if err := json.Unmarshal(pluginConfBytes, conf.Network); err != nil { - return nil, fmt.Errorf("error parsing configuration: %w", err) - } - if conf.Network.Type == "" { - return nil, fmt.Errorf("error parsing configuration: missing 'type'") - } - return conf, nil -} - -// Given a path to a directory containing a network configuration, and the name of a network, -// loads all plugin definitions found at path `networkConfPath/networkName/*.conf` -func NetworkPluginConfsFromFiles(networkConfPath, networkName string) ([]*PluginConfig, error) { - var pConfs []*PluginConfig - - pluginConfPath := filepath.Join(networkConfPath, networkName) - - pluginConfFiles, err := ConfFiles(pluginConfPath, []string{".conf"}) - if err != nil { - return nil, fmt.Errorf("failed to read plugin config files in %s: %w", pluginConfPath, err) - } - - for _, pluginConfFile := range pluginConfFiles { - pluginConfBytes, err := os.ReadFile(pluginConfFile) - if err != nil { - return nil, fmt.Errorf("error reading %s: %w", pluginConfFile, err) - } - pluginConf, err := NetworkPluginConfFromBytes(pluginConfBytes) - if err != nil { - return nil, err - } - pConfs = append(pConfs, pluginConf) - } - return pConfs, nil -} - -func NetworkConfFromBytes(confBytes []byte) (*NetworkConfigList, error) { - rawList := make(map[string]interface{}) - if err := json.Unmarshal(confBytes, &rawList); err != nil { - return nil, fmt.Errorf("error parsing configuration list: %w", err) - } - - rawName, ok := rawList["name"] - if !ok { - return nil, fmt.Errorf("error parsing configuration list: no name") - } - name, ok := rawName.(string) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid name type %T", rawName) - } - - var cniVersion string - rawVersion, ok := rawList["cniVersion"] - if ok { - cniVersion, ok = rawVersion.(string) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion type %T", rawVersion) - } - } - - rawVersions, ok := rawList["cniVersions"] - if ok { - // Parse the current package CNI version - rvs, ok := rawVersions.([]interface{}) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid type for cniVersions: %T", rvs) - } - vs := make([]string, 0, len(rvs)) - for i, rv := range rvs { - v, ok := rv.(string) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid type for cniVersions index %d: %T", i, rv) - } - gt, err := version.GreaterThan(v, version.Current()) - if err != nil { - return nil, fmt.Errorf("error parsing configuration list: invalid cniVersions entry %s at index %d: %w", v, i, err) - } else if !gt { - // Skip versions "greater" than this implementation of the spec - vs = append(vs, v) - } - } - - // if cniVersion was already set, append it to the list for sorting. - if cniVersion != "" { - gt, err := version.GreaterThan(cniVersion, version.Current()) - if err != nil { - return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion %s: %w", cniVersion, err) - } else if !gt { - // ignore any versions higher than the current implemented spec version - vs = append(vs, cniVersion) - } - } - slices.SortFunc[[]string](vs, func(v1, v2 string) int { - if v1 == v2 { - return 0 - } - if gt, _ := version.GreaterThan(v1, v2); gt { - return 1 - } - return -1 - }) - if len(vs) > 0 { - cniVersion = vs[len(vs)-1] - } - } - - readBool := func(key string) (bool, error) { - rawVal, ok := rawList[key] - if !ok { - return false, nil - } - if b, ok := rawVal.(bool); ok { - return b, nil - } - - s, ok := rawVal.(string) - if !ok { - return false, fmt.Errorf("error parsing configuration list: invalid type %T for %s", rawVal, key) - } - s = strings.ToLower(s) - switch s { - case "false": - return false, nil - case "true": - return true, nil - } - return false, fmt.Errorf("error parsing configuration list: invalid value %q for %s", s, key) - } - - disableCheck, err := readBool("disableCheck") - if err != nil { - return nil, err - } - - disableGC, err := readBool("disableGC") - if err != nil { - return nil, err - } - - loadOnlyInlinedPlugins, err := readBool("loadOnlyInlinedPlugins") - if err != nil { - return nil, err - } - - list := &NetworkConfigList{ - Name: name, - DisableCheck: disableCheck, - DisableGC: disableGC, - LoadOnlyInlinedPlugins: loadOnlyInlinedPlugins, - CNIVersion: cniVersion, - Bytes: confBytes, - } - - var plugins []interface{} - plug, ok := rawList["plugins"] - // We can have a `plugins` list key in the main conf, - // We can also have `loadOnlyInlinedPlugins == true` - // - // If `plugins` is there, then `loadOnlyInlinedPlugins` can be true - // - // If plugins is NOT there, then `loadOnlyInlinedPlugins` cannot be true - // - // We have to have at least some plugins. - if !ok && loadOnlyInlinedPlugins { - return nil, fmt.Errorf("error parsing configuration list: `loadOnlyInlinedPlugins` is true, and no 'plugins' key") - } else if !ok && !loadOnlyInlinedPlugins { - return list, nil - } - - plugins, ok = plug.([]interface{}) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid 'plugins' type %T", plug) - } - if len(plugins) == 0 { - return nil, fmt.Errorf("error parsing configuration list: no plugins in list") - } - - for i, conf := range plugins { - newBytes, err := json.Marshal(conf) - if err != nil { - return nil, fmt.Errorf("failed to marshal plugin config %d: %w", i, err) - } - netConf, err := ConfFromBytes(newBytes) - if err != nil { - return nil, fmt.Errorf("failed to parse plugin config %d: %w", i, err) - } - list.Plugins = append(list.Plugins, netConf) - } - return list, nil -} - -func NetworkConfFromFile(filename string) (*NetworkConfigList, error) { - bytes, err := os.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("error reading %s: %w", filename, err) - } - - conf, err := NetworkConfFromBytes(bytes) - if err != nil { - return nil, err - } - - if !conf.LoadOnlyInlinedPlugins { - plugins, err := NetworkPluginConfsFromFiles(filepath.Dir(filename), conf.Name) - if err != nil { - return nil, err - } - conf.Plugins = append(conf.Plugins, plugins...) - } - - if len(conf.Plugins) == 0 { - // Having 0 plugins for a given network is not necessarily a problem, - // but return as error for caller to decide, since they tried to load - return nil, fmt.Errorf("no plugin configs found") - } - return conf, nil -} - -// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions -func ConfFromBytes(bytes []byte) (*NetworkConfig, error) { - return NetworkPluginConfFromBytes(bytes) -} - -// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions -func ConfFromFile(filename string) (*NetworkConfig, error) { - bytes, err := os.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("error reading %s: %w", filename, err) - } - return ConfFromBytes(bytes) -} - -func ConfListFromBytes(bytes []byte) (*NetworkConfigList, error) { - return NetworkConfFromBytes(bytes) -} - -func ConfListFromFile(filename string) (*NetworkConfigList, error) { - return NetworkConfFromFile(filename) -} - -// ConfFiles simply returns a slice of all files in the provided directory -// with extensions matching the provided set. -func ConfFiles(dir string, extensions []string) ([]string, error) { - // In part, adapted from rkt/networking/podenv.go#listFiles - files, err := os.ReadDir(dir) - switch { - case err == nil: // break - case os.IsNotExist(err): - // If folder not there, return no error - only return an - // error if we cannot read contents or there are no contents. - return nil, nil - default: - return nil, err - } - - confFiles := []string{} - for _, f := range files { - if f.IsDir() { - continue - } - fileExt := filepath.Ext(f.Name()) - for _, ext := range extensions { - if fileExt == ext { - confFiles = append(confFiles, filepath.Join(dir, f.Name())) - } - } - } - return confFiles, nil -} - -// Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions -func LoadConf(dir, name string) (*NetworkConfig, error) { - files, err := ConfFiles(dir, []string{".conf", ".json"}) - switch { - case err != nil: - return nil, err - case len(files) == 0: - return nil, NoConfigsFoundError{Dir: dir} - } - sort.Strings(files) - - for _, confFile := range files { - conf, err := ConfFromFile(confFile) - if err != nil { - return nil, err - } - if conf.Network.Name == name { - return conf, nil - } - } - return nil, NotFoundError{dir, name} -} - -func LoadConfList(dir, name string) (*NetworkConfigList, error) { - return LoadNetworkConf(dir, name) -} - -// LoadNetworkConf looks at all the network configs in a given dir, -// loads and parses them all, and returns the first one with an extension of `.conf` -// that matches the provided network name predicate. -func LoadNetworkConf(dir, name string) (*NetworkConfigList, error) { - // TODO this .conflist/.conf extension thing is confusing and inexact - // for implementors. We should pick one extension for everything and stick with it. - files, err := ConfFiles(dir, []string{".conflist"}) - if err != nil { - return nil, err - } - sort.Strings(files) - - for _, confFile := range files { - conf, err := NetworkConfFromFile(confFile) - if err != nil { - return nil, err - } - if conf.Name == name { - return conf, nil - } - } - - // Deprecated: Try and load a network configuration file (instead of list) - // from the same name, then upconvert. - singleConf, err := LoadConf(dir, name) - if err != nil { - // A little extra logic so the error makes sense - var ncfErr NoConfigsFoundError - if len(files) != 0 && errors.As(err, &ncfErr) { - // Config lists found but no config files found - return nil, NotFoundError{dir, name} - } - - return nil, err - } - return ConfListFromConf(singleConf) -} - -// InjectConf takes a PluginConfig and inserts additional values into it, ensuring the result is serializable. -func InjectConf(original *PluginConfig, newValues map[string]interface{}) (*PluginConfig, error) { - config := make(map[string]interface{}) - err := json.Unmarshal(original.Bytes, &config) - if err != nil { - return nil, fmt.Errorf("unmarshal existing network bytes: %w", err) - } - - for key, value := range newValues { - if key == "" { - return nil, fmt.Errorf("keys cannot be empty") - } - - if value == nil { - return nil, fmt.Errorf("key '%s' value must not be nil", key) - } - - config[key] = value - } - - newBytes, err := json.Marshal(config) - if err != nil { - return nil, err - } - - return NetworkPluginConfFromBytes(newBytes) -} - -// ConfListFromConf "upconverts" a network config in to a NetworkConfigList, -// with the single network as the only entry in the list. -// -// Deprecated: Non-conflist file formats are unsupported, use NetworkConfXXX and NetworkPluginXXX functions -func ConfListFromConf(original *PluginConfig) (*NetworkConfigList, error) { - // Re-deserialize the config's json, then make a raw map configlist. - // This may seem a bit strange, but it's to make the Bytes fields - // actually make sense. Otherwise, the generated json is littered with - // golang default values. - - rawConfig := make(map[string]interface{}) - if err := json.Unmarshal(original.Bytes, &rawConfig); err != nil { - return nil, err - } - - rawConfigList := map[string]interface{}{ - "name": original.Network.Name, - "cniVersion": original.Network.CNIVersion, - "plugins": []interface{}{rawConfig}, - } - - b, err := json.Marshal(rawConfigList) - if err != nil { - return nil, err - } - return ConfListFromBytes(b) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/args.go b/vendor/github.com/containernetworking/cni/pkg/invoke/args.go deleted file mode 100644 index 3cdb4bc8dad..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/args.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "fmt" - "os" - "strings" -) - -type CNIArgs interface { - // For use with os/exec; i.e., return nil to inherit the - // environment from this process - // For use in delegation; inherit the environment from this - // process and allow overrides - AsEnv() []string -} - -type inherited struct{} - -var inheritArgsFromEnv inherited - -func (*inherited) AsEnv() []string { - return nil -} - -func ArgsFromEnv() CNIArgs { - return &inheritArgsFromEnv -} - -type Args struct { - Command string - ContainerID string - NetNS string - PluginArgs [][2]string - PluginArgsStr string - IfName string - Path string -} - -// Args implements the CNIArgs interface -var _ CNIArgs = &Args{} - -func (args *Args) AsEnv() []string { - env := os.Environ() - pluginArgsStr := args.PluginArgsStr - if pluginArgsStr == "" { - pluginArgsStr = stringify(args.PluginArgs) - } - - // Duplicated values which come first will be overridden, so we must put the - // custom values in the end to avoid being overridden by the process environments. - env = append(env, - "CNI_COMMAND="+args.Command, - "CNI_CONTAINERID="+args.ContainerID, - "CNI_NETNS="+args.NetNS, - "CNI_ARGS="+pluginArgsStr, - "CNI_IFNAME="+args.IfName, - "CNI_PATH="+args.Path, - ) - return dedupEnv(env) -} - -// taken from rkt/networking/net_plugin.go -func stringify(pluginArgs [][2]string) string { - entries := make([]string, len(pluginArgs)) - - for i, kv := range pluginArgs { - entries[i] = strings.Join(kv[:], "=") - } - - return strings.Join(entries, ";") -} - -// DelegateArgs implements the CNIArgs interface -// used for delegation to inherit from environments -// and allow some overrides like CNI_COMMAND -var _ CNIArgs = &DelegateArgs{} - -type DelegateArgs struct { - Command string -} - -func (d *DelegateArgs) AsEnv() []string { - env := os.Environ() - - // The custom values should come in the end to override the existing - // process environment of the same key. - env = append(env, - "CNI_COMMAND="+d.Command, - ) - return dedupEnv(env) -} - -// dedupEnv returns a copy of env with any duplicates removed, in favor of later values. -// Items not of the normal environment "key=value" form are preserved unchanged. -func dedupEnv(env []string) []string { - out := make([]string, 0, len(env)) - envMap := map[string]string{} - - for _, kv := range env { - // find the first "=" in environment, if not, just keep it - eq := strings.Index(kv, "=") - if eq < 0 { - out = append(out, kv) - continue - } - envMap[kv[:eq]] = kv[eq+1:] - } - - for k, v := range envMap { - out = append(out, fmt.Sprintf("%s=%s", k, v)) - } - - return out -} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go b/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go deleted file mode 100644 index c8b548e7c61..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -import ( - "context" - "os" - "path/filepath" - - "github.com/containernetworking/cni/pkg/types" -) - -func delegateCommon(delegatePlugin string, exec Exec) (string, Exec, error) { - if exec == nil { - exec = defaultExec - } - - paths := filepath.SplitList(os.Getenv("CNI_PATH")) - pluginPath, err := exec.FindInPath(delegatePlugin, paths) - if err != nil { - return "", nil, err - } - - return pluginPath, exec, nil -} - -// DelegateAdd calls the given delegate plugin with the CNI ADD action and -// JSON configuration -func DelegateAdd(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) (types.Result, error) { - pluginPath, realExec, err := delegateCommon(delegatePlugin, exec) - if err != nil { - return nil, err - } - - // DelegateAdd will override the original "CNI_COMMAND" env from process with ADD - return ExecPluginWithResult(ctx, pluginPath, netconf, delegateArgs("ADD"), realExec) -} - -// DelegateCheck calls the given delegate plugin with the CNI CHECK action and -// JSON configuration -func DelegateCheck(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - return delegateNoResult(ctx, delegatePlugin, netconf, exec, "CHECK") -} - -func delegateNoResult(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec, verb string) error { - pluginPath, realExec, err := delegateCommon(delegatePlugin, exec) - if err != nil { - return err - } - - return ExecPluginWithoutResult(ctx, pluginPath, netconf, delegateArgs(verb), realExec) -} - -// DelegateDel calls the given delegate plugin with the CNI DEL action and -// JSON configuration -func DelegateDel(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - return delegateNoResult(ctx, delegatePlugin, netconf, exec, "DEL") -} - -// DelegateStatus calls the given delegate plugin with the CNI STATUS action and -// JSON configuration -func DelegateStatus(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - return delegateNoResult(ctx, delegatePlugin, netconf, exec, "STATUS") -} - -// DelegateGC calls the given delegate plugin with the CNI GC action and -// JSON configuration -func DelegateGC(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - return delegateNoResult(ctx, delegatePlugin, netconf, exec, "GC") -} - -// return CNIArgs used by delegation -func delegateArgs(action string) *DelegateArgs { - return &DelegateArgs{ - Command: action, - } -} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go b/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go deleted file mode 100644 index a5e015fc925..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "context" - "encoding/json" - "fmt" - "os" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/create" - "github.com/containernetworking/cni/pkg/version" -) - -// Exec is an interface encapsulates all operations that deal with finding -// and executing a CNI plugin. Tests may provide a fake implementation -// to avoid writing fake plugins to temporary directories during the test. -type Exec interface { - ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error) - FindInPath(plugin string, paths []string) (string, error) - Decode(jsonBytes []byte) (version.PluginInfo, error) -} - -// Plugin must return result in same version as specified in netconf; but -// for backwards compatibility reasons if the result version is empty use -// config version (rather than technically correct 0.1.0). -// https://github.com/containernetworking/cni/issues/895 -func fixupResultVersion(netconf, result []byte) (string, []byte, error) { - versionDecoder := &version.ConfigDecoder{} - confVersion, err := versionDecoder.Decode(netconf) - if err != nil { - return "", nil, err - } - - var rawResult map[string]interface{} - if err := json.Unmarshal(result, &rawResult); err != nil { - return "", nil, fmt.Errorf("failed to unmarshal raw result: %w", err) - } - - // plugin output of "null" is successfully unmarshalled, but results in a nil - // map which causes a panic when the confVersion is assigned below. - if rawResult == nil { - rawResult = make(map[string]interface{}) - } - - // Manually decode Result version; we need to know whether its cniVersion - // is empty, while built-in decoders (correctly) substitute 0.1.0 for an - // empty version per the CNI spec. - if resultVerRaw, ok := rawResult["cniVersion"]; ok { - resultVer, ok := resultVerRaw.(string) - if ok && resultVer != "" { - return resultVer, result, nil - } - } - - // If the cniVersion is not present or empty, assume the result is - // the same CNI spec version as the config - rawResult["cniVersion"] = confVersion - newBytes, err := json.Marshal(rawResult) - if err != nil { - return "", nil, fmt.Errorf("failed to remarshal fixed result: %w", err) - } - - return confVersion, newBytes, nil -} - -// For example, a testcase could pass an instance of the following fakeExec -// object to ExecPluginWithResult() to verify the incoming stdin and environment -// and provide a tailored response: -// -// import ( -// "encoding/json" -// "path" -// "strings" -// ) -// -// type fakeExec struct { -// version.PluginDecoder -// } -// -// func (f *fakeExec) ExecPlugin(pluginPath string, stdinData []byte, environ []string) ([]byte, error) { -// net := &types.NetConf{} -// err := json.Unmarshal(stdinData, net) -// if err != nil { -// return nil, fmt.Errorf("failed to unmarshal configuration: %v", err) -// } -// pluginName := path.Base(pluginPath) -// if pluginName != net.Type { -// return nil, fmt.Errorf("plugin name %q did not match config type %q", pluginName, net.Type) -// } -// for _, e := range environ { -// // Check environment for forced failure request -// parts := strings.Split(e, "=") -// if len(parts) > 0 && parts[0] == "FAIL" { -// return nil, fmt.Errorf("failed to execute plugin %s", pluginName) -// } -// } -// return []byte("{\"CNIVersion\":\"0.4.0\"}"), nil -// } -// -// func (f *fakeExec) FindInPath(plugin string, paths []string) (string, error) { -// if len(paths) > 0 { -// return path.Join(paths[0], plugin), nil -// } -// return "", fmt.Errorf("failed to find plugin %s in paths %v", plugin, paths) -// } - -func ExecPluginWithResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) (types.Result, error) { - if exec == nil { - exec = defaultExec - } - - stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv()) - if err != nil { - return nil, err - } - - resultVersion, fixedBytes, err := fixupResultVersion(netconf, stdoutBytes) - if err != nil { - return nil, err - } - - return create.Create(resultVersion, fixedBytes) -} - -func ExecPluginWithoutResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) error { - if exec == nil { - exec = defaultExec - } - _, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv()) - return err -} - -// GetVersionInfo returns the version information available about the plugin. -// For recent-enough plugins, it uses the information returned by the VERSION -// command. For older plugins which do not recognize that command, it reports -// version 0.1.0 -func GetVersionInfo(ctx context.Context, pluginPath string, exec Exec) (version.PluginInfo, error) { - if exec == nil { - exec = defaultExec - } - args := &Args{ - Command: "VERSION", - - // set fake values required by plugins built against an older version of skel - NetNS: "dummy", - IfName: "dummy", - Path: "dummy", - } - stdin := []byte(fmt.Sprintf(`{"cniVersion":%q}`, version.Current())) - stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, stdin, args.AsEnv()) - if err != nil { - if err.Error() == "unknown CNI_COMMAND: VERSION" { - return version.PluginSupports("0.1.0"), nil - } - return nil, err - } - - return exec.Decode(stdoutBytes) -} - -// DefaultExec is an object that implements the Exec interface which looks -// for and executes plugins from disk. -type DefaultExec struct { - *RawExec - version.PluginDecoder -} - -// DefaultExec implements the Exec interface -var _ Exec = &DefaultExec{} - -var defaultExec = &DefaultExec{ - RawExec: &RawExec{Stderr: os.Stderr}, -} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/find.go b/vendor/github.com/containernetworking/cni/pkg/invoke/find.go deleted file mode 100644 index e62029eb788..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/find.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "fmt" - "os" - "path/filepath" - "strings" -) - -// FindInPath returns the full path of the plugin by searching in the provided path -func FindInPath(plugin string, paths []string) (string, error) { - if plugin == "" { - return "", fmt.Errorf("no plugin name provided") - } - - if strings.ContainsRune(plugin, os.PathSeparator) { - return "", fmt.Errorf("invalid plugin name: %s", plugin) - } - - if len(paths) == 0 { - return "", fmt.Errorf("no paths provided") - } - - for _, path := range paths { - for _, fe := range ExecutableFileExtensions { - fullpath := filepath.Join(path, plugin) + fe - if fi, err := os.Stat(fullpath); err == nil && fi.Mode().IsRegular() { - return fullpath, nil - } - } - } - - return "", fmt.Errorf("failed to find plugin %q in path %s", plugin, paths) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/os_unix.go b/vendor/github.com/containernetworking/cni/pkg/invoke/os_unix.go deleted file mode 100644 index ed0999bd0e1..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/os_unix.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2016 CNI 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. - -//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package invoke - -// Valid file extensions for plugin executables. -var ExecutableFileExtensions = []string{""} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go b/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go deleted file mode 100644 index 7665125b133..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -// Valid file extensions for plugin executables. -var ExecutableFileExtensions = []string{".exe", ""} diff --git a/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go b/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go deleted file mode 100644 index 5ab5cc88576..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os/exec" - "strings" - "time" - - "github.com/containernetworking/cni/pkg/types" -) - -type RawExec struct { - Stderr io.Writer -} - -func (e *RawExec) ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error) { - stdout := &bytes.Buffer{} - stderr := &bytes.Buffer{} - c := exec.CommandContext(ctx, pluginPath) - c.Env = environ - c.Stdin = bytes.NewBuffer(stdinData) - c.Stdout = stdout - c.Stderr = stderr - - // Retry the command on "text file busy" errors - for i := 0; i <= 5; i++ { - err := c.Run() - - // Command succeeded - if err == nil { - break - } - - // If the plugin is currently about to be written, then we wait a - // second and try it again - if strings.Contains(err.Error(), "text file busy") { - time.Sleep(time.Second) - continue - } - - // All other errors except than the busy text file - return nil, e.pluginErr(err, stdout.Bytes(), stderr.Bytes()) - } - - // Copy stderr to caller's buffer in case plugin printed to both - // stdout and stderr for some reason. Ignore failures as stderr is - // only informational. - if e.Stderr != nil && stderr.Len() > 0 { - _, _ = stderr.WriteTo(e.Stderr) - } - return stdout.Bytes(), nil -} - -func (e *RawExec) pluginErr(err error, stdout, stderr []byte) error { - emsg := types.Error{} - if len(stdout) == 0 { - if len(stderr) == 0 { - emsg.Msg = fmt.Sprintf("netplugin failed with no error message: %v", err) - } else { - emsg.Msg = fmt.Sprintf("netplugin failed: %q", string(stderr)) - } - } else if perr := json.Unmarshal(stdout, &emsg); perr != nil { - emsg.Msg = fmt.Sprintf("netplugin failed but error parsing its diagnostic message %q: %v", string(stdout), perr) - } - return &emsg -} - -func (e *RawExec) FindInPath(plugin string, paths []string) (string, error) { - return FindInPath(plugin, paths) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/020/types.go b/vendor/github.com/containernetworking/cni/pkg/types/020/types.go deleted file mode 100644 index 99b151ff240..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/020/types.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2016 CNI 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 types020 - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" - - "github.com/containernetworking/cni/pkg/types" - convert "github.com/containernetworking/cni/pkg/types/internal" -) - -const ImplementedSpecVersion string = "0.2.0" - -var supportedVersions = []string{"", "0.1.0", ImplementedSpecVersion} - -// Register converters for all versions less than the implemented spec version -func init() { - convert.RegisterConverter("0.1.0", []string{ImplementedSpecVersion}, convertFrom010) - convert.RegisterConverter(ImplementedSpecVersion, []string{"0.1.0"}, convertTo010) - - // Creator - convert.RegisterCreator(supportedVersions, NewResult) -} - -// Compatibility types for CNI version 0.1.0 and 0.2.0 - -// NewResult creates a new Result object from JSON data. The JSON data -// must be compatible with the CNI versions implemented by this type. -func NewResult(data []byte) (types.Result, error) { - result := &Result{} - if err := json.Unmarshal(data, result); err != nil { - return nil, err - } - for _, v := range supportedVersions { - if result.CNIVersion == v { - if result.CNIVersion == "" { - result.CNIVersion = "0.1.0" - } - return result, nil - } - } - return nil, fmt.Errorf("result type supports %v but unmarshalled CNIVersion is %q", - supportedVersions, result.CNIVersion) -} - -// GetResult converts the given Result object to the ImplementedSpecVersion -// and returns the concrete type or an error -func GetResult(r types.Result) (*Result, error) { - result020, err := convert.Convert(r, ImplementedSpecVersion) - if err != nil { - return nil, err - } - result, ok := result020.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - return result, nil -} - -func convertFrom010(from types.Result, toVersion string) (types.Result, error) { - if toVersion != "0.2.0" { - panic("only converts to version 0.2.0") - } - fromResult := from.(*Result) - return &Result{ - CNIVersion: ImplementedSpecVersion, - IP4: fromResult.IP4.Copy(), - IP6: fromResult.IP6.Copy(), - DNS: *fromResult.DNS.Copy(), - }, nil -} - -func convertTo010(from types.Result, toVersion string) (types.Result, error) { - if toVersion != "0.1.0" { - panic("only converts to version 0.1.0") - } - fromResult := from.(*Result) - return &Result{ - CNIVersion: "0.1.0", - IP4: fromResult.IP4.Copy(), - IP6: fromResult.IP6.Copy(), - DNS: *fromResult.DNS.Copy(), - }, nil -} - -// Result is what gets returned from the plugin (via stdout) to the caller -type Result struct { - CNIVersion string `json:"cniVersion,omitempty"` - IP4 *IPConfig `json:"ip4,omitempty"` - IP6 *IPConfig `json:"ip6,omitempty"` - DNS types.DNS `json:"dns,omitempty"` -} - -func (r *Result) Version() string { - return r.CNIVersion -} - -func (r *Result) GetAsVersion(version string) (types.Result, error) { - // If the creator of the result did not set the CNIVersion, assume it - // should be the highest spec version implemented by this Result - if r.CNIVersion == "" { - r.CNIVersion = ImplementedSpecVersion - } - return convert.Convert(r, version) -} - -func (r *Result) Print() error { - return r.PrintTo(os.Stdout) -} - -func (r *Result) PrintTo(writer io.Writer) error { - data, err := json.MarshalIndent(r, "", " ") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// IPConfig contains values necessary to configure an interface -type IPConfig struct { - IP net.IPNet - Gateway net.IP - Routes []types.Route -} - -func (i *IPConfig) Copy() *IPConfig { - if i == nil { - return nil - } - - var routes []types.Route - for _, fromRoute := range i.Routes { - routes = append(routes, *fromRoute.Copy()) - } - return &IPConfig{ - IP: i.IP, - Gateway: i.Gateway, - Routes: routes, - } -} - -// net.IPNet is not JSON (un)marshallable so this duality is needed -// for our custom IPNet type - -// JSON (un)marshallable types -type ipConfig struct { - IP types.IPNet `json:"ip"` - Gateway net.IP `json:"gateway,omitempty"` - Routes []types.Route `json:"routes,omitempty"` -} - -func (c *IPConfig) MarshalJSON() ([]byte, error) { - ipc := ipConfig{ - IP: types.IPNet(c.IP), - Gateway: c.Gateway, - Routes: c.Routes, - } - - return json.Marshal(ipc) -} - -func (c *IPConfig) UnmarshalJSON(data []byte) error { - ipc := ipConfig{} - if err := json.Unmarshal(data, &ipc); err != nil { - return err - } - - c.IP = net.IPNet(ipc.IP) - c.Gateway = ipc.Gateway - c.Routes = ipc.Routes - return nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/040/types.go b/vendor/github.com/containernetworking/cni/pkg/types/040/types.go deleted file mode 100644 index 3633b0eaa3a..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/040/types.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2016 CNI 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 types040 - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" - - "github.com/containernetworking/cni/pkg/types" - types020 "github.com/containernetworking/cni/pkg/types/020" - convert "github.com/containernetworking/cni/pkg/types/internal" -) - -const ImplementedSpecVersion string = "0.4.0" - -var supportedVersions = []string{"0.3.0", "0.3.1", ImplementedSpecVersion} - -// Register converters for all versions less than the implemented spec version -func init() { - // Up-converters - convert.RegisterConverter("0.1.0", supportedVersions, convertFrom02x) - convert.RegisterConverter("0.2.0", supportedVersions, convertFrom02x) - convert.RegisterConverter("0.3.0", supportedVersions, convertInternal) - convert.RegisterConverter("0.3.1", supportedVersions, convertInternal) - - // Down-converters - convert.RegisterConverter("0.4.0", []string{"0.3.0", "0.3.1"}, convertInternal) - convert.RegisterConverter("0.4.0", []string{"0.1.0", "0.2.0"}, convertTo02x) - convert.RegisterConverter("0.3.1", []string{"0.1.0", "0.2.0"}, convertTo02x) - convert.RegisterConverter("0.3.0", []string{"0.1.0", "0.2.0"}, convertTo02x) - - // Creator - convert.RegisterCreator(supportedVersions, NewResult) -} - -func NewResult(data []byte) (types.Result, error) { - result := &Result{} - if err := json.Unmarshal(data, result); err != nil { - return nil, err - } - for _, v := range supportedVersions { - if result.CNIVersion == v { - return result, nil - } - } - return nil, fmt.Errorf("result type supports %v but unmarshalled CNIVersion is %q", - supportedVersions, result.CNIVersion) -} - -func GetResult(r types.Result) (*Result, error) { - resultCurrent, err := r.GetAsVersion(ImplementedSpecVersion) - if err != nil { - return nil, err - } - result, ok := resultCurrent.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - return result, nil -} - -func NewResultFromResult(result types.Result) (*Result, error) { - newResult, err := convert.Convert(result, ImplementedSpecVersion) - if err != nil { - return nil, err - } - return newResult.(*Result), nil -} - -// Result is what gets returned from the plugin (via stdout) to the caller -type Result struct { - CNIVersion string `json:"cniVersion,omitempty"` - Interfaces []*Interface `json:"interfaces,omitempty"` - IPs []*IPConfig `json:"ips,omitempty"` - Routes []*types.Route `json:"routes,omitempty"` - DNS types.DNS `json:"dns,omitempty"` -} - -func convert020IPConfig(from *types020.IPConfig, ipVersion string) *IPConfig { - return &IPConfig{ - Version: ipVersion, - Address: from.IP, - Gateway: from.Gateway, - } -} - -func convertFrom02x(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*types020.Result) - toResult := &Result{ - CNIVersion: toVersion, - DNS: *fromResult.DNS.Copy(), - Routes: []*types.Route{}, - } - if fromResult.IP4 != nil { - toResult.IPs = append(toResult.IPs, convert020IPConfig(fromResult.IP4, "4")) - for _, fromRoute := range fromResult.IP4.Routes { - toResult.Routes = append(toResult.Routes, fromRoute.Copy()) - } - } - - if fromResult.IP6 != nil { - toResult.IPs = append(toResult.IPs, convert020IPConfig(fromResult.IP6, "6")) - for _, fromRoute := range fromResult.IP6.Routes { - toResult.Routes = append(toResult.Routes, fromRoute.Copy()) - } - } - - return toResult, nil -} - -func convertInternal(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*Result) - toResult := &Result{ - CNIVersion: toVersion, - DNS: *fromResult.DNS.Copy(), - Routes: []*types.Route{}, - } - for _, fromIntf := range fromResult.Interfaces { - toResult.Interfaces = append(toResult.Interfaces, fromIntf.Copy()) - } - for _, fromIPC := range fromResult.IPs { - toResult.IPs = append(toResult.IPs, fromIPC.Copy()) - } - for _, fromRoute := range fromResult.Routes { - toResult.Routes = append(toResult.Routes, fromRoute.Copy()) - } - return toResult, nil -} - -func convertTo02x(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*Result) - toResult := &types020.Result{ - CNIVersion: toVersion, - DNS: *fromResult.DNS.Copy(), - } - - for _, fromIP := range fromResult.IPs { - // Only convert the first IP address of each version as 0.2.0 - // and earlier cannot handle multiple IP addresses - if fromIP.Version == "4" && toResult.IP4 == nil { - toResult.IP4 = &types020.IPConfig{ - IP: fromIP.Address, - Gateway: fromIP.Gateway, - } - } else if fromIP.Version == "6" && toResult.IP6 == nil { - toResult.IP6 = &types020.IPConfig{ - IP: fromIP.Address, - Gateway: fromIP.Gateway, - } - } - if toResult.IP4 != nil && toResult.IP6 != nil { - break - } - } - - for _, fromRoute := range fromResult.Routes { - is4 := fromRoute.Dst.IP.To4() != nil - if is4 && toResult.IP4 != nil { - toResult.IP4.Routes = append(toResult.IP4.Routes, types.Route{ - Dst: fromRoute.Dst, - GW: fromRoute.GW, - }) - } else if !is4 && toResult.IP6 != nil { - toResult.IP6.Routes = append(toResult.IP6.Routes, types.Route{ - Dst: fromRoute.Dst, - GW: fromRoute.GW, - }) - } - } - - // 0.2.0 and earlier require at least one IP address in the Result - if toResult.IP4 == nil && toResult.IP6 == nil { - return nil, fmt.Errorf("cannot convert: no valid IP addresses") - } - - return toResult, nil -} - -func (r *Result) Version() string { - return r.CNIVersion -} - -func (r *Result) GetAsVersion(version string) (types.Result, error) { - // If the creator of the result did not set the CNIVersion, assume it - // should be the highest spec version implemented by this Result - if r.CNIVersion == "" { - r.CNIVersion = ImplementedSpecVersion - } - return convert.Convert(r, version) -} - -func (r *Result) Print() error { - return r.PrintTo(os.Stdout) -} - -func (r *Result) PrintTo(writer io.Writer) error { - data, err := json.MarshalIndent(r, "", " ") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// Interface contains values about the created interfaces -type Interface struct { - Name string `json:"name"` - Mac string `json:"mac,omitempty"` - Sandbox string `json:"sandbox,omitempty"` -} - -func (i *Interface) String() string { - return fmt.Sprintf("%+v", *i) -} - -func (i *Interface) Copy() *Interface { - if i == nil { - return nil - } - newIntf := *i - return &newIntf -} - -// Int returns a pointer to the int value passed in. Used to -// set the IPConfig.Interface field. -func Int(v int) *int { - return &v -} - -// IPConfig contains values necessary to configure an IP address on an interface -type IPConfig struct { - // IP version, either "4" or "6" - Version string - // Index into Result structs Interfaces list - Interface *int - Address net.IPNet - Gateway net.IP -} - -func (i *IPConfig) String() string { - return fmt.Sprintf("%+v", *i) -} - -func (i *IPConfig) Copy() *IPConfig { - if i == nil { - return nil - } - - ipc := &IPConfig{ - Version: i.Version, - Address: i.Address, - Gateway: i.Gateway, - } - if i.Interface != nil { - intf := *i.Interface - ipc.Interface = &intf - } - return ipc -} - -// JSON (un)marshallable types -type ipConfig struct { - Version string `json:"version"` - Interface *int `json:"interface,omitempty"` - Address types.IPNet `json:"address"` - Gateway net.IP `json:"gateway,omitempty"` -} - -func (c *IPConfig) MarshalJSON() ([]byte, error) { - ipc := ipConfig{ - Version: c.Version, - Interface: c.Interface, - Address: types.IPNet(c.Address), - Gateway: c.Gateway, - } - - return json.Marshal(ipc) -} - -func (c *IPConfig) UnmarshalJSON(data []byte) error { - ipc := ipConfig{} - if err := json.Unmarshal(data, &ipc); err != nil { - return err - } - - c.Version = ipc.Version - c.Interface = ipc.Interface - c.Address = net.IPNet(ipc.Address) - c.Gateway = ipc.Gateway - return nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/100/types.go b/vendor/github.com/containernetworking/cni/pkg/types/100/types.go deleted file mode 100644 index f58b91206dc..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/100/types.go +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright 2016 CNI 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 types100 - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" - - "github.com/containernetworking/cni/pkg/types" - types040 "github.com/containernetworking/cni/pkg/types/040" - convert "github.com/containernetworking/cni/pkg/types/internal" -) - -// The types did not change between v1.0 and v1.1 -const ImplementedSpecVersion string = "1.1.0" - -var supportedVersions = []string{"1.0.0", "1.1.0"} - -// Register converters for all versions less than the implemented spec version -func init() { - // Up-converters - convert.RegisterConverter("0.1.0", supportedVersions, convertFrom02x) - convert.RegisterConverter("0.2.0", supportedVersions, convertFrom02x) - convert.RegisterConverter("0.3.0", supportedVersions, convertFrom04x) - convert.RegisterConverter("0.3.1", supportedVersions, convertFrom04x) - convert.RegisterConverter("0.4.0", supportedVersions, convertFrom04x) - convert.RegisterConverter("1.0.0", []string{"1.1.0"}, convertFrom100) - - // Down-converters - convert.RegisterConverter("1.0.0", []string{"0.3.0", "0.3.1", "0.4.0"}, convertTo04x) - convert.RegisterConverter("1.0.0", []string{"0.1.0", "0.2.0"}, convertTo02x) - convert.RegisterConverter("1.1.0", []string{"0.3.0", "0.3.1", "0.4.0"}, convertTo04x) - convert.RegisterConverter("1.1.0", []string{"0.1.0", "0.2.0"}, convertTo02x) - convert.RegisterConverter("1.1.0", []string{"1.0.0"}, convertFrom100) - - // Creator - convert.RegisterCreator(supportedVersions, NewResult) -} - -func NewResult(data []byte) (types.Result, error) { - result := &Result{} - if err := json.Unmarshal(data, result); err != nil { - return nil, err - } - for _, v := range supportedVersions { - if result.CNIVersion == v { - return result, nil - } - } - return nil, fmt.Errorf("result type supports %v but unmarshalled CNIVersion is %q", - supportedVersions, result.CNIVersion) -} - -func GetResult(r types.Result) (*Result, error) { - resultCurrent, err := r.GetAsVersion(ImplementedSpecVersion) - if err != nil { - return nil, err - } - result, ok := resultCurrent.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - return result, nil -} - -func NewResultFromResult(result types.Result) (*Result, error) { - newResult, err := convert.Convert(result, ImplementedSpecVersion) - if err != nil { - return nil, err - } - return newResult.(*Result), nil -} - -// Result is what gets returned from the plugin (via stdout) to the caller -type Result struct { - CNIVersion string `json:"cniVersion,omitempty"` - Interfaces []*Interface `json:"interfaces,omitempty"` - IPs []*IPConfig `json:"ips,omitempty"` - Routes []*types.Route `json:"routes,omitempty"` - DNS types.DNS `json:"dns,omitempty"` -} - -// Note: DNS should be omit if DNS is empty but default Marshal function -// will output empty structure hence need to write a Marshal function -func (r *Result) MarshalJSON() ([]byte, error) { - // use type alias to escape recursion for json.Marshal() to MarshalJSON() - type fixObjType = Result - - bytes, err := json.Marshal(fixObjType(*r)) //nolint:all - if err != nil { - return nil, err - } - - fixupObj := make(map[string]interface{}) - if err := json.Unmarshal(bytes, &fixupObj); err != nil { - return nil, err - } - - if r.DNS.IsEmpty() { - delete(fixupObj, "dns") - } - - return json.Marshal(fixupObj) -} - -// convertFrom100 does nothing except set the version; the types are the same -func convertFrom100(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*Result) - - result := &Result{ - CNIVersion: toVersion, - Interfaces: fromResult.Interfaces, - IPs: fromResult.IPs, - Routes: fromResult.Routes, - DNS: fromResult.DNS, - } - return result, nil -} - -func convertFrom02x(from types.Result, toVersion string) (types.Result, error) { - result040, err := convert.Convert(from, "0.4.0") - if err != nil { - return nil, err - } - result100, err := convertFrom04x(result040, toVersion) - if err != nil { - return nil, err - } - return result100, nil -} - -func convertIPConfigFrom040(from *types040.IPConfig) *IPConfig { - to := &IPConfig{ - Address: from.Address, - Gateway: from.Gateway, - } - if from.Interface != nil { - intf := *from.Interface - to.Interface = &intf - } - return to -} - -func convertInterfaceFrom040(from *types040.Interface) *Interface { - return &Interface{ - Name: from.Name, - Mac: from.Mac, - Sandbox: from.Sandbox, - } -} - -func convertFrom04x(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*types040.Result) - toResult := &Result{ - CNIVersion: toVersion, - DNS: *fromResult.DNS.Copy(), - Routes: []*types.Route{}, - } - for _, fromIntf := range fromResult.Interfaces { - toResult.Interfaces = append(toResult.Interfaces, convertInterfaceFrom040(fromIntf)) - } - for _, fromIPC := range fromResult.IPs { - toResult.IPs = append(toResult.IPs, convertIPConfigFrom040(fromIPC)) - } - for _, fromRoute := range fromResult.Routes { - toResult.Routes = append(toResult.Routes, fromRoute.Copy()) - } - return toResult, nil -} - -func convertIPConfigTo040(from *IPConfig) *types040.IPConfig { - version := "6" - if from.Address.IP.To4() != nil { - version = "4" - } - to := &types040.IPConfig{ - Version: version, - Address: from.Address, - Gateway: from.Gateway, - } - if from.Interface != nil { - intf := *from.Interface - to.Interface = &intf - } - return to -} - -func convertInterfaceTo040(from *Interface) *types040.Interface { - return &types040.Interface{ - Name: from.Name, - Mac: from.Mac, - Sandbox: from.Sandbox, - } -} - -func convertTo04x(from types.Result, toVersion string) (types.Result, error) { - fromResult := from.(*Result) - toResult := &types040.Result{ - CNIVersion: toVersion, - DNS: *fromResult.DNS.Copy(), - Routes: []*types.Route{}, - } - for _, fromIntf := range fromResult.Interfaces { - toResult.Interfaces = append(toResult.Interfaces, convertInterfaceTo040(fromIntf)) - } - for _, fromIPC := range fromResult.IPs { - toResult.IPs = append(toResult.IPs, convertIPConfigTo040(fromIPC)) - } - for _, fromRoute := range fromResult.Routes { - toResult.Routes = append(toResult.Routes, fromRoute.Copy()) - } - return toResult, nil -} - -func convertTo02x(from types.Result, toVersion string) (types.Result, error) { - // First convert to 0.4.0 - result040, err := convertTo04x(from, "0.4.0") - if err != nil { - return nil, err - } - result02x, err := convert.Convert(result040, toVersion) - if err != nil { - return nil, err - } - return result02x, nil -} - -func (r *Result) Version() string { - return r.CNIVersion -} - -func (r *Result) GetAsVersion(version string) (types.Result, error) { - // If the creator of the result did not set the CNIVersion, assume it - // should be the highest spec version implemented by this Result - if r.CNIVersion == "" { - r.CNIVersion = ImplementedSpecVersion - } - return convert.Convert(r, version) -} - -func (r *Result) Print() error { - return r.PrintTo(os.Stdout) -} - -func (r *Result) PrintTo(writer io.Writer) error { - data, err := json.MarshalIndent(r, "", " ") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// Interface contains values about the created interfaces -type Interface struct { - Name string `json:"name"` - Mac string `json:"mac,omitempty"` - Mtu int `json:"mtu,omitempty"` - Sandbox string `json:"sandbox,omitempty"` - SocketPath string `json:"socketPath,omitempty"` - PciID string `json:"pciID,omitempty"` -} - -func (i *Interface) String() string { - return fmt.Sprintf("%+v", *i) -} - -func (i *Interface) Copy() *Interface { - if i == nil { - return nil - } - newIntf := *i - return &newIntf -} - -// Int returns a pointer to the int value passed in. Used to -// set the IPConfig.Interface field. -func Int(v int) *int { - return &v -} - -// IPConfig contains values necessary to configure an IP address on an interface -type IPConfig struct { - // Index into Result structs Interfaces list - Interface *int - Address net.IPNet - Gateway net.IP -} - -func (i *IPConfig) String() string { - return fmt.Sprintf("%+v", *i) -} - -func (i *IPConfig) Copy() *IPConfig { - if i == nil { - return nil - } - - ipc := &IPConfig{ - Address: i.Address, - Gateway: i.Gateway, - } - if i.Interface != nil { - intf := *i.Interface - ipc.Interface = &intf - } - return ipc -} - -// JSON (un)marshallable types -type ipConfig struct { - Interface *int `json:"interface,omitempty"` - Address types.IPNet `json:"address"` - Gateway net.IP `json:"gateway,omitempty"` -} - -func (c *IPConfig) MarshalJSON() ([]byte, error) { - ipc := ipConfig{ - Interface: c.Interface, - Address: types.IPNet(c.Address), - Gateway: c.Gateway, - } - - return json.Marshal(ipc) -} - -func (c *IPConfig) UnmarshalJSON(data []byte) error { - ipc := ipConfig{} - if err := json.Unmarshal(data, &ipc); err != nil { - return err - } - - c.Interface = ipc.Interface - c.Address = net.IPNet(ipc.Address) - c.Gateway = ipc.Gateway - return nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/args.go b/vendor/github.com/containernetworking/cni/pkg/types/args.go deleted file mode 100644 index 68a602bfdb4..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/args.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2015 CNI 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 types - -import ( - "encoding" - "fmt" - "reflect" - "strings" -) - -// UnmarshallableBool typedef for builtin bool -// because builtin type's methods can't be declared -type UnmarshallableBool bool - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -// Returns boolean true if the string is "1" or "true" or "True" -// Returns boolean false if the string is "0" or "false" or "False” -func (b *UnmarshallableBool) UnmarshalText(data []byte) error { - s := strings.ToLower(string(data)) - switch s { - case "1", "true": - *b = true - case "0", "false": - *b = false - default: - return fmt.Errorf("boolean unmarshal error: invalid input %s", s) - } - return nil -} - -// UnmarshallableString typedef for builtin string -type UnmarshallableString string - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -// Returns the string -func (s *UnmarshallableString) UnmarshalText(data []byte) error { - *s = UnmarshallableString(data) - return nil -} - -// CommonArgs contains the IgnoreUnknown argument -// and must be embedded by all Arg structs -type CommonArgs struct { - IgnoreUnknown UnmarshallableBool `json:"ignoreunknown,omitempty"` -} - -// GetKeyField is a helper function to receive Values -// Values that represent a pointer to a struct -func GetKeyField(keyString string, v reflect.Value) reflect.Value { - return v.Elem().FieldByName(keyString) -} - -// UnmarshalableArgsError is used to indicate error unmarshalling args -// from the args-string in the form "K=V;K2=V2;..." -type UnmarshalableArgsError struct { - error -} - -// LoadArgs parses args from a string in the form "K=V;K2=V2;..." -func LoadArgs(args string, container interface{}) error { - if args == "" { - return nil - } - - containerValue := reflect.ValueOf(container) - - pairs := strings.Split(args, ";") - unknownArgs := []string{} - for _, pair := range pairs { - kv := strings.Split(pair, "=") - if len(kv) != 2 { - return fmt.Errorf("ARGS: invalid pair %q", pair) - } - keyString := kv[0] - valueString := kv[1] - keyField := GetKeyField(keyString, containerValue) - if !keyField.IsValid() { - unknownArgs = append(unknownArgs, pair) - continue - } - - var keyFieldInterface interface{} - switch { - case keyField.Kind() == reflect.Ptr: - keyField.Set(reflect.New(keyField.Type().Elem())) - keyFieldInterface = keyField.Interface() - case keyField.CanAddr() && keyField.Addr().CanInterface(): - keyFieldInterface = keyField.Addr().Interface() - default: - return UnmarshalableArgsError{fmt.Errorf("field '%s' has no valid interface", keyString)} - } - u, ok := keyFieldInterface.(encoding.TextUnmarshaler) - if !ok { - return UnmarshalableArgsError{fmt.Errorf( - "ARGS: cannot unmarshal into field '%s' - type '%s' does not implement encoding.TextUnmarshaler", - keyString, reflect.TypeOf(keyFieldInterface))} - } - err := u.UnmarshalText([]byte(valueString)) - if err != nil { - return fmt.Errorf("ARGS: error parsing value of pair %q: %w", pair, err) - } - } - - isIgnoreUnknown := GetKeyField("IgnoreUnknown", containerValue).Bool() - if len(unknownArgs) > 0 && !isIgnoreUnknown { - return fmt.Errorf("ARGS: unknown args %q", unknownArgs) - } - return nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/create/create.go b/vendor/github.com/containernetworking/cni/pkg/types/create/create.go deleted file mode 100644 index 452cb62201d..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/create/create.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 CNI 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 create - -import ( - "encoding/json" - "fmt" - - "github.com/containernetworking/cni/pkg/types" - _ "github.com/containernetworking/cni/pkg/types/020" - _ "github.com/containernetworking/cni/pkg/types/040" - _ "github.com/containernetworking/cni/pkg/types/100" - convert "github.com/containernetworking/cni/pkg/types/internal" -) - -// DecodeVersion returns the CNI version from CNI configuration or result JSON, -// or an error if the operation could not be performed. -func DecodeVersion(jsonBytes []byte) (string, error) { - var conf struct { - CNIVersion string `json:"cniVersion"` - } - err := json.Unmarshal(jsonBytes, &conf) - if err != nil { - return "", fmt.Errorf("decoding version from network config: %w", err) - } - if conf.CNIVersion == "" { - return "0.1.0", nil - } - return conf.CNIVersion, nil -} - -// Create creates a CNI Result using the given JSON with the expected -// version, or an error if the creation could not be performed -func Create(version string, bytes []byte) (types.Result, error) { - return convert.Create(version, bytes) -} - -// CreateFromBytes creates a CNI Result from the given JSON, automatically -// detecting the CNI spec version of the result. An error is returned if the -// operation could not be performed. -func CreateFromBytes(bytes []byte) (types.Result, error) { - version, err := DecodeVersion(bytes) - if err != nil { - return nil, err - } - return convert.Create(version, bytes) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/internal/convert.go b/vendor/github.com/containernetworking/cni/pkg/types/internal/convert.go deleted file mode 100644 index bdbe4b0a59a..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/internal/convert.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2016 CNI 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 convert - -import ( - "fmt" - - "github.com/containernetworking/cni/pkg/types" -) - -// ConvertFn should convert from the given arbitrary Result type into a -// Result implementing CNI specification version passed in toVersion. -// The function is guaranteed to be passed a Result type matching the -// fromVersion it was registered with, and is guaranteed to be -// passed a toVersion matching one of the toVersions it was registered with. -type ConvertFn func(from types.Result, toVersion string) (types.Result, error) - -type converter struct { - // fromVersion is the CNI Result spec version that convertFn accepts - fromVersion string - // toVersions is a list of versions that convertFn can convert to - toVersions []string - convertFn ConvertFn -} - -var converters []*converter - -func findConverter(fromVersion, toVersion string) *converter { - for _, c := range converters { - if c.fromVersion == fromVersion { - for _, v := range c.toVersions { - if v == toVersion { - return c - } - } - } - } - return nil -} - -// Convert converts a CNI Result to the requested CNI specification version, -// or returns an error if the conversion could not be performed or failed -func Convert(from types.Result, toVersion string) (types.Result, error) { - if toVersion == "" { - toVersion = "0.1.0" - } - - fromVersion := from.Version() - - // Shortcut for same version - if fromVersion == toVersion { - return from, nil - } - - // Otherwise find the right converter - c := findConverter(fromVersion, toVersion) - if c == nil { - return nil, fmt.Errorf("no converter for CNI result version %s to %s", - fromVersion, toVersion) - } - return c.convertFn(from, toVersion) -} - -// RegisterConverter registers a CNI Result converter. SHOULD NOT BE CALLED -// EXCEPT FROM CNI ITSELF. -func RegisterConverter(fromVersion string, toVersions []string, convertFn ConvertFn) { - // Make sure there is no converter already registered for these - // from and to versions - for _, v := range toVersions { - if findConverter(fromVersion, v) != nil { - panic(fmt.Sprintf("converter already registered for %s to %s", - fromVersion, v)) - } - } - converters = append(converters, &converter{ - fromVersion: fromVersion, - toVersions: toVersions, - convertFn: convertFn, - }) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/internal/create.go b/vendor/github.com/containernetworking/cni/pkg/types/internal/create.go deleted file mode 100644 index 96363091259..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/internal/create.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2016 CNI 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 convert - -import ( - "fmt" - - "github.com/containernetworking/cni/pkg/types" -) - -type ResultFactoryFunc func([]byte) (types.Result, error) - -type creator struct { - // CNI Result spec versions that createFn can create a Result for - versions []string - createFn ResultFactoryFunc -} - -var creators []*creator - -func findCreator(version string) *creator { - for _, c := range creators { - for _, v := range c.versions { - if v == version { - return c - } - } - } - return nil -} - -// Create creates a CNI Result using the given JSON, or an error if the creation -// could not be performed -func Create(version string, bytes []byte) (types.Result, error) { - if c := findCreator(version); c != nil { - return c.createFn(bytes) - } - return nil, fmt.Errorf("unsupported CNI result version %q", version) -} - -// RegisterCreator registers a CNI Result creator. SHOULD NOT BE CALLED -// EXCEPT FROM CNI ITSELF. -func RegisterCreator(versions []string, createFn ResultFactoryFunc) { - // Make sure there is no creator already registered for these versions - for _, v := range versions { - if findCreator(v) != nil { - panic(fmt.Sprintf("creator already registered for %s", v)) - } - } - creators = append(creators, &creator{ - versions: versions, - createFn: createFn, - }) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/types/types.go b/vendor/github.com/containernetworking/cni/pkg/types/types.go deleted file mode 100644 index f4b3ce3535e..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/types/types.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2015 CNI 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 types - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" -) - -// like net.IPNet but adds JSON marshalling and unmarshalling -type IPNet net.IPNet - -// ParseCIDR takes a string like "10.2.3.1/24" and -// return IPNet with "10.2.3.1" and /24 mask -func ParseCIDR(s string) (*net.IPNet, error) { - ip, ipn, err := net.ParseCIDR(s) - if err != nil { - return nil, err - } - - ipn.IP = ip - return ipn, nil -} - -func (n IPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(&n).String()) -} - -func (n *IPNet) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - - tmp, err := ParseCIDR(s) - if err != nil { - return err - } - - *n = IPNet(*tmp) - return nil -} - -// Use PluginConf instead of NetConf, the NetConf -// backwards-compat alias will be removed in a future release. -type NetConf = PluginConf - -// PluginConf describes a plugin configuration for a specific network. -type PluginConf struct { - CNIVersion string `json:"cniVersion,omitempty"` - - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Capabilities map[string]bool `json:"capabilities,omitempty"` - IPAM IPAM `json:"ipam,omitempty"` - DNS DNS `json:"dns,omitempty"` - - RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` - PrevResult Result `json:"-"` - - // ValidAttachments is only supplied when executing a GC operation - ValidAttachments []GCAttachment `json:"cni.dev/valid-attachments,omitempty"` -} - -// GCAttachment is the parameters to a GC call -- namely, -// the container ID and ifname pair that represents a -// still-valid attachment. -type GCAttachment struct { - ContainerID string `json:"containerID"` - IfName string `json:"ifname"` -} - -// Note: DNS should be omit if DNS is empty but default Marshal function -// will output empty structure hence need to write a Marshal function -func (n *PluginConf) MarshalJSON() ([]byte, error) { - bytes, err := json.Marshal(*n) - if err != nil { - return nil, err - } - - fixupObj := make(map[string]interface{}) - if err := json.Unmarshal(bytes, &fixupObj); err != nil { - return nil, err - } - - if n.DNS.IsEmpty() { - delete(fixupObj, "dns") - } - - return json.Marshal(fixupObj) -} - -type IPAM struct { - Type string `json:"type,omitempty"` -} - -// IsEmpty returns true if IPAM structure has no value, otherwise return false -func (i *IPAM) IsEmpty() bool { - return i.Type == "" -} - -// NetConfList describes an ordered list of networks. -type NetConfList struct { - CNIVersion string `json:"cniVersion,omitempty"` - - Name string `json:"name,omitempty"` - DisableCheck bool `json:"disableCheck,omitempty"` - DisableGC bool `json:"disableGC,omitempty"` - Plugins []*PluginConf `json:"plugins,omitempty"` -} - -// Result is an interface that provides the result of plugin execution -type Result interface { - // The highest CNI specification result version the result supports - // without having to convert - Version() string - - // Returns the result converted into the requested CNI specification - // result version, or an error if conversion failed - GetAsVersion(version string) (Result, error) - - // Prints the result in JSON format to stdout - Print() error - - // Prints the result in JSON format to provided writer - PrintTo(writer io.Writer) error -} - -func PrintResult(result Result, version string) error { - newResult, err := result.GetAsVersion(version) - if err != nil { - return err - } - return newResult.Print() -} - -// DNS contains values interesting for DNS resolvers -type DNS struct { - Nameservers []string `json:"nameservers,omitempty"` - Domain string `json:"domain,omitempty"` - Search []string `json:"search,omitempty"` - Options []string `json:"options,omitempty"` -} - -// IsEmpty returns true if DNS structure has no value, otherwise return false -func (d *DNS) IsEmpty() bool { - if len(d.Nameservers) == 0 && d.Domain == "" && len(d.Search) == 0 && len(d.Options) == 0 { - return true - } - return false -} - -func (d *DNS) Copy() *DNS { - if d == nil { - return nil - } - - to := &DNS{Domain: d.Domain} - to.Nameservers = append(to.Nameservers, d.Nameservers...) - to.Search = append(to.Search, d.Search...) - to.Options = append(to.Options, d.Options...) - return to -} - -type Route struct { - Dst net.IPNet - GW net.IP - MTU int - AdvMSS int - Priority int - Table *int - Scope *int -} - -func (r *Route) String() string { - table := "" - if r.Table != nil { - table = fmt.Sprintf("%d", *r.Table) - } - - scope := "" - if r.Scope != nil { - scope = fmt.Sprintf("%d", *r.Scope) - } - - return fmt.Sprintf("{Dst:%+v GW:%v MTU:%d AdvMSS:%d Priority:%d Table:%s Scope:%s}", r.Dst, r.GW, r.MTU, r.AdvMSS, r.Priority, table, scope) -} - -func (r *Route) Copy() *Route { - if r == nil { - return nil - } - - route := &Route{ - Dst: r.Dst, - GW: r.GW, - MTU: r.MTU, - AdvMSS: r.AdvMSS, - Priority: r.Priority, - Scope: r.Scope, - } - - if r.Table != nil { - table := *r.Table - route.Table = &table - } - - if r.Scope != nil { - scope := *r.Scope - route.Scope = &scope - } - - return route -} - -// Well known error codes -// see https://github.com/containernetworking/cni/blob/main/SPEC.md#well-known-error-codes -const ( - ErrUnknown uint = iota // 0 - ErrIncompatibleCNIVersion // 1 - ErrUnsupportedField // 2 - ErrUnknownContainer // 3 - ErrInvalidEnvironmentVariables // 4 - ErrIOFailure // 5 - ErrDecodingFailure // 6 - ErrInvalidNetworkConfig // 7 - ErrInvalidNetNS // 8 - ErrTryAgainLater uint = 11 - ErrInternal uint = 999 -) - -type Error struct { - Code uint `json:"code"` - Msg string `json:"msg"` - Details string `json:"details,omitempty"` -} - -func NewError(code uint, msg, details string) *Error { - return &Error{ - Code: code, - Msg: msg, - Details: details, - } -} - -func (e *Error) Error() string { - details := "" - if e.Details != "" { - details = fmt.Sprintf("; %v", e.Details) - } - return fmt.Sprintf("%v%v", e.Msg, details) -} - -func (e *Error) Print() error { - return prettyPrint(e) -} - -// net.IPNet is not JSON (un)marshallable so this duality is needed -// for our custom IPNet type - -// JSON (un)marshallable types -type route struct { - Dst IPNet `json:"dst"` - GW net.IP `json:"gw,omitempty"` - MTU int `json:"mtu,omitempty"` - AdvMSS int `json:"advmss,omitempty"` - Priority int `json:"priority,omitempty"` - Table *int `json:"table,omitempty"` - Scope *int `json:"scope,omitempty"` -} - -func (r *Route) UnmarshalJSON(data []byte) error { - rt := route{} - if err := json.Unmarshal(data, &rt); err != nil { - return err - } - - r.Dst = net.IPNet(rt.Dst) - r.GW = rt.GW - r.MTU = rt.MTU - r.AdvMSS = rt.AdvMSS - r.Priority = rt.Priority - r.Table = rt.Table - r.Scope = rt.Scope - - return nil -} - -func (r Route) MarshalJSON() ([]byte, error) { - rt := route{ - Dst: IPNet(r.Dst), - GW: r.GW, - MTU: r.MTU, - AdvMSS: r.AdvMSS, - Priority: r.Priority, - Table: r.Table, - Scope: r.Scope, - } - - return json.Marshal(rt) -} - -func prettyPrint(obj interface{}) error { - data, err := json.MarshalIndent(obj, "", " ") - if err != nil { - return err - } - _, err = os.Stdout.Write(data) - return err -} diff --git a/vendor/github.com/containernetworking/cni/pkg/utils/utils.go b/vendor/github.com/containernetworking/cni/pkg/utils/utils.go deleted file mode 100644 index 1981d255691..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/utils/utils.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2019 CNI 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 utils - -import ( - "bytes" - "fmt" - "regexp" - "unicode" - - "github.com/containernetworking/cni/pkg/types" -) - -const ( - // cniValidNameChars is the regexp used to validate valid characters in - // containerID and networkName - cniValidNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.\-]` - - // maxInterfaceNameLength is the length max of a valid interface name - maxInterfaceNameLength = 15 -) - -var cniReg = regexp.MustCompile(`^` + cniValidNameChars + `*$`) - -// ValidateContainerID will validate that the supplied containerID is not empty does not contain invalid characters -func ValidateContainerID(containerID string) *types.Error { - if containerID == "" { - return types.NewError(types.ErrUnknownContainer, "missing containerID", "") - } - if !cniReg.MatchString(containerID) { - return types.NewError(types.ErrInvalidEnvironmentVariables, "invalid characters in containerID", containerID) - } - return nil -} - -// ValidateNetworkName will validate that the supplied networkName does not contain invalid characters -func ValidateNetworkName(networkName string) *types.Error { - if networkName == "" { - return types.NewError(types.ErrInvalidNetworkConfig, "missing network name:", "") - } - if !cniReg.MatchString(networkName) { - return types.NewError(types.ErrInvalidNetworkConfig, "invalid characters found in network name", networkName) - } - return nil -} - -// ValidateInterfaceName will validate the interface name based on the four rules below -// 1. The name must not be empty -// 2. The name must be less than 16 characters -// 3. The name must not be "." or ".." -// 4. The name must not contain / or : or any whitespace characters -// ref to https://github.com/torvalds/linux/blob/master/net/core/dev.c#L1024 -func ValidateInterfaceName(ifName string) *types.Error { - if len(ifName) == 0 { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is empty", "") - } - if len(ifName) > maxInterfaceNameLength { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is too long", fmt.Sprintf("interface name should be less than %d characters", maxInterfaceNameLength+1)) - } - if ifName == "." || ifName == ".." { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is . or ..", "") - } - for _, r := range bytes.Runes([]byte(ifName)) { - if r == '/' || r == ':' || unicode.IsSpace(r) { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name contains / or : or whitespace characters", "") - } - } - - return nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/version/conf.go b/vendor/github.com/containernetworking/cni/pkg/version/conf.go deleted file mode 100644 index 808c33b8382..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/version/conf.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "github.com/containernetworking/cni/pkg/types/create" -) - -// ConfigDecoder can decode the CNI version available in network config data -type ConfigDecoder struct{} - -func (*ConfigDecoder) Decode(jsonBytes []byte) (string, error) { - return create.DecodeVersion(jsonBytes) -} diff --git a/vendor/github.com/containernetworking/cni/pkg/version/plugin.go b/vendor/github.com/containernetworking/cni/pkg/version/plugin.go deleted file mode 100644 index e3bd375bca1..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/version/plugin.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "encoding/json" - "fmt" - "io" - "strconv" - "strings" -) - -// PluginInfo reports information about CNI versioning -type PluginInfo interface { - // SupportedVersions returns one or more CNI spec versions that the plugin - // supports. If input is provided in one of these versions, then the plugin - // promises to use the same CNI version in its response - SupportedVersions() []string - - // Encode writes this CNI version information as JSON to the given Writer - Encode(io.Writer) error -} - -type pluginInfo struct { - CNIVersion_ string `json:"cniVersion"` - SupportedVersions_ []string `json:"supportedVersions,omitempty"` -} - -// pluginInfo implements the PluginInfo interface -var _ PluginInfo = &pluginInfo{} - -func (p *pluginInfo) Encode(w io.Writer) error { - return json.NewEncoder(w).Encode(p) -} - -func (p *pluginInfo) SupportedVersions() []string { - return p.SupportedVersions_ -} - -// PluginSupports returns a new PluginInfo that will report the given versions -// as supported -func PluginSupports(supportedVersions ...string) PluginInfo { - if len(supportedVersions) < 1 { - panic("programmer error: you must support at least one version") - } - return &pluginInfo{ - CNIVersion_: Current(), - SupportedVersions_: supportedVersions, - } -} - -// PluginDecoder can decode the response returned by a plugin's VERSION command -type PluginDecoder struct{} - -func (*PluginDecoder) Decode(jsonBytes []byte) (PluginInfo, error) { - var info pluginInfo - err := json.Unmarshal(jsonBytes, &info) - if err != nil { - return nil, fmt.Errorf("decoding version info: %w", err) - } - if info.CNIVersion_ == "" { - return nil, fmt.Errorf("decoding version info: missing field cniVersion") - } - if len(info.SupportedVersions_) == 0 { - if info.CNIVersion_ == "0.2.0" { - return PluginSupports("0.1.0", "0.2.0"), nil - } - return nil, fmt.Errorf("decoding version info: missing field supportedVersions") - } - return &info, nil -} - -// ParseVersion parses a version string like "3.0.1" or "0.4.5" into major, -// minor, and micro numbers or returns an error -func ParseVersion(version string) (int, int, int, error) { - var major, minor, micro int - if version == "" { // special case: no version declared == v0.1.0 - return 0, 1, 0, nil - } - - parts := strings.Split(version, ".") - if len(parts) >= 4 { - return -1, -1, -1, fmt.Errorf("invalid version %q: too many parts", version) - } - - major, err := strconv.Atoi(parts[0]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert major version part %q: %w", parts[0], err) - } - - if len(parts) >= 2 { - minor, err = strconv.Atoi(parts[1]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert minor version part %q: %w", parts[1], err) - } - } - - if len(parts) >= 3 { - micro, err = strconv.Atoi(parts[2]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert micro version part %q: %w", parts[2], err) - } - } - - return major, minor, micro, nil -} - -// GreaterThanOrEqualTo takes two string versions, parses them into major/minor/micro -// numbers, and compares them to determine whether the first version is greater -// than or equal to the second -func GreaterThanOrEqualTo(version, otherVersion string) (bool, error) { - firstMajor, firstMinor, firstMicro, err := ParseVersion(version) - if err != nil { - return false, err - } - - secondMajor, secondMinor, secondMicro, err := ParseVersion(otherVersion) - if err != nil { - return false, err - } - - if firstMajor > secondMajor { - return true, nil - } else if firstMajor == secondMajor { - if firstMinor > secondMinor { - return true, nil - } else if firstMinor == secondMinor && firstMicro >= secondMicro { - return true, nil - } - } - return false, nil -} - -// GreaterThan returns true if the first version is greater than the second -func GreaterThan(version, otherVersion string) (bool, error) { - firstMajor, firstMinor, firstMicro, err := ParseVersion(version) - if err != nil { - return false, err - } - - secondMajor, secondMinor, secondMicro, err := ParseVersion(otherVersion) - if err != nil { - return false, err - } - - if firstMajor > secondMajor { - return true, nil - } else if firstMajor == secondMajor { - if firstMinor > secondMinor { - return true, nil - } else if firstMinor == secondMinor && firstMicro > secondMicro { - return true, nil - } - } - return false, nil -} diff --git a/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go b/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go deleted file mode 100644 index 25c3810b2aa..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 CNI 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 version - -import "fmt" - -type ErrorIncompatible struct { - Config string - Supported []string -} - -func (e *ErrorIncompatible) Details() string { - return fmt.Sprintf("config is %q, plugin supports %q", e.Config, e.Supported) -} - -func (e *ErrorIncompatible) Error() string { - return fmt.Sprintf("incompatible CNI versions: %s", e.Details()) -} - -type Reconciler struct{} - -func (r *Reconciler) Check(configVersion string, pluginInfo PluginInfo) *ErrorIncompatible { - return r.CheckRaw(configVersion, pluginInfo.SupportedVersions()) -} - -func (*Reconciler) CheckRaw(configVersion string, supportedVersions []string) *ErrorIncompatible { - for _, supportedVersion := range supportedVersions { - if configVersion == supportedVersion { - return nil - } - } - - return &ErrorIncompatible{ - Config: configVersion, - Supported: supportedVersions, - } -} diff --git a/vendor/github.com/containernetworking/cni/pkg/version/version.go b/vendor/github.com/containernetworking/cni/pkg/version/version.go deleted file mode 100644 index cfb6a12fa35..00000000000 --- a/vendor/github.com/containernetworking/cni/pkg/version/version.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "encoding/json" - "fmt" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/create" -) - -// Current reports the version of the CNI spec implemented by this library -func Current() string { - return "1.1.0" -} - -// Legacy PluginInfo describes a plugin that is backwards compatible with the -// CNI spec version 0.1.0. In particular, a runtime compiled against the 0.1.0 -// library ought to work correctly with a plugin that reports support for -// Legacy versions. -// -// Any future CNI spec versions which meet this definition should be added to -// this list. -var ( - Legacy = PluginSupports("0.1.0", "0.2.0") - All = PluginSupports("0.1.0", "0.2.0", "0.3.0", "0.3.1", "0.4.0", "1.0.0", "1.1.0") -) - -// VersionsFrom returns a list of versions starting from min, inclusive -func VersionsStartingFrom(min string) PluginInfo { - out := []string{} - // cheat, just assume ordered - ok := false - for _, v := range All.SupportedVersions() { - if !ok && v == min { - ok = true - } - if ok { - out = append(out, v) - } - } - return PluginSupports(out...) -} - -// Finds a Result object matching the requested version (if any) and asks -// that object to parse the plugin result, returning an error if parsing failed. -func NewResult(version string, resultBytes []byte) (types.Result, error) { - return create.Create(version, resultBytes) -} - -// ParsePrevResult parses a prevResult in a NetConf structure and sets -// the NetConf's PrevResult member to the parsed Result object. -func ParsePrevResult(conf *types.PluginConf) error { - if conf.RawPrevResult == nil { - return nil - } - - // Prior to 1.0.0, Result types may not marshal a CNIVersion. Since the - // result version must match the config version, if the Result's version - // is empty, inject the config version. - if ver, ok := conf.RawPrevResult["CNIVersion"]; !ok || ver == "" { - conf.RawPrevResult["CNIVersion"] = conf.CNIVersion - } - - resultBytes, err := json.Marshal(conf.RawPrevResult) - if err != nil { - return fmt.Errorf("could not serialize prevResult: %w", err) - } - - conf.RawPrevResult = nil - conf.PrevResult, err = create.Create(conf.CNIVersion, resultBytes) - if err != nil { - return fmt.Errorf("could not parse prevResult: %w", err) - } - - return nil -} diff --git a/vendor/github.com/containers/buildah/.cirrus.yml b/vendor/github.com/containers/buildah/.cirrus.yml index 2c71589ffb9..c181ae0d8c9 100644 --- a/vendor/github.com/containers/buildah/.cirrus.yml +++ b/vendor/github.com/containers/buildah/.cirrus.yml @@ -36,7 +36,7 @@ env: DEBIAN_NAME: "debian-14" # Image identifiers - IMAGE_SUFFIX: "c20251211t152018z-f43f42d14" + IMAGE_SUFFIX: "c20260310t170224z-f43f42d14" FEDORA_CACHE_IMAGE_NAME: "fedora-${IMAGE_SUFFIX}" PRIOR_FEDORA_CACHE_IMAGE_NAME: "prior-fedora-${IMAGE_SUFFIX}" RAWHIDE_CACHE_IMAGE_NAME: "rawhide-${IMAGE_SUFFIX}" # Used temporarily for rust-podman-sequoia. After that RPM is available in stable Fedora releases, we can stop testing against Rawhide again. @@ -127,7 +127,7 @@ vendor_task: # Runs within Cirrus's "community cluster" container: - image: docker.io/library/golang:1.24.6 + image: docker.io/library/golang:1.25 cpu: 1 memory: 1 @@ -178,6 +178,15 @@ unit_task: setup_script: '${SCRIPT_BASE}/setup.sh |& ${_TIMESTAMP}' unit_test_script: '${SCRIPT_BASE}/test.sh unit |& ${_TIMESTAMP}' + always: &standardlogs + audit_log_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh audit' + df_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh df' + journal_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh journal' + podman_system_info_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh podman' + buildah_version_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh buildah_version' + buildah_info_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh buildah_info' + package_versions_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh packages' + golang_version_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh golang' conformance_task: name: 'Debian Conformance w/ $STORAGE_DRIVER' @@ -199,6 +208,8 @@ conformance_task: setup_script: '${SCRIPT_BASE}/setup.sh conformance |& ${_TIMESTAMP}' conformance_test_script: '${SCRIPT_BASE}/test.sh conformance |& ${_TIMESTAMP}' + always: + <<: *standardlogs integration_task: name: "Integration $DISTRO_NV$RUNTIME_N w/ $STORAGE_DRIVER" @@ -284,15 +295,8 @@ integration_task: binary_artifacts: path: ./bin/* - always: &standardlogs - audit_log_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh audit' - df_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh df' - journal_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh journal' - podman_system_info_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh podman' - buildah_version_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh buildah_version' - buildah_info_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh buildah_info' - package_versions_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh packages' - golang_version_script: '$GOSRC/$SCRIPT_BASE/logcollector.sh golang' + always: + <<: *standardlogs integration_rootless_task: name: "Integration rootless $DISTRO_NV$RUNTIME_N w/ $STORAGE_DRIVER" diff --git a/vendor/github.com/containers/buildah/Makefile b/vendor/github.com/containers/buildah/Makefile index 65084fa07f9..a822f38830e 100644 --- a/vendor/github.com/containers/buildah/Makefile +++ b/vendor/github.com/containers/buildah/Makefile @@ -5,8 +5,6 @@ STORAGETAGS := $(shell ./btrfs_installed_tag.sh) $(shell ./hack/libsubid_tag.sh) SECURITYTAGS ?= seccomp $(APPARMORTAG) TAGS ?= $(SECURITYTAGS) $(STORAGETAGS) $(shell ./hack/systemd_tag.sh) $(shell ./hack/sqlite_tag.sh) ifeq ($(shell uname -s),FreeBSD) -# FreeBSD needs CNI until netavark is supported -TAGS += cni endif BUILDTAGS += $(TAGS) $(EXTRA_BUILD_TAGS) PREFIX := /usr/local @@ -35,11 +33,9 @@ SOURCE_DATE_EPOCH ?= $(if $(shell date +%s),$(shell date +%s),$(error "date fail # strings, while the 4.x we have on Linux doesn't. this is the documented # workaround COMMENT := \# -CNI_COMMIT := $(shell sed -n 's;^$(COMMENT) github.com/containernetworking/cni \([^ \n]*\).*$$;\1;p' vendor/modules.txt) - SEQUOIA_SONAME_DIR = EXTRA_LDFLAGS ?= -BUILDAH_LDFLAGS := $(GO_LDFLAGS) '-X main.GitCommit=$(GIT_COMMIT) -X main.buildInfo=$(SOURCE_DATE_EPOCH) -X main.cniVersion=$(CNI_COMMIT) -X go.podman.io/image/v5/signature/internal/sequoia.sequoiaLibraryDir="$(SEQUOIA_SONAME_DIR)" $(EXTRA_LDFLAGS)' +BUILDAH_LDFLAGS := $(GO_LDFLAGS) '-X main.GitCommit=$(GIT_COMMIT) -X main.buildInfo=$(SOURCE_DATE_EPOCH) -X go.podman.io/image/v5/signature/internal/sequoia.sequoiaLibraryDir="$(SEQUOIA_SONAME_DIR)" $(EXTRA_LDFLAGS)' # This isn't what we actually build; it's a superset, used for target # dependencies. Basically: all *.go and *.c files, except *_test.go, @@ -54,13 +50,13 @@ ifeq ($(BUILDDEBUG), 1) endif # Managed by renovate. -export GOLANGCI_LINT_VERSION := 2.9.0 +export GOLANGCI_LINT_VERSION := 2.11.1 # make all BUILDDEBUG=1 # Note: Uses the -N -l go compiler options to disable compiler optimizations # and inlining. Using these build options allows you to subsequently # use source debugging tools like delve. -all: bin/buildah bin/imgtype bin/copy bin/inet bin/tutorial bin/dumpspec bin/passwd bin/crash bin/wait docs +all: bin/buildah bin/imgtype bin/copy bin/inet bin/tutorial bin/dumpspec bin/passwd bin/crash bin/wait bin/grpcnoop docs bin/buildah: $(SOURCES) internal/mkcw/embed/entrypoint_amd64.gz $(GO_BUILD) $(BUILDAH_LDFLAGS) $(GO_GCFLAGS) "$(GOGCFLAGS)" -o $@ $(BUILDFLAGS) ./cmd/buildah @@ -131,6 +127,9 @@ bin/inet: tests/inet/inet.go bin/passwd: tests/passwd/passwd.go $(GO_BUILD) $(BUILDAH_LDFLAGS) -o $@ $(BUILDFLAGS) ./tests/passwd/passwd.go +bin/grpcnoop: tests/rpc/noop/noop.go + $(GO_BUILD) $(BUILDAH_LDFLAGS) -o $@ $(BUILDFLAGS) ./tests/rpc/noop/noop.go + .PHONY: clean clean: $(RM) -r bin tests/testreport/testreport tests/conformance/testdata/mount-targets/true internal/mkcw/embed/entrypoint_amd64 internal/mkcw/embed/entrypoint_arm64 internal/mkcw/embed/entrypoint_ppc64le internal/mkcw/embed/entrypoint_s390x internal/mkcw/embed/*.gz internal/mkcw/embed/asm/*.o diff --git a/vendor/github.com/containers/buildah/buildah.go b/vendor/github.com/containers/buildah/buildah.go index 27d67b63316..44a78649230 100644 --- a/vendor/github.com/containers/buildah/buildah.go +++ b/vendor/github.com/containers/buildah/buildah.go @@ -147,14 +147,13 @@ type Builder struct { // namespace), effectively deciding whether or not the process has a // usable network. ConfigureNetwork define.NetworkConfigurationPolicy - // CNIPluginPath is the location of CNI plugin helpers, if they should be - // run from a location other than the default location. + // Deprecated: CNIPluginPath was the location of CNI plugin helpers. + // It is no longer used and is expected to be empty. CNIPluginPath string - // CNIConfigDir is the location of CNI configuration files, if the files in - // the default configuration directory shouldn't be used. + // Deprecated: CNIConfigDir was the location of CNI configuration files. + // It is no longer used and is expected to be empty. CNIConfigDir string - - // NetworkInterface is the libnetwork network interface used to setup CNI or netavark networks. + // NetworkInterface is the libnetwork network interface used to setup netavark networks. NetworkInterface nettypes.ContainerNetwork `json:"-"` // GroupAdd is a list of groups to add to the primary process when Run() is @@ -224,13 +223,15 @@ type BuilderInfo struct { NamespaceOptions define.NamespaceOptions Capabilities []string ConfigureNetwork string - CNIPluginPath string - CNIConfigDir string - IDMappingOptions define.IDMappingOptions - History []v1.History - Devices define.ContainerDevices - DeviceSpecs []string - CDIConfigDir string + // Deprecated: CNIPluginPath is no longer used and is expected to be empty. + CNIPluginPath string + // Deprecated: CNIConfigDir is no longer used and is expected to be empty. + CNIConfigDir string + IDMappingOptions define.IDMappingOptions + History []v1.History + Devices define.ContainerDevices + DeviceSpecs []string + CDIConfigDir string } // GetBuildInfo gets a pointer to a Builder object and returns a BuilderInfo object from it. @@ -261,8 +262,6 @@ func GetBuildInfo(b *Builder) BuilderInfo { Isolation: b.Isolation.String(), NamespaceOptions: b.NamespaceOptions, ConfigureNetwork: fmt.Sprintf("%v", b.ConfigureNetwork), - CNIPluginPath: b.CNIPluginPath, - CNIConfigDir: b.CNIConfigDir, IDMappingOptions: b.IDMappingOptions, Capabilities: b.Capabilities, History: history, @@ -333,14 +332,13 @@ type BuilderOptions struct { // namespace), effectively deciding whether or not the process has a // usable network. ConfigureNetwork define.NetworkConfigurationPolicy - // CNIPluginPath is the location of CNI plugin helpers, if they should be - // run from a location other than the default location. + // Deprecated: CNIPluginPath was the location of CNI plugin helpers. + // It is no longer used and is expected to be empty. CNIPluginPath string - // CNIConfigDir is the location of CNI configuration files, if the files in - // the default configuration directory shouldn't be used. + // Deprecated: CNIConfigDir was the location of CNI configuration files. + // It is no longer used and is expected to be empty. CNIConfigDir string - - // NetworkInterface is the libnetwork network interface used to setup CNI or netavark networks. + // NetworkInterface is the libnetwork network interface used to setup netavark networks. NetworkInterface nettypes.ContainerNetwork `json:"-"` // ID mapping options to use if we're setting up our own user namespace. @@ -462,7 +460,7 @@ func OpenBuilder(store storage.Store, container string) (*Builder, error) { return nil, fmt.Errorf("container %q is not a %s container (is a %q container)", container, define.Package, b.Type) } - netInt, err := getNetworkInterface(store, b.CNIConfigDir, b.CNIPluginPath) + netInt, err := getNetworkInterface(store) if err != nil { return nil, err } diff --git a/vendor/github.com/containers/buildah/chroot/run_common.go b/vendor/github.com/containers/buildah/chroot/run_common.go index fbd0689f6af..c6d4825be58 100644 --- a/vendor/github.com/containers/buildah/chroot/run_common.go +++ b/vendor/github.com/containers/buildah/chroot/run_common.go @@ -35,8 +35,6 @@ const ( runUsingChrootCommand = "buildah-chroot-runtime" // runUsingChrootExec is a command we use as a key for reexec runUsingChrootExecCommand = "buildah-chroot-exec" - // containersConfEnv is an environment variable that we need to pass down except for the command itself - containersConfEnv = "CONTAINERS_CONF" ) func init() { @@ -133,9 +131,6 @@ func RunUsingChroot(spec *specs.Spec, bundlePath, homeDir string, stdin io.Reade cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr cmd.Dir = "/" cmd.Env = []string{fmt.Sprintf("LOGLEVEL=%d", logrus.GetLevel())} - if _, ok := os.LookupEnv(containersConfEnv); ok { - cmd.Env = append(cmd.Env, containersConfEnv+"="+os.Getenv(containersConfEnv)) - } interrupted := make(chan os.Signal, 100) cmd.Hook = func(int) error { @@ -521,9 +516,6 @@ func runUsingChroot(spec *specs.Spec, bundlePath string, ctty *os.File, stdin io cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr cmd.Dir = "/" cmd.Env = []string{fmt.Sprintf("LOGLEVEL=%d", logrus.GetLevel())} - if _, ok := os.LookupEnv(containersConfEnv); ok { - cmd.Env = append(cmd.Env, containersConfEnv+"="+os.Getenv(containersConfEnv)) - } if ctty != nil { cmd.Setsid = true cmd.Ctty = ctty diff --git a/vendor/github.com/containers/buildah/config.go b/vendor/github.com/containers/buildah/config.go index a5381972265..a3f3b604474 100644 --- a/vendor/github.com/containers/buildah/config.go +++ b/vendor/github.com/containers/buildah/config.go @@ -383,10 +383,11 @@ func (b *Builder) Shell() []string { // commands in the container, or in a container built using an image built from // this container. // Note: this setting is not present in the OCIv1 image format, so it is -// discarded when writing images using OCIv1 formats. +// discarded when writing images using OCIv1 formats, even though it is used +// for subsequent RUN instructions while building this image. func (b *Builder) SetShell(shell []string) { if len(shell) > 0 && b.Format != define.Dockerv2ImageManifest { - b.Logger.Warnf("SHELL is not supported for OCI image format, %s will be ignored. Must use `docker` format", shell) + b.Logger.Warnf("SHELL is not persisted in the OCI image format, %s will be used for RUN subsequent instructions to build this image but will not be present in saved image which may affect any images that use this as a base. Must use `docker` format to persist in saved image", shell) } b.Docker.Config.Shell = slices.Clone(shell) diff --git a/vendor/github.com/containers/buildah/define/build.go b/vendor/github.com/containers/buildah/define/build.go index 90c76f592bd..3861fe23611 100644 --- a/vendor/github.com/containers/buildah/define/build.go +++ b/vendor/github.com/containers/buildah/define/build.go @@ -236,14 +236,13 @@ type BuildOptions struct { // namespace), effectively deciding whether or not the process has a // usable network. ConfigureNetwork NetworkConfigurationPolicy - // CNIPluginPath is the location of CNI plugin helpers, if they should be - // run from a location other than the default location. + // Deprecated: CNIPluginPath was the location of CNI plugin helpers. + // It is no longer used and is expected to be empty. CNIPluginPath string - // CNIConfigDir is the location of CNI configuration files, if the files in - // the default configuration directory shouldn't be used. + // Deprecated: CNIConfigDir was the location of CNI configuration files. + // It is no longer used and is expected to be empty. CNIConfigDir string - - // NetworkInterface is the libnetwork network interface used to setup CNI or netavark networks. + // NetworkInterface is the libnetwork network interface used to setup netavark networks. NetworkInterface nettypes.ContainerNetwork `json:"-"` // ID mapping options to use if we're setting up our own user namespace diff --git a/vendor/github.com/containers/buildah/define/namespace.go b/vendor/github.com/containers/buildah/define/namespace.go index d0247fe9165..74592210e96 100644 --- a/vendor/github.com/containers/buildah/define/namespace.go +++ b/vendor/github.com/containers/buildah/define/namespace.go @@ -17,8 +17,8 @@ type NamespaceOption struct { // is not set. If Host is not set and Path is also empty, a new // namespace will be created for the process that we're starting. // If Name is specs.NetworkNamespace, if Path doesn't look like an - // absolute path, it is treated as a comma-separated list of CNI - // configuration names which will be selected from among all of the CNI + // absolute path, it is treated as a comma-separated list of network + // configuration names which will be selected from among all of the // network configurations which we find. Path string } diff --git a/vendor/github.com/containers/buildah/define/types.go b/vendor/github.com/containers/buildah/define/types.go index 9c7da4cd849..49b66d517e3 100644 --- a/vendor/github.com/containers/buildah/define/types.go +++ b/vendor/github.com/containers/buildah/define/types.go @@ -109,6 +109,21 @@ type Secret struct { SourceType string } +func (s Secret) ResolveValue() ([]byte, error) { + switch s.SourceType { + case "env": + return []byte(os.Getenv(s.Source)), nil + case "file": + rv, err := os.ReadFile(s.Source) + if err != nil { + return nil, fmt.Errorf("reading file for secret ID %s: %w", s.ID, err) + } + return rv, nil + default: + return nil, fmt.Errorf("invalid secret type: %s for secret ID: %s", s.SourceType, s.ID) + } +} + // BuildOutputOptions contains the the outcome of parsing the value of a build --output flag // Deprecated: This structure is now internal type BuildOutputOption struct { diff --git a/vendor/github.com/containers/buildah/image.go b/vendor/github.com/containers/buildah/image.go index 469db661079..659675727c9 100644 --- a/vendor/github.com/containers/buildah/image.go +++ b/vendor/github.com/containers/buildah/image.go @@ -14,6 +14,7 @@ import ( "path/filepath" "slices" "strings" + "syscall" "time" "github.com/containers/buildah/copier" @@ -59,6 +60,37 @@ const ( // create uniquely-named files, but we don't want to try to use their // contents until after they've been written to containerExcludesSubstring = ".tmp" + + // Windows-specific PAX record keys + keyFileAttr = "MSWINDOWS.fileattr" + keySDRaw = "MSWINDOWS.rawsd" + keyCreationTime = "LIBARCHIVE.creationtime" + // FILE_ATTRIBUTE_ values + fileAttributeDirectory = "16" + fileAttributeArchive = "32" + + // Windows Security Descriptors (base64-encoded) + // SDDL: O:BAG:SYD:(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)(A;;FA;;;BA)(A;OICIIO;GA;;;CO)(A;OICI;0x1200a9;;;BU)(A;CI;LC;;;BU)(A;CI;DC;;;BU) + // Owner: Built-in Administrators (BA) + // Group: Local System (SY) + // DACL: + // - Allow OBJECT_INHERIT+CONTAINER_INHERIT Full Access to Built-in Administrators (BA) + // - Allow OBJECT_INHERIT+CONTAINER_INHERIT Full Access to Local System (SY) + // - Allow Full Access to Built-in Administrators (BA) + // - Allow OBJECT_INHERIT+CONTAINER_INHERIT+INHERIT_ONLY Generic All to Creator Owner (CO) + // - Allow OBJECT_INHERIT+CONTAINER_INHERIT Read/Execute permissions to Built-in Users (BU) + // - Allow CONTAINER_INHERIT List Contents to Built-in Users (BU) + // - Allow CONTAINER_INHERIT Delete Child to Built-in Users (BU) + winSecurityDescriptorDirectory = "AQAEgBQAAAAkAAAAAAAAADAAAAABAgAAAAAABSAAAAAgAgAAAQEAAAAAAAUSAAAAAgCoAAcAAAAAAxgA/wEfAAECAAAAAAAFIAAAACACAAAAAxQA/wEfAAEBAAAAAAAFEgAAAAAAGAD/AR8AAQIAAAAAAAUgAAAAIAIAAAALFAAAAAAQAQEAAAAAAAMAAAAAAAMYAKkAEgABAgAAAAAABSAAAAAhAgAAAAIYAAQAAAABAgAAAAAABSAAAAAhAgAAAAIYAAIAAAABAgAAAAAABSAAAAAhAgAA" + + // SDDL: O:BAG:SYD:(A;;FA;;;BA)(A;;FA;;;SY)(A;;0x1200a9;;;BU) + // Owner: Built-in Administrators (BA) + // Group: Local System (SY) + // DACL: + // - Allow Full Access to Built-in Administrators (BA) + // - Allow Full Access to Local System (SY) + // - Allow Read/Execute permissions to Built-in Users (BU) + winSecurityDescriptorFile = "AQAEgBQAAAAkAAAAAAAAADAAAAABAgAAAAAABSAAAAAgAgAAAQEAAAAAAAUSAAAAAgBMAAMAAAAAABgA/wEfAAECAAAAAAAFIAAAACACAAAAABQA/wEfAAEBAAAAAAAFEgAAAAAAGACpABIAAQIAAAAAAAUgAAAAIQIAAA==" ) // ExtractRootfsOptions is consumed by ExtractRootfs() which allows users to @@ -112,6 +144,7 @@ type containerImageRef struct { unsetAnnotations []string setAnnotations []string createdAnnotation types.OptionalBool + os string } type blobLayerInfo struct { @@ -1084,6 +1117,7 @@ func (i *containerImageRef) NewImageSource(ctx context.Context, _ *types.SystemC diffBeingAltered := i.compression != archive.Uncompressed diffBeingAltered = diffBeingAltered || i.layerModTime != nil || i.layerLatestModTime != nil diffBeingAltered = diffBeingAltered || len(layerExclusions) != 0 + diffBeingAltered = diffBeingAltered || i.os == "windows" if diffBeingAltered { destHasher = digest.Canonical.Digester() multiWriter = io.MultiWriter(counter, destHasher.Hash()) @@ -1099,11 +1133,13 @@ func (i *containerImageRef) NewImageSource(ctx context.Context, _ *types.SystemC return nil, fmt.Errorf("compressing %s: %w", what, err) } writer := io.MultiWriter(writeCloser, srcHasher.Hash()) - // Use specified timestamps in the layer, if we're doing that for history // entries. nestedWriteCloser := ioutils.NewWriteCloserWrapper(writer, writeCloser.Close) - writeCloser = makeFilteredLayerWriteCloser(nestedWriteCloser, i.layerModTime, i.layerLatestModTime, layerExclusions) + writeCloser, err = makeFilteredLayerWriteCloser(nestedWriteCloser, i.layerModTime, i.layerLatestModTime, layerExclusions, i.os == "windows") + if err != nil { + return nil, fmt.Errorf("creating filter write closer %s: %w", what, err) + } writer = writeCloser // Okay, copy from the raw diff through the filter, compressor, and counter and // digesters. @@ -1373,9 +1409,9 @@ func (i *containerImageRef) makeExtraImageContentDiff(includeFooter bool, timest // no later than layerLatestModTime (if a value is provided for it). // This implies that if both values are provided, the archive's timestamps will // be set to the earlier of the two values. -func makeFilteredLayerWriteCloser(wc io.WriteCloser, layerModTime, layerLatestModTime *time.Time, exclusions []copier.ConditionalRemovePath) io.WriteCloser { - if layerModTime == nil && layerLatestModTime == nil && len(exclusions) == 0 { - return wc +func makeFilteredLayerWriteCloser(wc io.WriteCloser, layerModTime, layerLatestModTime *time.Time, exclusions []copier.ConditionalRemovePath, windows bool) (io.WriteCloser, error) { + if layerModTime == nil && layerLatestModTime == nil && len(exclusions) == 0 && !windows { + return wc, nil } exclusionsMap := make(map[string]copier.ConditionalRemovePath) for _, exclusionSpec := range exclusions { @@ -1385,19 +1421,22 @@ func makeFilteredLayerWriteCloser(wc io.WriteCloser, layerModTime, layerLatestMo } exclusionsMap[pathSpec] = exclusionSpec } + var initialized bool wc = newTarFilterer(wc, func(hdr *tar.Header) (skip, replaceContents bool, replacementContents io.Reader) { - // Changing a zeroed field to a non-zero field can affect the - // format that the library uses for writing the header, so only - // change fields that are already set to avoid changing the - // format (and as a result, changing the length) of the header - // that we write. modTime := hdr.ModTime - nameSpec := strings.Trim(path.Clean(hdr.Name), "/") - if conditions, ok := exclusionsMap[nameSpec]; ok { - if (conditions.ModTime == nil || conditions.ModTime.Equal(modTime)) && - (conditions.Owner == nil || (conditions.Owner.UID == hdr.Uid && conditions.Owner.GID == hdr.Gid)) && - (conditions.Mode == nil || (*conditions.Mode&os.ModePerm == os.FileMode(hdr.Mode)&os.ModePerm)) { - return true, false, nil + if layerModTime != nil || layerLatestModTime != nil || len(exclusions) != 0 { + // Changing a zeroed field to a non-zero field can affect the + // format that the library uses for writing the header, so only + // change fields that are already set to avoid changing the + // format (and as a result, changing the length) of the header + // that we write. + nameSpec := strings.Trim(path.Clean(hdr.Name), "/") + if conditions, ok := exclusionsMap[nameSpec]; ok { + if (conditions.ModTime == nil || conditions.ModTime.Equal(modTime)) && + (conditions.Owner == nil || (conditions.Owner.UID == hdr.Uid && conditions.Owner.GID == hdr.Gid)) && + (conditions.Mode == nil || (*conditions.Mode&os.ModePerm == os.FileMode(hdr.Mode)&os.ModePerm)) { + return true, false, nil + } } } if layerModTime != nil { @@ -1415,9 +1454,70 @@ func makeFilteredLayerWriteCloser(wc io.WriteCloser, layerModTime, layerLatestMo if !hdr.ChangeTime.IsZero() { hdr.ChangeTime = modTime } + if windows { + isDir := hdr.Typeflag == tar.TypeDir + if initialized { + hdr.Name = path.Join("Files", hdr.Name) + if isDir { + hdr.Name += "/" + } + if hdr.Linkname != "" { + hdr.Linkname = path.Join("Files", hdr.Linkname) + if isDir { + hdr.Linkname += "/" + } + } + } + // ensure all header fields are set in a way that is expected for Windows images + if hdr.PAXRecords == nil { + hdr.PAXRecords = map[string]string{} + } + hdr.Format = tar.FormatPAX + if isDir { + hdr.Mode |= syscall.S_IFDIR + hdr.PAXRecords[keyFileAttr] = fileAttributeDirectory + hdr.PAXRecords[keySDRaw] = winSecurityDescriptorDirectory + } else if hdr.Typeflag == tar.TypeReg { + hdr.Mode |= syscall.S_IFREG + hdr.PAXRecords[keyFileAttr] = fileAttributeArchive + hdr.PAXRecords[keySDRaw] = winSecurityDescriptorFile + } + if !hdr.ModTime.IsZero() { + hdr.PAXRecords[keyCreationTime] = fmt.Sprintf("%d.%09d", hdr.ModTime.Unix(), hdr.ModTime.Nanosecond()) + } + } return false, false, nil }) - return wc + if windows { + // prep the archive by writing the Files/ and Hives/ directories to the writer. + // This fulfills a requirement of Windows images + winTarWriter := tar.NewWriter(wc) + now := time.Now() + h := &tar.Header{ + Name: "Hives/", + Typeflag: tar.TypeDir, + ModTime: now, + Mode: 0o755, + } + if err := winTarWriter.WriteHeader(h); err != nil { + return nil, err + } + h = &tar.Header{ + Name: "Files/", + Typeflag: tar.TypeDir, + ModTime: now, + Mode: 0o755, + } + if err := winTarWriter.WriteHeader(h); err != nil { + return nil, err + } + // As we plan to continue to add to the archive, Flush() needs to be used, rather than Close(). + if err := winTarWriter.Flush(); err != nil { + return nil, err + } + } + initialized = true + return wc, nil } // makeLinkedLayerInfos calculates the size and digest information for a layer @@ -1475,7 +1575,10 @@ func (b *Builder) makeLinkedLayerInfos(layers []LinkedLayer, layerType string, l digester := digest.Canonical.Digester() sizeCountedFile := ioutils.NewWriteCounter(io.MultiWriter(digester.Hash(), f)) - wc := makeFilteredLayerWriteCloser(ioutils.NopWriteCloser(sizeCountedFile), layerModTime, layerLatestModTime, nil) + wc, err := makeFilteredLayerWriteCloser(ioutils.NopWriteCloser(sizeCountedFile), layerModTime, layerLatestModTime, nil, false) + if err != nil { + return err + } _, copyErr := io.Copy(wc, rc) wcErr := wc.Close() if err := rc.Close(); err != nil { @@ -1677,6 +1780,7 @@ func (b *Builder) makeContainerImageRef(options CommitOptions) (*containerImageR layerMountTargets: layerMountTargets, layerPullUps: layerPullUps, createdAnnotation: options.CreatedAnnotation, + os: b.OCIv1.OS, } if ref.created != nil { for i := range ref.preEmptyLayers { diff --git a/vendor/github.com/containers/buildah/imagebuildah/executor.go b/vendor/github.com/containers/buildah/imagebuildah/executor.go index faa52c4eaca..9022fc9895a 100644 --- a/vendor/github.com/containers/buildah/imagebuildah/executor.go +++ b/vendor/github.com/containers/buildah/imagebuildah/executor.go @@ -101,9 +101,7 @@ type executor struct { isolation define.Isolation namespaceOptions []define.NamespaceOption configureNetwork define.NetworkConfigurationPolicy - cniPluginPath string - cniConfigDir string - // NetworkInterface is the libnetwork network interface used to setup CNI or netavark networks. + // networkInterface is the libnetwork network interface used to setup netavark networks. networkInterface nettypes.ContainerNetwork idmappingOptions *define.IDMappingOptions commonBuildOptions *define.CommonBuildOptions @@ -302,8 +300,6 @@ func newExecutor(logger *logrus.Logger, logPrefix string, store storage.Store, o inheritAnnotations: options.InheritAnnotations, namespaceOptions: options.NamespaceOptions, configureNetwork: options.ConfigureNetwork, - cniPluginPath: options.CNIPluginPath, - cniConfigDir: options.CNIConfigDir, networkInterface: options.NetworkInterface, idmappingOptions: options.IDMappingOptions, commonBuildOptions: options.CommonBuildOpts, @@ -545,6 +541,7 @@ func (b *executor) getImageTypeAndHistoryAndDiffIDs(ctx context.Context, imageID } func (b *executor) buildStage(ctx context.Context, cleanupStages map[int]*stageExecutor, stages imagebuilder.Stages, stageIndex int) (imageID string, commitResults *buildah.CommitResults, onlyBaseImage bool, err error) { + var prependInstructions, appendInstructions []string stage := stages[stageIndex] ib := stage.Builder node := stage.Node @@ -569,36 +566,29 @@ func (b *executor) buildStage(ctx context.Context, cleanupStages map[int]*stageE output := "" if stageIndex == len(stages)-1 { output = b.output - // Check if any labels were passed in via the API, and add a final line - // to the Dockerfile that would provide the same result. + // Check if any labels were passed in via the API, and add an instruction at + // the end of the Dockerfile stage that would provide the intended result. // Reason: Docker adds label modification as a last step which can be // processed like regular steps, and if no modification is done to // layers, its easier to reuse cached layers. if len(b.labels) > 0 { - var labelLine string - labels := slices.Clone(b.labels) - for _, labelSpec := range labels { + labelLine := "LABEL" + for _, labelSpec := range b.labels { key, value, _ := strings.Cut(labelSpec, "=") // check only for an empty key since docker allows empty values if key != "" { labelLine += fmt.Sprintf(" %q=%q", key, value) } } - if len(labelLine) > 0 { - additionalNode, err := imagebuilder.ParseDockerfile(strings.NewReader("LABEL" + labelLine + "\n")) - if err != nil { - return "", nil, false, fmt.Errorf("while adding additional LABEL step: %w", err) - } - stage.Node.Children = append(stage.Node.Children, additionalNode.Children...) - } + appendInstructions = slices.Concat(appendInstructions, []string{labelLine}) } } - // If this stage is starting out with environment variables that were - // passed in via our API, we should include them in the history, since - // they affect RUN instructions in this stage. + // If we were given environment variables to set via the API, add them as instructions + // at the beginning of the stage so that they affect subsequent RUN instructions and + // factor into the image history. if len(b.envs) > 0 { - var envLine string + envLine := "ENV" for _, envSpec := range b.envs { key, value, hasValue := strings.Cut(envSpec, "=") if hasValue { @@ -607,14 +597,25 @@ func (b *executor) buildStage(ctx context.Context, cleanupStages map[int]*stageE return "", nil, false, fmt.Errorf("BUG: unresolved environment variable: %q", key) } } - if len(envLine) > 0 { - additionalNode, err := imagebuilder.ParseDockerfile(strings.NewReader("ENV" + envLine + "\n")) - if err != nil { - return "", nil, false, fmt.Errorf("while adding additional ENV step: %w", err) - } - // make this the first instruction in the stage after its FROM instruction - stage.Node.Children = append(additionalNode.Children, stage.Node.Children...) + prependInstructions = slices.Concat([]string{envLine}, prependInstructions) + } + + // If we're supposed to be appending or prepending instructions to this stage, add them now. + if len(prependInstructions) > 0 { + addLines := strings.Join(prependInstructions, "\n") + additionalNodes, err := imagebuilder.ParseDockerfile(strings.NewReader(addLines)) + if err != nil { + return "", nil, false, fmt.Errorf("while adding additional steps %q: %w", prependInstructions, err) + } + stage.Node.Children = append(additionalNodes.Children, stage.Node.Children...) + } + if len(appendInstructions) > 0 { + addLines := strings.Join(appendInstructions, "\n") + additionalNodes, err := imagebuilder.ParseDockerfile(strings.NewReader(addLines)) + if err != nil { + return "", nil, false, fmt.Errorf("while adding additional steps %q: %w", appendInstructions, err) } + stage.Node.Children = append(stage.Node.Children, additionalNodes.Children...) } b.stagesLock.Lock() diff --git a/vendor/github.com/containers/buildah/imagebuildah/stage_executor.go b/vendor/github.com/containers/buildah/imagebuildah/stage_executor.go index d7d94316d19..0afee4bd9c1 100644 --- a/vendor/github.com/containers/buildah/imagebuildah/stage_executor.go +++ b/vendor/github.com/containers/buildah/imagebuildah/stage_executor.go @@ -811,7 +811,7 @@ func (s *stageExecutor) Run(run imagebuilder.Run, config docker.Config) error { args = []string{full} } } - stageMountPoints, err := s.runStageMountPoints(run.Mounts) + stageMountPoints, err := s.runStageMountPoints(slices.Concat(run.Mounts, s.executor.transientRunMounts)) if err != nil { return err } @@ -876,7 +876,7 @@ func (s *stageExecutor) Run(run imagebuilder.Run, config docker.Config) error { } if run.Shell { - if len(config.Shell) > 0 && s.builder.Format == define.Dockerv2ImageManifest { + if len(config.Shell) > 0 { args = append(config.Shell, args...) } else { args = append([]string{"/bin/sh", "-c"}, args...) @@ -1084,8 +1084,6 @@ func (s *stageExecutor) prepare(ctx context.Context, from string, initializeIBCo Isolation: s.executor.isolation, NamespaceOptions: s.executor.namespaceOptions, ConfigureNetwork: s.executor.configureNetwork, - CNIPluginPath: s.executor.cniPluginPath, - CNIConfigDir: s.executor.cniConfigDir, NetworkInterface: s.executor.networkInterface, IDMappingOptions: s.executor.idmappingOptions, CommonBuildOpts: s.executor.commonBuildOptions, @@ -1412,6 +1410,7 @@ func (s *stageExecutor) execute(ctx context.Context, base string) (imgID string, logImageID(imgID) } + executedLayerStep := false for i, node := range children { logRusage() moreInstructions := i < len(children)-1 @@ -1521,6 +1520,9 @@ func (s *stageExecutor) execute(ctx context.Context, base string) (imgID string, // instruction. if !s.executor.layers { s.didExecute = true + if s.stepRequiresLayer(step) { + executedLayerStep = true + } err := ib.Run(step, s, noRunsRemaining) if err != nil { logrus.Debugf("Error building at step %+v: %v", *step, err) @@ -1555,7 +1557,7 @@ func (s *stageExecutor) execute(ctx context.Context, base string) (imgID string, if err != nil { return "", nil, false, fmt.Errorf("unable to get createdBy for the node: %w", err) } - imgID, commitResults, err = s.commit(ctx, createdBy, false, s.output, s.executor.squash, lastStage && lastInstruction) + imgID, commitResults, err = s.commit(ctx, createdBy, !executedLayerStep, s.output, s.executor.squash, lastStage && lastInstruction) if err != nil { return "", nil, false, fmt.Errorf("committing container for step %+v: %w", *step, err) } diff --git a/vendor/github.com/containers/buildah/import.go b/vendor/github.com/containers/buildah/import.go index d0b5655382f..961936dc228 100644 --- a/vendor/github.com/containers/buildah/import.go +++ b/vendor/github.com/containers/buildah/import.go @@ -87,7 +87,7 @@ func importBuilderDataFromImage(ctx context.Context, store storage.Store, system return nil, err } - netInt, err := getNetworkInterface(store, "", "") + netInt, err := getNetworkInterface(store) if err != nil { return nil, err } diff --git a/vendor/github.com/containers/buildah/install.md b/vendor/github.com/containers/buildah/install.md index df8a82560e7..e8713baf274 100644 --- a/vendor/github.com/containers/buildah/install.md +++ b/vendor/github.com/containers/buildah/install.md @@ -116,38 +116,6 @@ encounters a `RUN` instruction, so you'll also need to build and install a compa [runc](https://github.com/opencontainers/runc) for Buildah to call for those cases. If Buildah is installed via a package manager such as yum, dnf or apt-get, runc will be installed as part of that process. -### CNI Requirement - -When Buildah uses `runc` to run commands, it defaults to running those commands -in the host's network namespace. If the command is being run in a separate -user namespace, though, for example when ID mapping is used, then the command -will also be run in a separate network namespace. - -A newly-created network namespace starts with no network interfaces, so -commands which are run in that namespace are effectively disconnected from the -network unless additional setup is done. Buildah relies on the CNI -[library](https://github.com/containernetworking/cni) and -[plugins](https://github.com/containernetworking/plugins) to set up interfaces -and routing for network namespaces. - -If Buildah is installed via a package manager such as yum, dnf or apt-get, a -package containing CNI plugins may be available (in Fedora, the package is -named `containernetworking-cni`). If not, they will need to be installed, -for example using: -``` - git clone https://github.com/containernetworking/plugins - ( cd ./plugins; ./build_linux.sh ) - sudo mkdir -p /opt/cni/bin - sudo install -v ./plugins/bin/* /opt/cni/bin -``` - -The CNI library needs to be configured so that it will know which plugins to -call to set up namespaces. Usually, this configuration takes the form of one -or more configuration files in the `/etc/cni/net.d` directory. A set of example -configuration files is included in the -[`docs/cni-examples`](https://github.com/containers/buildah/tree/main/docs/cni-examples) -directory of this source tree. - ## Package Installation Buildah is available on several software repositories and can be installed via a package manager such diff --git a/vendor/github.com/containers/buildah/internal/mkcw/embed/entrypoint_amd64.gz b/vendor/github.com/containers/buildah/internal/mkcw/embed/entrypoint_amd64.gz index c2399f9e904..5c5f81c18e4 100644 Binary files a/vendor/github.com/containers/buildah/internal/mkcw/embed/entrypoint_amd64.gz and b/vendor/github.com/containers/buildah/internal/mkcw/embed/entrypoint_amd64.gz differ diff --git a/vendor/github.com/containers/buildah/new.go b/vendor/github.com/containers/buildah/new.go index 1f8bb87b8a1..dbf5a9d3c2f 100644 --- a/vendor/github.com/containers/buildah/new.go +++ b/vendor/github.com/containers/buildah/new.go @@ -129,10 +129,7 @@ func newBuilder(ctx context.Context, store storage.Store, options BuilderOptions if options.NetworkInterface == nil { // create the network interface - // Note: It is important to do this before we pull any images/create containers. - // The default backend detection logic needs an empty store to correctly detect - // that we can use netavark, if the store was not empty it will use CNI to not break existing installs. - options.NetworkInterface, err = getNetworkInterface(store, options.CNIConfigDir, options.CNIPluginPath) + options.NetworkInterface, err = getNetworkInterface(store) if err != nil { return nil, err } @@ -307,8 +304,6 @@ func newBuilder(ctx context.Context, store storage.Store, options BuilderOptions Isolation: options.Isolation, NamespaceOptions: namespaceOptions, ConfigureNetwork: options.ConfigureNetwork, - CNIPluginPath: options.CNIPluginPath, - CNIConfigDir: options.CNIConfigDir, IDMappingOptions: define.IDMappingOptions{ HostUIDMapping: len(uidmap) == 0, HostGIDMapping: len(uidmap) == 0, diff --git a/vendor/github.com/containers/buildah/pkg/cli/build.go b/vendor/github.com/containers/buildah/pkg/cli/build.go index e2df822848f..8db26a6c195 100644 --- a/vendor/github.com/containers/buildah/pkg/cli/build.go +++ b/vendor/github.com/containers/buildah/pkg/cli/build.go @@ -331,7 +331,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) ( } } - if c.Flag("network").Changed && c.Flag("isolation").Changed { + if c.Flag("network").Changed { if isolation == define.IsolationChroot { if ns := namespaceOptions.Find(string(specs.NetworkNamespace)); ns != nil { if !ns.Host { @@ -390,8 +390,6 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) ( CacheTo: cacheTo, CacheTTL: cacheTTL, CDIConfigDir: iopts.CDIConfigDir, - CNIConfigDir: iopts.CNIConfigDir, - CNIPluginPath: iopts.CNIPlugInPath, CompatVolumes: compatVolumes, ConfidentialWorkload: confidentialWorkloadOptions, CPPFlags: iopts.CPPFlags, diff --git a/vendor/github.com/containers/buildah/pkg/cli/common.go b/vendor/github.com/containers/buildah/pkg/cli/common.go index fe41c0d0977..7eee472b073 100644 --- a/vendor/github.com/containers/buildah/pkg/cli/common.go +++ b/vendor/github.com/containers/buildah/pkg/cli/common.go @@ -42,10 +42,12 @@ type UserNSResults struct { // NameSpaceResults represents the results for Namespace flags type NameSpaceResults struct { - Cgroup string - IPC string - Network string - CNIConfigDir string + Cgroup string + IPC string + Network string + // Deprecated: CNIConfigDir is no longer used and is expected to be empty. + CNIConfigDir string + // Deprecated: CNIPlugInPath is no longer used and is expected to be empty. CNIPlugInPath string PID string UTS string @@ -195,10 +197,6 @@ func GetNameSpaceFlags(flags *NameSpaceResults) pflag.FlagSet { fs.StringVar(&flags.Cgroup, "cgroupns", "", "'private', or 'host'") fs.StringVar(&flags.IPC, string(specs.IPCNamespace), "", "'private', `path` of IPC namespace to join, or 'host'") fs.StringVar(&flags.Network, string(specs.NetworkNamespace), "", "'private', 'none', 'ns:path' of network namespace to join, or 'host'") - fs.StringVar(&flags.CNIConfigDir, "cni-config-dir", "", "`directory` of CNI configuration files") - _ = fs.MarkHidden("cni-config-dir") - fs.StringVar(&flags.CNIPlugInPath, "cni-plugin-path", "", "`path` of CNI network plugins") - _ = fs.MarkHidden("cni-plugin-path") fs.StringVar(&flags.PID, string(specs.PIDNamespace), "", "private, `path` of PID namespace to join, or 'host'") fs.StringVar(&flags.UTS, string(specs.UTSNamespace), "", "private, :`path` of UTS namespace to join, or 'host'") return fs diff --git a/vendor/github.com/containers/buildah/pkg/overlay/overlay.go b/vendor/github.com/containers/buildah/pkg/overlay/overlay.go index 4353c7bbaf2..0eafdbbac42 100644 --- a/vendor/github.com/containers/buildah/pkg/overlay/overlay.go +++ b/vendor/github.com/containers/buildah/pkg/overlay/overlay.go @@ -61,7 +61,7 @@ type Options struct { // beneath it, and then returns the path of the new directory. func TempDir(containerDir string, rootUID, rootGID int) (string, error) { contentDir := filepath.Join(containerDir, "overlay") - if err := idtools.MkdirAllAs(contentDir, 0o700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAndChown(contentDir, 0o700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { return "", fmt.Errorf("failed to create the overlay %s directory: %w", contentDir, err) } @@ -76,7 +76,7 @@ func TempDir(containerDir string, rootUID, rootGID int) (string, error) { // GenerateStructure generates an overlay directory structure for container content func GenerateStructure(containerDir, containerID, name string, rootUID, rootGID int) (string, error) { contentDir := filepath.Join(containerDir, "overlay-containers", containerID, name) - if err := idtools.MkdirAllAs(contentDir, 0o700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAndChown(contentDir, 0o700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { return "", fmt.Errorf("failed to create the overlay %s directory: %w", contentDir, err) } @@ -87,14 +87,14 @@ func GenerateStructure(containerDir, containerID, name string, rootUID, rootGID func generateOverlayStructure(containerDir string, rootUID, rootGID int) error { upperDir := filepath.Join(containerDir, "upper") workDir := filepath.Join(containerDir, "work") - if err := idtools.MkdirAllAs(upperDir, 0o700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAndChown(upperDir, 0o700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { return fmt.Errorf("creating overlay upper directory %s: %w", upperDir, err) } - if err := idtools.MkdirAllAs(workDir, 0o700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAndChown(workDir, 0o700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { return fmt.Errorf("creating overlay work directory %s: %w", workDir, err) } mergeDir := filepath.Join(containerDir, "merge") - if err := idtools.MkdirAllAs(mergeDir, 0o700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAndChown(mergeDir, 0o700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { return fmt.Errorf("creating overlay merge directory %s: %w", mergeDir, err) } return nil @@ -216,7 +216,7 @@ func recreate(contentDir string) error { return err } - if err := idtools.MkdirAllAs(contentDir, os.FileMode(st.Mode()), int(st.UID()), int(st.GID())); err != nil { + if err := idtools.MkdirAllAndChown(contentDir, os.FileMode(st.Mode()), idtools.IDPair{UID: int(st.UID()), GID: int(st.GID())}); err != nil { return fmt.Errorf("failed to create overlay directory: %w", err) } return nil diff --git a/vendor/github.com/containers/buildah/pull.go b/vendor/github.com/containers/buildah/pull.go index 8fd715794b0..89a4defd543 100644 --- a/vendor/github.com/containers/buildah/pull.go +++ b/vendor/github.com/containers/buildah/pull.go @@ -87,14 +87,6 @@ func Pull(_ context.Context, imageName string, options PullOptions) (imageID str return "", err } - // Note: It is important to do this before we pull any images/create containers. - // The default backend detection logic needs an empty store to correctly detect - // that we can use netavark, if the store was not empty it will use CNI to not break existing installs. - _, err = getNetworkInterface(options.Store, "", "") - if err != nil { - return "", err - } - runtime, err := libimage.RuntimeFromStore(options.Store, &libimage.RuntimeOptions{SystemContext: options.SystemContext}) if err != nil { return "", err diff --git a/vendor/github.com/containers/buildah/run.go b/vendor/github.com/containers/buildah/run.go index 4f20f9c1b80..0efa4d8b03e 100644 --- a/vendor/github.com/containers/buildah/run.go +++ b/vendor/github.com/containers/buildah/run.go @@ -129,11 +129,11 @@ type RunOptions struct { // namespace), effectively deciding whether or not the process has a // usable network. ConfigureNetwork define.NetworkConfigurationPolicy - // CNIPluginPath is the location of CNI plugin helpers, if they should be - // run from a location other than the default location. + // Deprecated: CNIPluginPath was the location of CNI plugin helpers. + // It is no longer used and is expected to be empty. CNIPluginPath string - // CNIConfigDir is the location of CNI configuration files, if the files in - // the default configuration directory shouldn't be used. + // Deprecated: CNIConfigDir was the location of CNI configuration files. + // It is no longer used and is expected to be empty. CNIConfigDir string // Terminal provides a way to specify whether or not the command should // be run with a pseudoterminal. By default (DefaultTerminal), a @@ -199,12 +199,12 @@ type runMountArtifacts struct { MountedImages []string // Agents are the ssh agents started, which should have their Shutdown() methods called Agents []*sshagent.AgentServer - // SSHAuthSock is the path to the ssh auth sock inside the container - SSHAuthSock string // Lock files, which should have their Unlock() methods called TargetLocks []*lockfile.LockFile // Intermediate mount points, which should be Unmount()ed and Removed()d IntermediateMounts []string + // Environment variables that should be set for RUN that may contain secrets, each is name=value form + EnvVars []string } // RunMountInfo are the available run mounts for this run diff --git a/vendor/github.com/containers/buildah/run_common.go b/vendor/github.com/containers/buildah/run_common.go index d9f1b35939c..640e375c417 100644 --- a/vendor/github.com/containers/buildah/run_common.go +++ b/vendor/github.com/containers/buildah/run_common.go @@ -331,22 +331,13 @@ func (b *Builder) configureEnvironment(g *generate.Generator, options RunOptions } // getNetworkInterface creates the network interface -func getNetworkInterface(store storage.Store, cniConfDir, cniPluginPath string) (netTypes.ContainerNetwork, error) { +func getNetworkInterface(store storage.Store) (netTypes.ContainerNetwork, error) { conf, err := config.Default() if err != nil { return nil, err } - // copy the config to not modify the default by accident - newconf := *conf - if len(cniConfDir) > 0 { - newconf.Network.NetworkConfigDir = cniConfDir - } - if len(cniPluginPath) > 0 { - plugins := strings.Split(cniPluginPath, string(os.PathListSeparator)) - newconf.Network.CNIPluginDirs.Set(plugins) - } - _, netInt, err := network.NetworkBackend(store, &newconf, false) + _, netInt, err := network.NetworkBackend(store, conf, false) if err != nil { return nil, err } @@ -478,15 +469,7 @@ func runUsingRuntime(options RunOptions, configureNetwork bool, moreCreateArgs [ logrus.Debugf("config = %v", string(specbytes)) - // Decide which runtime to use. runtime := options.Runtime - if runtime == "" { - runtime = util.Runtime() - } - localRuntime := util.FindLocalRuntime(runtime) - if localRuntime != "" { - runtime = localRuntime - } // Default to just passing down our stdio. getCreateStdio := func() (io.ReadCloser, io.WriteCloser, io.WriteCloser) { @@ -1165,6 +1148,17 @@ func runUsingRuntimeMain() { func (b *Builder) runUsingRuntimeSubproc(isolation define.Isolation, options RunOptions, configureNetwork bool, networkString string, moreCreateArgs []string, spec *specs.Spec, rootPath, bundlePath, containerName, buildContainerName, hostsFile, resolvFile string, ) (err error) { + // Decide which runtime to use in case it was empty. + ociRuntime := options.Runtime + if ociRuntime == "" { + ociRuntime = util.Runtime() + } + localRuntime := util.FindLocalRuntime(ociRuntime) + if localRuntime != "" { + ociRuntime = localRuntime + } + options.Runtime = ociRuntime + // Lock the caller to a single OS-level thread. runtime.LockOSThread() defer runtime.UnlockOSThread() @@ -1433,6 +1427,9 @@ func (b *Builder) setupMounts(mountPoint string, spec *specs.Spec, bundlePath st mounts = append(mounts, mount) } + // Some mounts require env vars to be set, do these here + spec.Process.Env = append(spec.Process.Env, mountArtifacts.EnvVars...) + // Set the list in the spec. spec.Mounts = mounts succeeded = true @@ -1522,7 +1519,7 @@ func (b *Builder) runSetupRunMounts(bundlePath string, mounts []string, sources intermediateMounts := make([]string, 0, len(mounts)) finalMounts := make([]specs.Mount, 0, len(mounts)) agents := make([]*sshagent.AgentServer, 0, len(mounts)) - defaultSSHSock := "" + var envVars []string targetLocks := []*lockfile.LockFile{} var overlayDirs []string succeeded := false @@ -1561,11 +1558,7 @@ func (b *Builder) runSetupRunMounts(bundlePath string, mounts []string, sources } }() for _, mount := range mounts { - var mountSpec *specs.Mount - var err error - var envFile, image, bundleMountsDir, overlayDir, intermediateMount string - var agent *sshagent.AgentServer - var tl *lockfile.LockFile + var bundleMountsDir string tokens := strings.Split(mount, ",") @@ -1583,35 +1576,39 @@ func (b *Builder) runSetupRunMounts(bundlePath string, mounts []string, sources } switch mountType { case "secret": - mountSpec, envFile, err = b.getSecretMount(tokens, sources.Secrets, idMaps, sources.WorkDir) + mountOrEnvSpec, err := b.getSecretMount(tokens, sources.Secrets, idMaps, sources.WorkDir) if err != nil { return nil, nil, err } - if mountSpec != nil { - finalMounts = append(finalMounts, *mountSpec) - if envFile != "" { - tmpFiles = append(tmpFiles, envFile) - } + if mountOrEnvSpec.Mount != nil { + finalMounts = append(finalMounts, *mountOrEnvSpec.Mount) + } + if mountOrEnvSpec.EnvFile != "" { + tmpFiles = append(tmpFiles, mountOrEnvSpec.EnvFile) + } + if mountOrEnvSpec.EnvVariable != "" { + envVars = append(envVars, mountOrEnvSpec.EnvVariable) } case "ssh": - mountSpec, agent, err = b.getSSHMount(tokens, len(agents), sources.SSHSources, idMaps) + mountSpec, agent, err := b.getSSHMount(tokens, len(agents), sources.SSHSources, idMaps) if err != nil { return nil, nil, err } if mountSpec != nil { finalMounts = append(finalMounts, *mountSpec) if len(agents) == 0 { - defaultSSHSock = mountSpec.Destination + envVars = append(envVars, "SSH_AUTH_SOCK="+mountSpec.Destination) } agents = append(agents, agent) } case define.TypeBind: if bundleMountsDir == "" { + var err error if bundleMountsDir, err = os.MkdirTemp(bundlePath, "mounts"); err != nil { return nil, nil, err } } - mountSpec, image, intermediateMount, overlayDir, err = b.getBindMount(tokens, sources.SystemContext, sources.ContextDir, sources.StageMountPoints, idMaps, sources.WorkDir, bundleMountsDir) + mountSpec, image, intermediateMount, overlayDir, err := b.getBindMount(tokens, sources.SystemContext, sources.ContextDir, sources.StageMountPoints, idMaps, sources.WorkDir, bundleMountsDir) if err != nil { return nil, nil, err } @@ -1626,18 +1623,19 @@ func (b *Builder) runSetupRunMounts(bundlePath string, mounts []string, sources } finalMounts = append(finalMounts, *mountSpec) case "tmpfs": - mountSpec, err = b.getTmpfsMount(tokens, idMaps, sources.WorkDir) + mountSpec, err := b.getTmpfsMount(tokens, idMaps, sources.WorkDir) if err != nil { return nil, nil, err } finalMounts = append(finalMounts, *mountSpec) case "cache": if bundleMountsDir == "" { + var err error if bundleMountsDir, err = os.MkdirTemp(bundlePath, "mounts"); err != nil { return nil, nil, err } } - mountSpec, image, intermediateMount, overlayDir, tl, err = b.getCacheMount(tokens, sources.SystemContext, sources.StageMountPoints, idMaps, sources.WorkDir, bundleMountsDir) + mountSpec, image, intermediateMount, overlayDir, tl, err := b.getCacheMount(tokens, sources.SystemContext, sources.StageMountPoints, idMaps, sources.WorkDir, bundleMountsDir) if err != nil { return nil, nil, err } @@ -1663,9 +1661,9 @@ func (b *Builder) runSetupRunMounts(bundlePath string, mounts []string, sources RunOverlayDirs: overlayDirs, Agents: agents, MountedImages: mountImages, - SSHAuthSock: defaultSSHSock, TargetLocks: targetLocks, IntermediateMounts: intermediateMounts, + EnvVars: envVars, } return finalMounts, artifacts, nil } @@ -1731,16 +1729,27 @@ func (b *Builder) getTmpfsMount(tokens []string, idMaps IDMaps, workDir string) return &volumes[0], nil } -func (b *Builder) getSecretMount(tokens []string, secrets map[string]define.Secret, idMaps IDMaps, workdir string) (_ *specs.Mount, _ string, retErr error) { - errInvalidSyntax := errors.New("secret should have syntax id=id[,target=path,required=bool,mode=uint,uid=uint,gid=uint") +type secretMountOrEnv struct { + // set if mount created + Mount *specs.Mount + + // set if caller mount created from temp created env file + EnvFile string + + // set if caller should add to env variable list + EnvVariable string +} + +func (b *Builder) getSecretMount(tokens []string, secrets map[string]define.Secret, idMaps IDMaps, workdir string) (_ secretMountOrEnv, retErr error) { + errInvalidSyntax := errors.New("secret should have syntax id=id[,target=path,required=bool,mode=uint,uid=uint,gid=uint,env=dstVarName") if len(tokens) == 0 { - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } - var err error - var id, target string + var id, target, env string var required bool var uid, gid uint32 var mode uint32 = 0o400 + var rv secretMountOrEnv for _, val := range tokens { kv := strings.SplitN(val, "=", 2) switch kv[0] { @@ -1757,110 +1766,133 @@ func (b *Builder) getSecretMount(tokens []string, secrets map[string]define.Secr case "required": required = true if len(kv) > 1 { + var err error required, err = strconv.ParseBool(kv[1]) if err != nil { - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } } case "mode": mode64, err := strconv.ParseUint(kv[1], 8, 32) if err != nil { - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } mode = uint32(mode64) case "uid": uid64, err := strconv.ParseUint(kv[1], 10, 32) if err != nil { - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } uid = uint32(uid64) case "gid": gid64, err := strconv.ParseUint(kv[1], 10, 32) if err != nil { - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } gid = uint32(gid64) + case "env": + if kv[1] == "" { + return secretMountOrEnv{}, errInvalidSyntax + } + env = kv[1] default: - return nil, "", errInvalidSyntax + return secretMountOrEnv{}, errInvalidSyntax } } - if id == "" { - return nil, "", errInvalidSyntax - } - // Default location for secrets is /run/secrets/id + // apply defaults, matching documented behaviour if target == "" { - target = "/run/secrets/" + id + if env == "" { + target = "/run/secrets/" + id + } + } else { + if id == "" { + id = filepath.Base(target) + } } + if id == "" { + return secretMountOrEnv{}, errInvalidSyntax + } + + // first fetch the secret data secr, ok := secrets[id] if !ok { if required { - return nil, "", fmt.Errorf("secret required but no secret with id %q found", id) + return secretMountOrEnv{}, fmt.Errorf("secret required but no secret with id %q found", id) } - return nil, "", nil + return rv, nil } - var data []byte - var envFile string + data, err := secr.ResolveValue() + if err != nil { + return secretMountOrEnv{}, err + } + + // if env is set, then we set that + if env != "" { + rv.EnvVariable = env + "=" + string(data) + } + + // if no target needs to be mounted, then return now, we're done + if target == "" { + return rv, nil + } + var ctrFileOnHost string switch secr.SourceType { case "env": - data = []byte(os.Getenv(secr.Source)) tmpFile, err := os.CreateTemp(tmpdir.GetTempDir(), "buildah*") if err != nil { - return nil, "", err + return secretMountOrEnv{}, err } + tmpFile.Close() defer func() { if retErr != nil { os.Remove(tmpFile.Name()) } }() - envFile = tmpFile.Name() + rv.EnvFile = tmpFile.Name() ctrFileOnHost = tmpFile.Name() case "file": containerWorkingDir, err := b.store.ContainerDirectory(b.ContainerID) if err != nil { - return nil, "", err - } - data, err = os.ReadFile(secr.Source) - if err != nil { - return nil, "", err + return secretMountOrEnv{}, err } ctrFileOnHost = filepath.Join(containerWorkingDir, "secrets", digest.FromString(id).Encoded()[:16]) default: - return nil, "", errors.New("invalid source secret type") + return secretMountOrEnv{}, errors.New("invalid source secret type") } // Copy secrets to container working dir (or tmp dir if it's an env), since we need to chmod, // chown and relabel it for the container user and we don't want to mess with the original file if err := os.MkdirAll(filepath.Dir(ctrFileOnHost), 0o755); err != nil { - return nil, "", err + return secretMountOrEnv{}, err } if err := os.WriteFile(ctrFileOnHost, data, 0o644); err != nil { - return nil, "", err + return secretMountOrEnv{}, err } if err := relabel(ctrFileOnHost, b.MountLabel, false); err != nil { - return nil, "", err + return secretMountOrEnv{}, err } hostUID, hostGID, err := util.GetHostIDs(idMaps.uidmap, idMaps.gidmap, uid, gid) if err != nil { - return nil, "", err + return secretMountOrEnv{}, err } if err := os.Lchown(ctrFileOnHost, int(hostUID), int(hostGID)); err != nil { - return nil, "", err + return secretMountOrEnv{}, err } if err := os.Chmod(ctrFileOnHost, os.FileMode(mode)); err != nil { - return nil, "", err + return secretMountOrEnv{}, err } - newMount := specs.Mount{ + rv.Mount = &specs.Mount{ Destination: target, Type: define.TypeBind, Source: ctrFileOnHost, Options: append(define.BindOptions, "rprivate", "ro"), } - return &newMount, envFile, nil + return rv, nil } // getSSHMount parses the --mount type=ssh flag in the Containerfile, checks if there's an ssh source provided, and creates and starts an ssh-agent to be forwarded into the container diff --git a/vendor/github.com/containers/buildah/run_freebsd.go b/vendor/github.com/containers/buildah/run_freebsd.go index 74771a2664f..6d0d57223d3 100644 --- a/vendor/github.com/containers/buildah/run_freebsd.go +++ b/vendor/github.com/containers/buildah/run_freebsd.go @@ -276,10 +276,6 @@ func (b *Builder) Run(command []string, options RunOptions) error { if err != nil { return fmt.Errorf("resolving mountpoints for container %q: %w", b.ContainerID, err) } - if runArtifacts.SSHAuthSock != "" { - sshenv := "SSH_AUTH_SOCK=" + runArtifacts.SSHAuthSock - spec.Process.Env = append(spec.Process.Env, sshenv) - } // following run was called from `buildah run` // and some images were mounted for this run diff --git a/vendor/github.com/containers/buildah/run_linux.go b/vendor/github.com/containers/buildah/run_linux.go index d3b12eede8e..c3dbaf7972a 100644 --- a/vendor/github.com/containers/buildah/run_linux.go +++ b/vendor/github.com/containers/buildah/run_linux.go @@ -513,10 +513,6 @@ rootless=%d if err != nil { return fmt.Errorf("resolving mountpoints for container %q: %w", b.ContainerID, err) } - if runArtifacts.SSHAuthSock != "" { - sshenv := "SSH_AUTH_SOCK=" + runArtifacts.SSHAuthSock - spec.Process.Env = append(spec.Process.Env, sshenv) - } // Create any mount points that we need that aren't already present in // the rootfs. diff --git a/vendor/github.com/containers/buildah/run_unix.go b/vendor/github.com/containers/buildah/run_unix.go index 61e18910c64..f2129aab179 100644 --- a/vendor/github.com/containers/buildah/run_unix.go +++ b/vendor/github.com/containers/buildah/run_unix.go @@ -38,6 +38,6 @@ func DefaultNamespaceOptions() (NamespaceOptions, error) { } // getNetworkInterface creates the network interface -func getNetworkInterface(store storage.Store, cniConfDir, cniPluginPath string) (nettypes.ContainerNetwork, error) { +func getNetworkInterface(store storage.Store) (nettypes.ContainerNetwork, error) { return nil, nil } diff --git a/vendor/github.com/containers/buildah/run_unsupported.go b/vendor/github.com/containers/buildah/run_unsupported.go index 5530a465f46..59e463f9288 100644 --- a/vendor/github.com/containers/buildah/run_unsupported.go +++ b/vendor/github.com/containers/buildah/run_unsupported.go @@ -24,6 +24,6 @@ func DefaultNamespaceOptions() (NamespaceOptions, error) { } // getNetworkInterface creates the network interface -func getNetworkInterface(store storage.Store, cniConfDir, cniPluginPath string) (nettypes.ContainerNetwork, error) { +func getNetworkInterface(store storage.Store) (nettypes.ContainerNetwork, error) { return nil, errors.New("function not supported on non-linux systems") } diff --git a/vendor/github.com/containers/buildah/util.go b/vendor/github.com/containers/buildah/util.go index 10cd6f597e0..5bb77f386b3 100644 --- a/vendor/github.com/containers/buildah/util.go +++ b/vendor/github.com/containers/buildah/util.go @@ -94,17 +94,17 @@ func convertRuntimeIDMaps(UIDMap, GIDMap []rspec.LinuxIDMapping) ([]idtools.IDMa func isRegistryBlocked(registry string, sc *types.SystemContext) (bool, error) { reginfo, err := sysregistriesv2.FindRegistry(sc, registry) if err != nil { - return false, fmt.Errorf("unable to parse the registries configuration (%s): %w", sysregistriesv2.ConfigPath(sc), err) + return false, fmt.Errorf("unable to parse the registries configuration (%s): %w", sysregistriesv2.ConfigurationSourceDescription(sc), err) } if reginfo != nil { if reginfo.Blocked { - logrus.Debugf("registry %q is marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigPath(sc)) + logrus.Debugf("registry %q is marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigurationSourceDescription(sc)) } else { - logrus.Debugf("registry %q is not marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigPath(sc)) + logrus.Debugf("registry %q is not marked as blocked in registries configuration %q", registry, sysregistriesv2.ConfigurationSourceDescription(sc)) } return reginfo.Blocked, nil } - logrus.Debugf("registry %q is not listed in registries configuration %q, assuming it's not blocked", registry, sysregistriesv2.ConfigPath(sc)) + logrus.Debugf("registry %q is not listed in registries configuration %q, assuming it's not blocked", registry, sysregistriesv2.ConfigurationSourceDescription(sc)) return false, nil } diff --git a/vendor/github.com/coreos/go-oidc/v3/oidc/oidc.go b/vendor/github.com/coreos/go-oidc/v3/oidc/oidc.go index f6a7ea8a580..2659518cc48 100644 --- a/vendor/github.com/coreos/go-oidc/v3/oidc/oidc.go +++ b/vendor/github.com/coreos/go-oidc/v3/oidc/oidc.go @@ -162,7 +162,7 @@ var supportedAlgorithms = map[string]bool{ // parsing. // // // Directly fetch the metadata document. -// resp, err := http.Get("https://login.example.com/custom-metadata-path") +// resp, err := http.Get("https://login.example.com/custom-metadata-path") // if err != nil { // // ... // } @@ -267,7 +267,7 @@ func NewProvider(ctx context.Context, issuer string) (*Provider, error) { issuerURL = issuer } if p.Issuer != issuerURL && !skipIssuerValidation { - return nil, fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", issuer, p.Issuer) + return nil, fmt.Errorf("oidc: issuer URL provided to client (%q) did not match the issuer URL returned by provider (%q)", issuer, p.Issuer) } var algs []string for _, a := range p.Algorithms { diff --git a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go deleted file mode 100644 index 931ae10ab1e..00000000000 --- a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go +++ /dev/null @@ -1,23 +0,0 @@ -package blkiodev - -import "fmt" - -// WeightDevice is a structure that holds device:weight pair -type WeightDevice struct { - Path string - Weight uint16 -} - -func (w *WeightDevice) String() string { - return fmt.Sprintf("%s:%d", w.Path, w.Weight) -} - -// ThrottleDevice is a structure that holds device:rate_per_second pair -type ThrottleDevice struct { - Path string - Rate uint64 -} - -func (t *ThrottleDevice) String() string { - return fmt.Sprintf("%s:%d", t.Path, t.Rate) -} diff --git a/vendor/github.com/docker/docker/api/types/common/id_response.go b/vendor/github.com/docker/docker/api/types/common/id_response.go deleted file mode 100644 index 22e8c60a48d..00000000000 --- a/vendor/github.com/docker/docker/api/types/common/id_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package common - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// IDResponse Response to an API call that returns just an Id -// swagger:model IDResponse -type IDResponse struct { - - // The id of the newly created object. - // Required: true - ID string `json:"Id"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/change_type.go b/vendor/github.com/docker/docker/api/types/container/change_type.go deleted file mode 100644 index fe8d6d36966..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_type.go +++ /dev/null @@ -1,15 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ChangeType Kind of change -// -// Can be one of: -// -// - `0`: Modified ("C") -// - `1`: Added ("A") -// - `2`: Deleted ("D") -// -// swagger:model ChangeType -type ChangeType uint8 diff --git a/vendor/github.com/docker/docker/api/types/container/change_types.go b/vendor/github.com/docker/docker/api/types/container/change_types.go deleted file mode 100644 index 3a3a83866ec..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/change_types.go +++ /dev/null @@ -1,23 +0,0 @@ -package container - -const ( - // ChangeModify represents the modify operation. - ChangeModify ChangeType = 0 - // ChangeAdd represents the add operation. - ChangeAdd ChangeType = 1 - // ChangeDelete represents the delete operation. - ChangeDelete ChangeType = 2 -) - -func (ct ChangeType) String() string { - switch ct { - case ChangeModify: - return "C" - case ChangeAdd: - return "A" - case ChangeDelete: - return "D" - default: - return "" - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/commit.go b/vendor/github.com/docker/docker/api/types/container/commit.go deleted file mode 100644 index 6fd1b0ead13..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/commit.go +++ /dev/null @@ -1,7 +0,0 @@ -package container - -import "github.com/docker/docker/api/types/common" - -// CommitResponse response for the commit API call, containing the ID of the -// image that was produced. -type CommitResponse = common.IDResponse diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go deleted file mode 100644 index 0555416540b..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ /dev/null @@ -1,73 +0,0 @@ -package container - -import ( - "time" - - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - dockerspec "github.com/moby/docker-image-spec/specs-go/v1" -) - -// MinimumDuration puts a minimum on user configured duration. -// This is to prevent API error on time unit. For example, API may -// set 3 as healthcheck interval with intention of 3 seconds, but -// Docker interprets it as 3 nanoseconds. -const MinimumDuration = 1 * time.Millisecond - -// StopOptions holds the options to stop or restart a container. -type StopOptions struct { - // Signal (optional) is the signal to send to the container to (gracefully) - // stop it before forcibly terminating the container with SIGKILL after the - // timeout expires. If not value is set, the default (SIGTERM) is used. - Signal string `json:",omitempty"` - - // Timeout (optional) is the timeout (in seconds) to wait for the container - // to stop gracefully before forcibly terminating it with SIGKILL. - // - // - Use nil to use the default timeout (10 seconds). - // - Use '-1' to wait indefinitely. - // - Use '0' to not wait for the container to exit gracefully, and - // immediately proceeds to forcibly terminating the container. - // - Other positive values are used as timeout (in seconds). - Timeout *int `json:",omitempty"` -} - -// HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig = dockerspec.HealthcheckConfig - -// Config contains the configuration data about a container. -// It should hold only portable information about the container. -// Here, "portable" means "independent from the host we are running on". -// Non-portable information *should* appear in HostConfig. -// All fields added to this struct must be marked `omitempty` to keep getting -// predictable hashes from the old `v1Compatibility` configuration. -type Config struct { - Hostname string // Hostname - Domainname string // Domainname - User string // User that will run the command(s) inside the container, also support user:group - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStdout bool // Attach the standard output - AttachStderr bool // Attach the standard error - ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports - Tty bool // Attach standard streams to a tty, including stdin if it is not closed. - OpenStdin bool // Open stdin - StdinOnce bool // If true, close stdin after the 1 attached client disconnects. - Env []string // List of environment variable to set in the container - Cmd strslice.StrSlice // Command to run when starting the container - Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy - ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (meaning treat as a command line) (Windows specific). - Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) - Volumes map[string]struct{} // List of volumes (mounts) used for the container - WorkingDir string // Current directory (PWD) in the command will be launched - Entrypoint strslice.StrSlice // Entrypoint to run when starting the container - NetworkDisabled bool `json:",omitempty"` // Is network disabled - // Mac Address of the container. - // - // Deprecated: this field is deprecated since API v1.44. Use EndpointSettings.MacAddress instead. - MacAddress string `json:",omitempty"` - OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile - Labels map[string]string // List of labels set to this container - StopSignal string `json:",omitempty"` // Signal to stop a container - StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container - Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT -} diff --git a/vendor/github.com/docker/docker/api/types/container/container.go b/vendor/github.com/docker/docker/api/types/container/container.go deleted file mode 100644 index a191ca8bdb7..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/container.go +++ /dev/null @@ -1,188 +0,0 @@ -package container - -import ( - "io" - "os" - "time" - - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/storage" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// ContainerUpdateOKBody OK response to ContainerUpdate operation -// -// Deprecated: use [UpdateResponse]. This alias will be removed in the next release. -type ContainerUpdateOKBody = UpdateResponse - -// ContainerTopOKBody OK response to ContainerTop operation -// -// Deprecated: use [TopResponse]. This alias will be removed in the next release. -type ContainerTopOKBody = TopResponse - -// PruneReport contains the response for Engine API: -// POST "/containers/prune" -type PruneReport struct { - ContainersDeleted []string - SpaceReclaimed uint64 -} - -// PathStat is used to encode the header from -// GET "/containers/{name:.*}/archive" -// "Name" is the file or directory name. -type PathStat struct { - Name string `json:"name"` - Size int64 `json:"size"` - Mode os.FileMode `json:"mode"` - Mtime time.Time `json:"mtime"` - LinkTarget string `json:"linkTarget"` -} - -// CopyToContainerOptions holds information -// about files to copy into a container -type CopyToContainerOptions struct { - AllowOverwriteDirWithFile bool - CopyUIDGID bool -} - -// StatsResponseReader wraps an io.ReadCloser to read (a stream of) stats -// for a container, as produced by the GET "/stats" endpoint. -// -// The OSType field is set to the server's platform to allow -// platform-specific handling of the response. -// -// TODO(thaJeztah): remove this wrapper, and make OSType part of [StatsResponse]. -type StatsResponseReader struct { - Body io.ReadCloser `json:"body"` - OSType string `json:"ostype"` -} - -// MountPoint represents a mount point configuration inside the container. -// This is used for reporting the mountpoints in use by a container. -type MountPoint struct { - // Type is the type of mount, see `Type` definitions in - // github.com/docker/docker/api/types/mount.Type - Type mount.Type `json:",omitempty"` - - // Name is the name reference to the underlying data defined by `Source` - // e.g., the volume name. - Name string `json:",omitempty"` - - // Source is the source location of the mount. - // - // For volumes, this contains the storage location of the volume (within - // `/var/lib/docker/volumes/`). For bind-mounts, and `npipe`, this contains - // the source (host) part of the bind-mount. For `tmpfs` mount points, this - // field is empty. - Source string - - // Destination is the path relative to the container root (`/`) where the - // Source is mounted inside the container. - Destination string - - // Driver is the volume driver used to create the volume (if it is a volume). - Driver string `json:",omitempty"` - - // Mode is a comma separated list of options supplied by the user when - // creating the bind/volume mount. - // - // The default is platform-specific (`"z"` on Linux, empty on Windows). - Mode string - - // RW indicates whether the mount is mounted writable (read-write). - RW bool - - // Propagation describes how mounts are propagated from the host into the - // mount point, and vice-versa. Refer to the Linux kernel documentation - // for details: - // https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt - // - // This field is not used on Windows. - Propagation mount.Propagation -} - -// State stores container's running state -// it's part of ContainerJSONBase and returned by "inspect" command -type State struct { - Status ContainerState // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead" - Running bool - Paused bool - Restarting bool - OOMKilled bool - Dead bool - Pid int - ExitCode int - Error string - StartedAt string - FinishedAt string - Health *Health `json:",omitempty"` -} - -// Summary contains response of Engine API: -// GET "/containers/json" -type Summary struct { - ID string `json:"Id"` - Names []string - Image string - ImageID string - ImageManifestDescriptor *ocispec.Descriptor `json:"ImageManifestDescriptor,omitempty"` - Command string - Created int64 - Ports []Port - SizeRw int64 `json:",omitempty"` - SizeRootFs int64 `json:",omitempty"` - Labels map[string]string - State ContainerState - Status string - HostConfig struct { - NetworkMode string `json:",omitempty"` - Annotations map[string]string `json:",omitempty"` - } - NetworkSettings *NetworkSettingsSummary - Mounts []MountPoint -} - -// ContainerJSONBase contains response of Engine API GET "/containers/{name:.*}/json" -// for API version 1.18 and older. -// -// TODO(thaJeztah): combine ContainerJSONBase and InspectResponse into a single struct. -// The split between ContainerJSONBase (ContainerJSONBase) and InspectResponse (InspectResponse) -// was done in commit 6deaa58ba5f051039643cedceee97c8695e2af74 (https://github.com/moby/moby/pull/13675). -// ContainerJSONBase contained all fields for API < 1.19, and InspectResponse -// held fields that were added in API 1.19 and up. Given that the minimum -// supported API version is now 1.24, we no longer use the separate type. -type ContainerJSONBase struct { - ID string `json:"Id"` - Created string - Path string - Args []string - State *State - Image string - ResolvConfPath string - HostnamePath string - HostsPath string - LogPath string - Name string - RestartCount int - Driver string - Platform string - MountLabel string - ProcessLabel string - AppArmorProfile string - ExecIDs []string - HostConfig *HostConfig - GraphDriver storage.DriverData - SizeRw *int64 `json:",omitempty"` - SizeRootFs *int64 `json:",omitempty"` -} - -// InspectResponse is the response for the GET "/containers/{name:.*}/json" -// endpoint. -type InspectResponse struct { - *ContainerJSONBase - Mounts []MountPoint - Config *Config - NetworkSettings *NetworkSettings - // ImageManifestDescriptor is the descriptor of a platform-specific manifest of the image used to create the container. - ImageManifestDescriptor *ocispec.Descriptor `json:"ImageManifestDescriptor,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/create_request.go b/vendor/github.com/docker/docker/api/types/container/create_request.go deleted file mode 100644 index e98dd6ad449..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/create_request.go +++ /dev/null @@ -1,13 +0,0 @@ -package container - -import "github.com/docker/docker/api/types/network" - -// CreateRequest is the request message sent to the server for container -// create calls. It is a config wrapper that holds the container [Config] -// (portable) and the corresponding [HostConfig] (non-portable) and -// [network.NetworkingConfig]. -type CreateRequest struct { - *Config - HostConfig *HostConfig `json:"HostConfig,omitempty"` - NetworkingConfig *network.NetworkingConfig `json:"NetworkingConfig,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/create_response.go b/vendor/github.com/docker/docker/api/types/container/create_response.go deleted file mode 100644 index aa0e7f7d078..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/create_response.go +++ /dev/null @@ -1,19 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// CreateResponse ContainerCreateResponse -// -// OK response to ContainerCreate operation -// swagger:model CreateResponse -type CreateResponse struct { - - // The ID of the created container - // Required: true - ID string `json:"Id"` - - // Warnings encountered when creating the container - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/disk_usage.go b/vendor/github.com/docker/docker/api/types/container/disk_usage.go deleted file mode 100644 index d77538c2ab5..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/disk_usage.go +++ /dev/null @@ -1,10 +0,0 @@ -package container - -// DiskUsage contains disk usage for containers. -// -// Deprecated: this type is no longer used and will be removed in the next release. -type DiskUsage struct { - TotalSize int64 - Reclaimable int64 - Items []*Summary -} diff --git a/vendor/github.com/docker/docker/api/types/container/errors.go b/vendor/github.com/docker/docker/api/types/container/errors.go deleted file mode 100644 index 32c978037ea..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package container - -type errInvalidParameter struct{ error } - -func (e *errInvalidParameter) InvalidParameter() {} - -func (e *errInvalidParameter) Unwrap() error { - return e.error -} diff --git a/vendor/github.com/docker/docker/api/types/container/exec.go b/vendor/github.com/docker/docker/api/types/container/exec.go deleted file mode 100644 index e455cd27b27..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/exec.go +++ /dev/null @@ -1,53 +0,0 @@ -package container - -import "github.com/docker/docker/api/types/common" - -// ExecCreateResponse is the response for a successful exec-create request. -// It holds the ID of the exec that was created. -// -// TODO(thaJeztah): make this a distinct type. -type ExecCreateResponse = common.IDResponse - -// ExecOptions is a small subset of the Config struct that holds the configuration -// for the exec feature of docker. -type ExecOptions struct { - User string // User that will run the command - Privileged bool // Is the container in privileged mode - Tty bool // Attach standard streams to a tty. - ConsoleSize *[2]uint `json:",omitempty"` // Initial console size [height, width] - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStderr bool // Attach the standard error - AttachStdout bool // Attach the standard output - DetachKeys string // Escape keys for detach - Env []string // Environment variables - WorkingDir string // Working directory - Cmd []string // Execution commands and args - - // Deprecated: the Detach field is not used, and will be removed in a future release. - Detach bool -} - -// ExecStartOptions is a temp struct used by execStart -// Config fields is part of ExecConfig in runconfig package -type ExecStartOptions struct { - // ExecStart will first check if it's detached - Detach bool - // Check if there's a tty - Tty bool - // Terminal size [height, width], unused if Tty == false - ConsoleSize *[2]uint `json:",omitempty"` -} - -// ExecAttachOptions is a temp struct used by execAttach. -// -// TODO(thaJeztah): make this a separate type; ContainerExecAttach does not use the Detach option, and cannot run detached. -type ExecAttachOptions = ExecStartOptions - -// ExecInspect holds information returned by exec inspect. -type ExecInspect struct { - ExecID string `json:"ID"` - ContainerID string - Running bool - ExitCode int - Pid int -} diff --git a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go deleted file mode 100644 index 9e9c2ad1d58..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go +++ /dev/null @@ -1,19 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// FilesystemChange Change in the container's filesystem. -// -// swagger:model FilesystemChange -type FilesystemChange struct { - - // kind - // Required: true - Kind ChangeType `json:"Kind"` - - // Path to file or directory that has changed. - // - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/health.go b/vendor/github.com/docker/docker/api/types/container/health.go deleted file mode 100644 index 96e91cc8d8a..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/health.go +++ /dev/null @@ -1,50 +0,0 @@ -package container - -import ( - "fmt" - "strings" - "time" -) - -// HealthStatus is a string representation of the container's health. -// -// It currently is an alias for string, but may become a distinct type in future. -type HealthStatus = string - -// Health states -const ( - NoHealthcheck HealthStatus = "none" // Indicates there is no healthcheck - Starting HealthStatus = "starting" // Starting indicates that the container is not yet ready - Healthy HealthStatus = "healthy" // Healthy indicates that the container is running correctly - Unhealthy HealthStatus = "unhealthy" // Unhealthy indicates that the container has a problem -) - -// Health stores information about the container's healthcheck results -type Health struct { - Status HealthStatus // Status is one of [Starting], [Healthy] or [Unhealthy]. - FailingStreak int // FailingStreak is the number of consecutive failures - Log []*HealthcheckResult // Log contains the last few results (oldest first) -} - -// HealthcheckResult stores information about a single run of a healthcheck probe -type HealthcheckResult struct { - Start time.Time // Start is the time this check started - End time.Time // End is the time this check ended - ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe - Output string // Output from last check -} - -var validHealths = []string{ - NoHealthcheck, Starting, Healthy, Unhealthy, -} - -// ValidateHealthStatus checks if the provided string is a valid -// container [HealthStatus]. -func ValidateHealthStatus(s HealthStatus) error { - switch s { - case NoHealthcheck, Starting, Healthy, Unhealthy: - return nil - default: - return errInvalidParameter{error: fmt.Errorf("invalid value for health (%s): must be one of %s", s, strings.Join(validHealths, ", "))} - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go deleted file mode 100644 index 7a41436cc70..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig.go +++ /dev/null @@ -1,506 +0,0 @@ -package container - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - "github.com/docker/go-units" -) - -// CgroupnsMode represents the cgroup namespace mode of the container -type CgroupnsMode string - -// cgroup namespace modes for containers -const ( - CgroupnsModeEmpty CgroupnsMode = "" - CgroupnsModePrivate CgroupnsMode = "private" - CgroupnsModeHost CgroupnsMode = "host" -) - -// IsPrivate indicates whether the container uses its own private cgroup namespace -func (c CgroupnsMode) IsPrivate() bool { - return c == CgroupnsModePrivate -} - -// IsHost indicates whether the container shares the host's cgroup namespace -func (c CgroupnsMode) IsHost() bool { - return c == CgroupnsModeHost -} - -// IsEmpty indicates whether the container cgroup namespace mode is unset -func (c CgroupnsMode) IsEmpty() bool { - return c == CgroupnsModeEmpty -} - -// Valid indicates whether the cgroup namespace mode is valid -func (c CgroupnsMode) Valid() bool { - return c.IsEmpty() || c.IsPrivate() || c.IsHost() -} - -// Isolation represents the isolation technology of a container. The supported -// values are platform specific -type Isolation string - -// Isolation modes for containers -const ( - IsolationEmpty Isolation = "" // IsolationEmpty is unspecified (same behavior as default) - IsolationDefault Isolation = "default" // IsolationDefault is the default isolation mode on current daemon - IsolationProcess Isolation = "process" // IsolationProcess is process isolation mode - IsolationHyperV Isolation = "hyperv" // IsolationHyperV is HyperV isolation mode -) - -// IsDefault indicates the default isolation technology of a container. On Linux this -// is the native driver. On Windows, this is a Windows Server Container. -func (i Isolation) IsDefault() bool { - // TODO consider making isolation-mode strict (case-sensitive) - v := Isolation(strings.ToLower(string(i))) - return v == IsolationDefault || v == IsolationEmpty -} - -// IsHyperV indicates the use of a Hyper-V partition for isolation -func (i Isolation) IsHyperV() bool { - // TODO consider making isolation-mode strict (case-sensitive) - return Isolation(strings.ToLower(string(i))) == IsolationHyperV -} - -// IsProcess indicates the use of process isolation -func (i Isolation) IsProcess() bool { - // TODO consider making isolation-mode strict (case-sensitive) - return Isolation(strings.ToLower(string(i))) == IsolationProcess -} - -// IpcMode represents the container ipc stack. -type IpcMode string - -// IpcMode constants -const ( - IPCModeNone IpcMode = "none" - IPCModeHost IpcMode = "host" - IPCModeContainer IpcMode = "container" - IPCModePrivate IpcMode = "private" - IPCModeShareable IpcMode = "shareable" -) - -// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. -func (n IpcMode) IsPrivate() bool { - return n == IPCModePrivate -} - -// IsHost indicates whether the container shares the host's ipc namespace. -func (n IpcMode) IsHost() bool { - return n == IPCModeHost -} - -// IsShareable indicates whether the container's ipc namespace can be shared with another container. -func (n IpcMode) IsShareable() bool { - return n == IPCModeShareable -} - -// IsContainer indicates whether the container uses another container's ipc namespace. -func (n IpcMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// IsNone indicates whether container IpcMode is set to "none". -func (n IpcMode) IsNone() bool { - return n == IPCModeNone -} - -// IsEmpty indicates whether container IpcMode is empty -func (n IpcMode) IsEmpty() bool { - return n == "" -} - -// Valid indicates whether the ipc mode is valid. -func (n IpcMode) Valid() bool { - // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. - return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() -} - -// Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// NetworkMode represents the container network stack. -type NetworkMode string - -// IsNone indicates whether container isn't using a network stack. -func (n NetworkMode) IsNone() bool { - return n == network.NetworkNone -} - -// IsDefault indicates whether container uses the default network stack. -func (n NetworkMode) IsDefault() bool { - return n == network.NetworkDefault -} - -// IsPrivate indicates whether container uses its private network stack. -func (n NetworkMode) IsPrivate() bool { - return !n.IsHost() && !n.IsContainer() -} - -// IsContainer indicates whether container uses a container network stack. -func (n NetworkMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// UserDefined indicates user-created network -func (n NetworkMode) UserDefined() string { - if n.IsUserDefined() { - return string(n) - } - return "" -} - -// UsernsMode represents userns mode in the container. -type UsernsMode string - -// IsHost indicates whether the container uses the host's userns. -func (n UsernsMode) IsHost() bool { - return n == "host" -} - -// IsPrivate indicates whether the container uses the a private userns. -func (n UsernsMode) IsPrivate() bool { - return !n.IsHost() -} - -// Valid indicates whether the userns is valid. -func (n UsernsMode) Valid() bool { - return n == "" || n.IsHost() -} - -// CgroupSpec represents the cgroup to use for the container. -type CgroupSpec string - -// IsContainer indicates whether the container is using another container cgroup -func (c CgroupSpec) IsContainer() bool { - _, ok := containerID(string(c)) - return ok -} - -// Valid indicates whether the cgroup spec is valid. -func (c CgroupSpec) Valid() bool { - // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. - return c == "" || c.IsContainer() -} - -// Container returns the ID or name of the container whose cgroup will be used. -func (c CgroupSpec) Container() (idOrName string) { - idOrName, _ = containerID(string(c)) - return idOrName -} - -// UTSMode represents the UTS namespace of the container. -type UTSMode string - -// IsPrivate indicates whether the container uses its private UTS namespace. -func (n UTSMode) IsPrivate() bool { - return !n.IsHost() -} - -// IsHost indicates whether the container uses the host's UTS namespace. -func (n UTSMode) IsHost() bool { - return n == "host" -} - -// Valid indicates whether the UTS namespace is valid. -func (n UTSMode) Valid() bool { - return n == "" || n.IsHost() -} - -// PidMode represents the pid namespace of the container. -type PidMode string - -// IsPrivate indicates whether the container uses its own new pid namespace. -func (n PidMode) IsPrivate() bool { - return !n.IsHost() && !n.IsContainer() -} - -// IsHost indicates whether the container uses the host's pid namespace. -func (n PidMode) IsHost() bool { - return n == "host" -} - -// IsContainer indicates whether the container uses a container's pid namespace. -func (n PidMode) IsContainer() bool { - _, ok := containerID(string(n)) - return ok -} - -// Valid indicates whether the pid namespace is valid. -func (n PidMode) Valid() bool { - return n == "" || n.IsHost() || validContainer(string(n)) -} - -// Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() (idOrName string) { - idOrName, _ = containerID(string(n)) - return idOrName -} - -// DeviceRequest represents a request for devices from a device driver. -// Used by GPU device drivers. -type DeviceRequest struct { - Driver string // Name of device driver - Count int // Number of devices to request (-1 = All) - DeviceIDs []string // List of device IDs as recognizable by the device driver - Capabilities [][]string // An OR list of AND lists of device capabilities (e.g. "gpu") - Options map[string]string // Options to pass onto the device driver -} - -// DeviceMapping represents the device mapping between the host and the container. -type DeviceMapping struct { - PathOnHost string - PathInContainer string - CgroupPermissions string -} - -// RestartPolicy represents the restart policies of the container. -type RestartPolicy struct { - Name RestartPolicyMode - MaximumRetryCount int -} - -type RestartPolicyMode string - -const ( - RestartPolicyDisabled RestartPolicyMode = "no" - RestartPolicyAlways RestartPolicyMode = "always" - RestartPolicyOnFailure RestartPolicyMode = "on-failure" - RestartPolicyUnlessStopped RestartPolicyMode = "unless-stopped" -) - -// IsNone indicates whether the container has the "no" restart policy. -// This means the container will not automatically restart when exiting. -func (rp *RestartPolicy) IsNone() bool { - return rp.Name == RestartPolicyDisabled || rp.Name == "" -} - -// IsAlways indicates whether the container has the "always" restart policy. -// This means the container will automatically restart regardless of the exit status. -func (rp *RestartPolicy) IsAlways() bool { - return rp.Name == RestartPolicyAlways -} - -// IsOnFailure indicates whether the container has the "on-failure" restart policy. -// This means the container will automatically restart of exiting with a non-zero exit status. -func (rp *RestartPolicy) IsOnFailure() bool { - return rp.Name == RestartPolicyOnFailure -} - -// IsUnlessStopped indicates whether the container has the -// "unless-stopped" restart policy. This means the container will -// automatically restart unless user has put it to stopped state. -func (rp *RestartPolicy) IsUnlessStopped() bool { - return rp.Name == RestartPolicyUnlessStopped -} - -// IsSame compares two RestartPolicy to see if they are the same -func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { - return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount -} - -// ValidateRestartPolicy validates the given RestartPolicy. -func ValidateRestartPolicy(policy RestartPolicy) error { - switch policy.Name { - case RestartPolicyAlways, RestartPolicyUnlessStopped, RestartPolicyDisabled: - if policy.MaximumRetryCount != 0 { - msg := "invalid restart policy: maximum retry count can only be used with 'on-failure'" - if policy.MaximumRetryCount < 0 { - msg += " and cannot be negative" - } - return &errInvalidParameter{errors.New(msg)} - } - return nil - case RestartPolicyOnFailure: - if policy.MaximumRetryCount < 0 { - return &errInvalidParameter{errors.New("invalid restart policy: maximum retry count cannot be negative")} - } - return nil - case "": - // Versions before v25.0.0 created an empty restart-policy "name" as - // default. Allow an empty name with "any" MaximumRetryCount for - // backward-compatibility. - return nil - default: - return &errInvalidParameter{fmt.Errorf("invalid restart policy: unknown policy '%s'; use one of '%s', '%s', '%s', or '%s'", policy.Name, RestartPolicyDisabled, RestartPolicyAlways, RestartPolicyOnFailure, RestartPolicyUnlessStopped)} - } -} - -// LogMode is a type to define the available modes for logging -// These modes affect how logs are handled when log messages start piling up. -type LogMode string - -// Available logging modes -const ( - LogModeUnset LogMode = "" - LogModeBlocking LogMode = "blocking" - LogModeNonBlock LogMode = "non-blocking" -) - -// LogConfig represents the logging configuration of the container. -type LogConfig struct { - Type string - Config map[string]string -} - -// Ulimit is an alias for [units.Ulimit], which may be moving to a different -// location or become a local type. This alias is to help transitioning. -// -// Users are recommended to use this alias instead of using [units.Ulimit] directly. -type Ulimit = units.Ulimit - -// Resources contains container's resources (cgroups config, ulimits...) -type Resources struct { - // Applicable to all platforms - CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) - Memory int64 // Memory limit (in bytes) - NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. - - // Applicable to UNIX platforms - CgroupParent string // Parent cgroup. - BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) - BlkioWeightDevice []*blkiodev.WeightDevice - BlkioDeviceReadBps []*blkiodev.ThrottleDevice - BlkioDeviceWriteBps []*blkiodev.ThrottleDevice - BlkioDeviceReadIOps []*blkiodev.ThrottleDevice - BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice - CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period - CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota - CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime - CpusetCpus string // CpusetCpus 0-2, 0,1 - CpusetMems string // CpusetMems 0-2, 0,1 - Devices []DeviceMapping // List of devices to map inside the container - DeviceCgroupRules []string // List of rule to be added to the device cgroup - DeviceRequests []DeviceRequest // List of device requests for device drivers - - // KernelMemory specifies the kernel memory limit (in bytes) for the container. - // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes. - KernelMemory int64 `json:",omitempty"` - // Hard limit for kernel TCP buffer memory (in bytes). - // - // Deprecated: This field is deprecated and will be removed in the next release. - // Starting with 6.12, the kernel has deprecated kernel memory tcp accounting - // for cgroups v1. - KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes) - MemoryReservation int64 // Memory soft limit (in bytes) - MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap - MemorySwappiness *int64 // Tuning container memory swappiness behaviour - OomKillDisable *bool // Whether to disable OOM Killer or not - PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. - Ulimits []*Ulimit // List of ulimits to be set in the container - - // Applicable to Windows - CPUCount int64 `json:"CpuCount"` // CPU count - CPUPercent int64 `json:"CpuPercent"` // CPU percent - IOMaximumIOps uint64 // Maximum IOps for the container system drive - IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive -} - -// UpdateConfig holds the mutable attributes of a Container. -// Those attributes can be updated at runtime. -type UpdateConfig struct { - // Contains container's resources (cgroups, ulimits) - Resources - RestartPolicy RestartPolicy -} - -// HostConfig the non-portable Config structure of a container. -// Here, "non-portable" means "dependent of the host we are running on". -// Portable information *should* appear in Config. -type HostConfig struct { - // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - ConsoleSize [2]uint // Initial console size (height,width) - Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime - - // Applicable to UNIX platforms - CapAdd strslice.StrSlice // List of kernel capabilities to add to the container - CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container - CgroupnsMode CgroupnsMode // Cgroup namespace mode to use for the container - DNS []string `json:"Dns"` // List of DNS server to lookup - DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for - DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for - ExtraHosts []string // List of extra hosts - GroupAdd []string // List of additional groups that the container process will run as - IpcMode IpcMode // IPC namespace to use for the container - Cgroup CgroupSpec // Cgroup to use for the container - Links []string // List of links (in the name:alias form) - OomScoreAdj int // Container preference for OOM-killing - PidMode PidMode // PID namespace to use for the container - Privileged bool // Is the container in privileged mode - PublishAllPorts bool // Should docker publish all exposed port for the container - ReadonlyRootfs bool // Is the container root filesystem in read-only - SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. - StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. - Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container - UTSMode UTSMode // UTS namespace to use for the container - UsernsMode UsernsMode // The user namespace to use for the container - ShmSize int64 // Total shm memory usage - Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container - Runtime string `json:",omitempty"` // Runtime to use with this container - - // Applicable to Windows - Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) - - // Contains container's resources (cgroups, ulimits) - Resources - - // Mounts specs used by the container - Mounts []mount.Mount `json:",omitempty"` - - // MaskedPaths is the list of paths to be masked inside the container (this overrides the default set of paths) - MaskedPaths []string - - // ReadonlyPaths is the list of paths to be set as read-only inside the container (this overrides the default set of paths) - ReadonlyPaths []string - - // Run a custom init inside the container, if null, use the daemon's configured settings - Init *bool `json:",omitempty"` -} - -// containerID splits "container:" values. It returns the container -// ID or name, and whether an ID/name was found. It returns an empty string and -// a "false" if the value does not have a "container:" prefix. Further validation -// of the returned, including checking if the value is empty, should be handled -// by the caller. -func containerID(val string) (idOrName string, ok bool) { - k, v, hasSep := strings.Cut(val, ":") - if !hasSep || k != "container" { - return "", false - } - return v, true -} - -// validContainer checks if the given value is a "container:" mode with -// a non-empty name/ID. -func validContainer(val string) bool { - id, ok := containerID(val) - return ok && id != "" -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go deleted file mode 100644 index cd6a7a9be22..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ /dev/null @@ -1,45 +0,0 @@ -//go:build !windows - -package container - -import "github.com/docker/docker/api/types/network" - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() -} - -// IsBridge indicates whether container uses the bridge network stack -func (n NetworkMode) IsBridge() bool { - return n == network.NetworkBridge -} - -// IsHost indicates whether container uses the host network stack. -func (n NetworkMode) IsHost() bool { - return n == network.NetworkHost -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - switch { - case n.IsDefault(): - return network.NetworkDefault - case n.IsBridge(): - return network.NetworkBridge - case n.IsHost(): - return network.NetworkHost - case n.IsNone(): - return network.NetworkNone - case n.IsContainer(): - return "container" - case n.IsUserDefined(): - return n.UserDefined() - default: - return "" - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go deleted file mode 100644 index db63e190d19..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ /dev/null @@ -1,47 +0,0 @@ -package container - -import "github.com/docker/docker/api/types/network" - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() || i.IsHyperV() || i.IsProcess() -} - -// IsBridge indicates whether container uses the bridge network stack -// in windows it is given the name NAT -func (n NetworkMode) IsBridge() bool { - return n == network.NetworkNat -} - -// IsHost indicates whether container uses the host network stack. -// returns false as this is not supported by windows -func (n NetworkMode) IsHost() bool { - return false -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - switch { - case n.IsDefault(): - return network.NetworkDefault - case n.IsBridge(): - return network.NetworkNat - case n.IsHost(): - // Windows currently doesn't support host network-mode, so - // this would currently never happen.. - return network.NetworkHost - case n.IsNone(): - return network.NetworkNone - case n.IsContainer(): - return "container" - case n.IsUserDefined(): - return n.UserDefined() - default: - return "" - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/network_settings.go b/vendor/github.com/docker/docker/api/types/container/network_settings.go deleted file mode 100644 index 687145f2953..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/network_settings.go +++ /dev/null @@ -1,85 +0,0 @@ -package container - -import ( - "github.com/docker/docker/api/types/network" - "github.com/docker/go-connections/nat" -) - -// NetworkSettings exposes the network settings in the api -type NetworkSettings struct { - NetworkSettingsBase - DefaultNetworkSettings - Networks map[string]*network.EndpointSettings -} - -// NetworkSettingsBase holds networking state for a container when inspecting it. -// -// Deprecated: Most fields in NetworkSettingsBase are deprecated. Fields which aren't deprecated will move to -// NetworkSettings in v29.0, and this struct will be removed. -type NetworkSettingsBase struct { - Bridge string // Deprecated: This field is only set when the daemon is started with the --bridge flag specified. - SandboxID string // SandboxID uniquely represents a container's network stack - SandboxKey string // SandboxKey identifies the sandbox - Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port - - // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface - // - // Deprecated: This field is never set and will be removed in a future release. - HairpinMode bool - // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix - // - // Deprecated: This field is never set and will be removed in a future release. - LinkLocalIPv6Address string - // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address - // - // Deprecated: This field is never set and will be removed in a future release. - LinkLocalIPv6PrefixLen int - SecondaryIPAddresses []network.Address // Deprecated: This field is never set and will be removed in a future release. - SecondaryIPv6Addresses []network.Address // Deprecated: This field is never set and will be removed in a future release. -} - -// DefaultNetworkSettings holds the networking state for the default bridge, if the container is connected to that -// network. -// -// Deprecated: this struct is deprecated since Docker v1.11 and will be removed in v29. You should look for the default -// network in NetworkSettings.Networks instead. -type DefaultNetworkSettings struct { - // EndpointID uniquely represents a service endpoint in a Sandbox - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - EndpointID string - // Gateway holds the gateway address for the network - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - Gateway string - // GlobalIPv6Address holds network's global IPv6 address - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - GlobalIPv6Address string - // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - GlobalIPv6PrefixLen int - // IPAddress holds the IPv4 address for the network - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - IPAddress string - // IPPrefixLen represents mask length of network's IPv4 address - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - IPPrefixLen int - // IPv6Gateway holds gateway address specific for IPv6 - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - IPv6Gateway string - // MacAddress holds the MAC address for the network - // - // Deprecated: This field will be removed in v29. You should look for the default network in NetworkSettings.Networks instead. - MacAddress string -} - -// NetworkSettingsSummary provides a summary of container's networks -// in /containers/json -type NetworkSettingsSummary struct { - Networks map[string]*network.EndpointSettings -} diff --git a/vendor/github.com/docker/docker/api/types/container/options.go b/vendor/github.com/docker/docker/api/types/container/options.go deleted file mode 100644 index 7a230057692..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/options.go +++ /dev/null @@ -1,67 +0,0 @@ -package container - -import "github.com/docker/docker/api/types/filters" - -// ResizeOptions holds parameters to resize a TTY. -// It can be used to resize container TTYs and -// exec process TTYs too. -type ResizeOptions struct { - Height uint - Width uint -} - -// AttachOptions holds parameters to attach to a container. -type AttachOptions struct { - Stream bool - Stdin bool - Stdout bool - Stderr bool - DetachKeys string - Logs bool -} - -// CommitOptions holds parameters to commit changes into a container. -type CommitOptions struct { - Reference string - Comment string - Author string - Changes []string - Pause bool - Config *Config -} - -// RemoveOptions holds parameters to remove containers. -type RemoveOptions struct { - RemoveVolumes bool - RemoveLinks bool - Force bool -} - -// StartOptions holds parameters to start containers. -type StartOptions struct { - CheckpointID string - CheckpointDir string -} - -// ListOptions holds parameters to list containers with. -type ListOptions struct { - Size bool - All bool - Latest bool - Since string - Before string - Limit int - Filters filters.Args -} - -// LogsOptions holds parameters to filter logs with. -type LogsOptions struct { - ShowStdout bool - ShowStderr bool - Since string - Until string - Timestamps bool - Follow bool - Tail string - Details bool -} diff --git a/vendor/github.com/docker/docker/api/types/container/port.go b/vendor/github.com/docker/docker/api/types/container/port.go deleted file mode 100644 index 895043cfe94..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/port.go +++ /dev/null @@ -1,23 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Port An open port on a container -// swagger:model Port -type Port struct { - - // Host IP address that the container's port is mapped to - IP string `json:"IP,omitempty"` - - // Port on the container - // Required: true - PrivatePort uint16 `json:"PrivatePort"` - - // Port exposed on the host - PublicPort uint16 `json:"PublicPort,omitempty"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/state.go b/vendor/github.com/docker/docker/api/types/container/state.go deleted file mode 100644 index 78d5c4fe85c..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/state.go +++ /dev/null @@ -1,64 +0,0 @@ -package container - -import ( - "fmt" - "strings" -) - -// ContainerState is a string representation of the container's current state. -// -// It currently is an alias for string, but may become a distinct type in the future. -type ContainerState = string - -const ( - StateCreated ContainerState = "created" // StateCreated indicates the container is created, but not (yet) started. - StateRunning ContainerState = "running" // StateRunning indicates that the container is running. - StatePaused ContainerState = "paused" // StatePaused indicates that the container's current state is paused. - StateRestarting ContainerState = "restarting" // StateRestarting indicates that the container is currently restarting. - StateRemoving ContainerState = "removing" // StateRemoving indicates that the container is being removed. - StateExited ContainerState = "exited" // StateExited indicates that the container exited. - StateDead ContainerState = "dead" // StateDead indicates that the container failed to be deleted. Containers in this state are attempted to be cleaned up when the daemon restarts. -) - -var validStates = []ContainerState{ - StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead, -} - -// ValidateContainerState checks if the provided string is a valid -// container [ContainerState]. -func ValidateContainerState(s ContainerState) error { - switch s { - case StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead: - return nil - default: - return errInvalidParameter{error: fmt.Errorf("invalid value for state (%s): must be one of %s", s, strings.Join(validStates, ", "))} - } -} - -// StateStatus is used to return container wait results. -// Implements exec.ExitCode interface. -// This type is needed as State include a sync.Mutex field which make -// copying it unsafe. -type StateStatus struct { - exitCode int - err error -} - -// ExitCode returns current exitcode for the state. -func (s StateStatus) ExitCode() int { - return s.exitCode -} - -// Err returns current error for the state. Returns nil if the container had -// exited on its own. -func (s StateStatus) Err() error { - return s.err -} - -// NewStateStatus returns a new StateStatus with the given exit code and error. -func NewStateStatus(exitCode int, err error) StateStatus { - return StateStatus{ - exitCode: exitCode, - err: err, - } -} diff --git a/vendor/github.com/docker/docker/api/types/container/stats.go b/vendor/github.com/docker/docker/api/types/container/stats.go deleted file mode 100644 index 3bfeb4849f9..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/stats.go +++ /dev/null @@ -1,177 +0,0 @@ -package container - -import "time" - -// ThrottlingData stores CPU throttling stats of one running container. -// Not used on Windows. -type ThrottlingData struct { - // Number of periods with throttling active - Periods uint64 `json:"periods"` - // Number of periods when the container hits its throttling limit. - ThrottledPeriods uint64 `json:"throttled_periods"` - // Aggregate time the container was throttled for in nanoseconds. - ThrottledTime uint64 `json:"throttled_time"` -} - -// CPUUsage stores All CPU stats aggregated since container inception. -type CPUUsage struct { - // Total CPU time consumed. - // Units: nanoseconds (Linux) - // Units: 100's of nanoseconds (Windows) - TotalUsage uint64 `json:"total_usage"` - - // Total CPU time consumed per core (Linux). Not used on Windows. - // Units: nanoseconds. - PercpuUsage []uint64 `json:"percpu_usage,omitempty"` - - // Time spent by tasks of the cgroup in kernel mode (Linux). - // Time spent by all container processes in kernel mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. - UsageInKernelmode uint64 `json:"usage_in_kernelmode"` - - // Time spent by tasks of the cgroup in user mode (Linux). - // Time spent by all container processes in user mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers - UsageInUsermode uint64 `json:"usage_in_usermode"` -} - -// CPUStats aggregates and wraps all CPU related info of container -type CPUStats struct { - // CPU Usage. Linux and Windows. - CPUUsage CPUUsage `json:"cpu_usage"` - - // System Usage. Linux only. - SystemUsage uint64 `json:"system_cpu_usage,omitempty"` - - // Online CPUs. Linux only. - OnlineCPUs uint32 `json:"online_cpus,omitempty"` - - // Throttling Data. Linux only. - ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` -} - -// MemoryStats aggregates all memory stats since container inception on Linux. -// Windows returns stats for commit and private working set only. -type MemoryStats struct { - // Linux Memory Stats - - // current res_counter usage for memory - Usage uint64 `json:"usage,omitempty"` - // maximum usage ever recorded. - MaxUsage uint64 `json:"max_usage,omitempty"` - // TODO(vishh): Export these as stronger types. - // all the stats exported via memory.stat. - Stats map[string]uint64 `json:"stats,omitempty"` - // number of times memory usage hits limits. - Failcnt uint64 `json:"failcnt,omitempty"` - Limit uint64 `json:"limit,omitempty"` - - // Windows Memory Stats - // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx - - // committed bytes - Commit uint64 `json:"commitbytes,omitempty"` - // peak committed bytes - CommitPeak uint64 `json:"commitpeakbytes,omitempty"` - // private working set - PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` -} - -// BlkioStatEntry is one small entity to store a piece of Blkio stats -// Not used on Windows. -type BlkioStatEntry struct { - Major uint64 `json:"major"` - Minor uint64 `json:"minor"` - Op string `json:"op"` - Value uint64 `json:"value"` -} - -// BlkioStats stores All IO service stats for data read and write. -// This is a Linux specific structure as the differences between expressing -// block I/O on Windows and Linux are sufficiently significant to make -// little sense attempting to morph into a combined structure. -type BlkioStats struct { - // number of bytes transferred to and from the block device - IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` - IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` - IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` - IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` - IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` - IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` - IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` - SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` -} - -// StorageStats is the disk I/O stats for read/write on Windows. -type StorageStats struct { - ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` - ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` - WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` - WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` -} - -// NetworkStats aggregates the network stats of one container -type NetworkStats struct { - // Bytes received. Windows and Linux. - RxBytes uint64 `json:"rx_bytes"` - // Packets received. Windows and Linux. - RxPackets uint64 `json:"rx_packets"` - // Received errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - RxErrors uint64 `json:"rx_errors"` - // Incoming packets dropped. Windows and Linux. - RxDropped uint64 `json:"rx_dropped"` - // Bytes sent. Windows and Linux. - TxBytes uint64 `json:"tx_bytes"` - // Packets sent. Windows and Linux. - TxPackets uint64 `json:"tx_packets"` - // Sent errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - TxErrors uint64 `json:"tx_errors"` - // Outgoing packets dropped. Windows and Linux. - TxDropped uint64 `json:"tx_dropped"` - // Endpoint ID. Not used on Linux. - EndpointID string `json:"endpoint_id,omitempty"` - // Instance ID. Not used on Linux. - InstanceID string `json:"instance_id,omitempty"` -} - -// PidsStats contains the stats of a container's pids -type PidsStats struct { - // Current is the number of pids in the cgroup - Current uint64 `json:"current,omitempty"` - // Limit is the hard limit on the number of pids in the cgroup. - // A "Limit" of 0 means that there is no limit. - Limit uint64 `json:"limit,omitempty"` -} - -// Stats is Ultimate struct aggregating all types of stats of one container -// -// Deprecated: use [StatsResponse] instead. This type will be removed in the next release. -type Stats = StatsResponse - -// StatsResponse aggregates all types of stats of one container. -type StatsResponse struct { - Name string `json:"name,omitempty"` - ID string `json:"id,omitempty"` - - // Common stats - Read time.Time `json:"read"` - PreRead time.Time `json:"preread"` - - // Linux specific stats, not populated on Windows. - PidsStats PidsStats `json:"pids_stats,omitempty"` - BlkioStats BlkioStats `json:"blkio_stats,omitempty"` - - // Windows specific stats, not populated on Linux. - NumProcs uint32 `json:"num_procs"` - StorageStats StorageStats `json:"storage_stats,omitempty"` - - // Shared stats - CPUStats CPUStats `json:"cpu_stats,omitempty"` - PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" - MemoryStats MemoryStats `json:"memory_stats,omitempty"` - Networks map[string]NetworkStats `json:"networks,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/top_response.go b/vendor/github.com/docker/docker/api/types/container/top_response.go deleted file mode 100644 index b4bae5ef036..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/top_response.go +++ /dev/null @@ -1,18 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// TopResponse ContainerTopResponse -// -// Container "top" response. -// swagger:model TopResponse -type TopResponse struct { - - // Each process running in the container, where each process - // is an array of values corresponding to the titles. - Processes [][]string `json:"Processes"` - - // The ps column titles - Titles []string `json:"Titles"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/update_response.go b/vendor/github.com/docker/docker/api/types/container/update_response.go deleted file mode 100644 index e2b5bf5ac0e..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/update_response.go +++ /dev/null @@ -1,14 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// UpdateResponse ContainerUpdateResponse -// -// Response for a successful container-update. -// swagger:model UpdateResponse -type UpdateResponse struct { - - // Warnings encountered when updating the container. - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go b/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go deleted file mode 100644 index ab56d4eed8e..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/wait_exit_error.go +++ /dev/null @@ -1,12 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// WaitExitError container waiting error, if any -// swagger:model WaitExitError -type WaitExitError struct { - - // Details of an error - Message string `json:"Message,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/wait_response.go b/vendor/github.com/docker/docker/api/types/container/wait_response.go deleted file mode 100644 index 84fc6afddc6..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/wait_response.go +++ /dev/null @@ -1,18 +0,0 @@ -package container - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// WaitResponse ContainerWaitResponse -// -// OK response to ContainerWait operation -// swagger:model WaitResponse -type WaitResponse struct { - - // error - Error *WaitExitError `json:"Error,omitempty"` - - // Exit code of the container - // Required: true - StatusCode int64 `json:"StatusCode"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/waitcondition.go b/vendor/github.com/docker/docker/api/types/container/waitcondition.go deleted file mode 100644 index 64820fe3583..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/waitcondition.go +++ /dev/null @@ -1,22 +0,0 @@ -package container - -// WaitCondition is a type used to specify a container state for which -// to wait. -type WaitCondition string - -// Possible WaitCondition Values. -// -// WaitConditionNotRunning (default) is used to wait for any of the non-running -// states: "created", "exited", "dead", "removing", or "removed". -// -// WaitConditionNextExit is used to wait for the next time the state changes -// to a non-running state. If the state is currently "created" or "exited", -// this would cause Wait() to block until either the container runs and exits -// or is removed. -// -// WaitConditionRemoved is used to wait for the container to be removed. -const ( - WaitConditionNotRunning WaitCondition = "not-running" - WaitConditionNextExit WaitCondition = "next-exit" - WaitConditionRemoved WaitCondition = "removed" -) diff --git a/vendor/github.com/docker/docker/api/types/filters/errors.go b/vendor/github.com/docker/docker/api/types/filters/errors.go deleted file mode 100644 index b8a690d67ab..00000000000 --- a/vendor/github.com/docker/docker/api/types/filters/errors.go +++ /dev/null @@ -1,24 +0,0 @@ -package filters - -import "fmt" - -// invalidFilter indicates that the provided filter or its value is invalid -type invalidFilter struct { - Filter string - Value []string -} - -func (e invalidFilter) Error() string { - msg := "invalid filter" - if e.Filter != "" { - msg += " '" + e.Filter - if e.Value != nil { - msg = fmt.Sprintf("%s=%s", msg, e.Value) - } - msg += "'" - } - return msg -} - -// InvalidParameter marks this error as ErrInvalidParameter -func (e invalidFilter) InvalidParameter() {} diff --git a/vendor/github.com/docker/docker/api/types/filters/filters_deprecated.go b/vendor/github.com/docker/docker/api/types/filters/filters_deprecated.go deleted file mode 100644 index 4504cd7a7fe..00000000000 --- a/vendor/github.com/docker/docker/api/types/filters/filters_deprecated.go +++ /dev/null @@ -1,61 +0,0 @@ -package filters - -import ( - "encoding/json" - - "github.com/docker/docker/api/types/versions" -) - -// ToParamWithVersion encodes Args as a JSON string. If version is less than 1.22 -// then the encoded format will use an older legacy format where the values are a -// list of strings, instead of a set. -// -// Deprecated: do not use in any new code; use ToJSON instead -func ToParamWithVersion(version string, a Args) (string, error) { - out, err := ToJSON(a) - if out == "" || err != nil { - return "", nil - } - if version != "" && versions.LessThan(version, "1.22") { - return encodeLegacyFilters(out) - } - return out, nil -} - -// encodeLegacyFilters encodes Args in the legacy format as used in API v1.21 and older. -// where values are a list of strings, instead of a set. -// -// Don't use in any new code; use [filters.ToJSON]] instead. -func encodeLegacyFilters(currentFormat string) (string, error) { - // The Args.fields field is not exported, but used to marshal JSON, - // so we'll marshal to the new format, then unmarshal to get the - // fields, and marshal again. - // - // This is far from optimal, but this code is only used for deprecated - // API versions, so should not be hit commonly. - var argsFields map[string]map[string]bool - err := json.Unmarshal([]byte(currentFormat), &argsFields) - if err != nil { - return "", err - } - - buf, err := json.Marshal(convertArgsToSlice(argsFields)) - if err != nil { - return "", err - } - return string(buf), nil -} - -func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { - m := map[string][]string{} - for k, v := range f { - values := []string{} - for kk := range v { - if v[kk] { - values = append(values, kk) - } - } - m[k] = values - } - return m -} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go deleted file mode 100644 index 396657bb192..00000000000 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ /dev/null @@ -1,302 +0,0 @@ -/* -Package filters provides tools for encoding a mapping of keys to a set of -multiple values. -*/ -package filters - -import ( - "encoding/json" - "regexp" - "strings" -) - -// Args stores a mapping of keys to a set of multiple values. -type Args struct { - fields map[string]map[string]bool -} - -// KeyValuePair are used to initialize a new Args -type KeyValuePair struct { - Key string - Value string -} - -// Arg creates a new KeyValuePair for initializing Args -func Arg(key, value string) KeyValuePair { - return KeyValuePair{Key: key, Value: value} -} - -// NewArgs returns a new Args populated with the initial args -func NewArgs(initialArgs ...KeyValuePair) Args { - args := Args{fields: map[string]map[string]bool{}} - for _, arg := range initialArgs { - args.Add(arg.Key, arg.Value) - } - return args -} - -// Keys returns all the keys in list of Args -func (args Args) Keys() []string { - keys := make([]string, 0, len(args.fields)) - for k := range args.fields { - keys = append(keys, k) - } - return keys -} - -// MarshalJSON returns a JSON byte representation of the Args -func (args Args) MarshalJSON() ([]byte, error) { - if len(args.fields) == 0 { - return []byte("{}"), nil - } - return json.Marshal(args.fields) -} - -// ToJSON returns the Args as a JSON encoded string -func ToJSON(a Args) (string, error) { - if a.Len() == 0 { - return "", nil - } - buf, err := json.Marshal(a) - return string(buf), err -} - -// FromJSON decodes a JSON encoded string into Args -func FromJSON(p string) (Args, error) { - args := NewArgs() - - if p == "" { - return args, nil - } - - raw := []byte(p) - err := json.Unmarshal(raw, &args) - if err == nil { - return args, nil - } - - // Fallback to parsing arguments in the legacy slice format - deprecated := map[string][]string{} - if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { - return args, &invalidFilter{} - } - - args.fields = deprecatedArgs(deprecated) - return args, nil -} - -// UnmarshalJSON populates the Args from JSON encode bytes -func (args Args) UnmarshalJSON(raw []byte) error { - return json.Unmarshal(raw, &args.fields) -} - -// Get returns the list of values associated with the key -func (args Args) Get(key string) []string { - values := args.fields[key] - if values == nil { - return make([]string, 0) - } - slice := make([]string, 0, len(values)) - for key := range values { - slice = append(slice, key) - } - return slice -} - -// Add a new value to the set of values -func (args Args) Add(key, value string) { - if _, ok := args.fields[key]; ok { - args.fields[key][value] = true - } else { - args.fields[key] = map[string]bool{value: true} - } -} - -// Del removes a value from the set -func (args Args) Del(key, value string) { - if _, ok := args.fields[key]; ok { - delete(args.fields[key], value) - if len(args.fields[key]) == 0 { - delete(args.fields, key) - } - } -} - -// Len returns the number of keys in the mapping -func (args Args) Len() int { - return len(args.fields) -} - -// MatchKVList returns true if all the pairs in sources exist as key=value -// pairs in the mapping at key, or if there are no values at key. -func (args Args) MatchKVList(key string, sources map[string]string) bool { - fieldValues := args.fields[key] - - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - - if len(sources) == 0 { - return false - } - - for value := range fieldValues { - testK, testV, hasValue := strings.Cut(value, "=") - - v, ok := sources[testK] - if !ok { - return false - } - if hasValue && testV != v { - return false - } - } - - return true -} - -// Match returns true if any of the values at key match the source string -func (args Args) Match(field, source string) bool { - if args.ExactMatch(field, source) { - return true - } - - fieldValues := args.fields[field] - for name2match := range fieldValues { - match, err := regexp.MatchString(name2match, source) - if err != nil { - continue - } - if match { - return true - } - } - return false -} - -// GetBoolOrDefault returns a boolean value of the key if the key is present -// and is interpretable as a boolean value. Otherwise the default value is returned. -// Error is not nil only if the filter values are not valid boolean or are conflicting. -func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) { - fieldValues, ok := args.fields[key] - if !ok { - return defaultValue, nil - } - - if len(fieldValues) == 0 { - return defaultValue, &invalidFilter{key, nil} - } - - isFalse := fieldValues["0"] || fieldValues["false"] - isTrue := fieldValues["1"] || fieldValues["true"] - if isFalse == isTrue { - // Either no or conflicting truthy/falsy value were provided - return defaultValue, &invalidFilter{key, args.Get(key)} - } - return isTrue, nil -} - -// ExactMatch returns true if the source matches exactly one of the values. -func (args Args) ExactMatch(key, source string) bool { - fieldValues, ok := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if !ok || len(fieldValues) == 0 { - return true - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// UniqueExactMatch returns true if there is only one value and the source -// matches exactly the value. -func (args Args) UniqueExactMatch(key, source string) bool { - fieldValues := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - if len(args.fields[key]) != 1 { - return false - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// FuzzyMatch returns true if the source matches exactly one value, or the -// source has one of the values as a prefix. -func (args Args) FuzzyMatch(key, source string) bool { - if args.ExactMatch(key, source) { - return true - } - - fieldValues := args.fields[key] - for prefix := range fieldValues { - if strings.HasPrefix(source, prefix) { - return true - } - } - return false -} - -// Contains returns true if the key exists in the mapping -func (args Args) Contains(field string) bool { - _, ok := args.fields[field] - return ok -} - -// Validate compared the set of accepted keys against the keys in the mapping. -// An error is returned if any mapping keys are not in the accepted set. -func (args Args) Validate(accepted map[string]bool) error { - for name := range args.fields { - if !accepted[name] { - return &invalidFilter{name, nil} - } - } - return nil -} - -// WalkValues iterates over the list of values for a key in the mapping and calls -// op() for each value. If op returns an error the iteration stops and the -// error is returned. -func (args Args) WalkValues(field string, op func(value string) error) error { - if _, ok := args.fields[field]; !ok { - return nil - } - for v := range args.fields[field] { - if err := op(v); err != nil { - return err - } - } - return nil -} - -// Clone returns a copy of args. -func (args Args) Clone() (newArgs Args) { - newArgs.fields = make(map[string]map[string]bool, len(args.fields)) - for k, m := range args.fields { - var mm map[string]bool - if m != nil { - mm = make(map[string]bool, len(m)) - for kk, v := range m { - mm[kk] = v - } - } - newArgs.fields[k] = mm - } - return newArgs -} - -func deprecatedArgs(d map[string][]string) map[string]map[string]bool { - m := map[string]map[string]bool{} - for k, v := range d { - values := map[string]bool{} - for _, vv := range v { - values[vv] = true - } - m[k] = values - } - return m -} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go deleted file mode 100644 index 090d436c626..00000000000 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ /dev/null @@ -1,157 +0,0 @@ -package mount - -import ( - "os" -) - -// Type represents the type of a mount. -type Type string - -// Type constants -const ( - // TypeBind is the type for mounting host dir - TypeBind Type = "bind" - // TypeVolume is the type for remote storage volumes - TypeVolume Type = "volume" - // TypeTmpfs is the type for mounting tmpfs - TypeTmpfs Type = "tmpfs" - // TypeNamedPipe is the type for mounting Windows named pipes - TypeNamedPipe Type = "npipe" - // TypeCluster is the type for Swarm Cluster Volumes. - TypeCluster Type = "cluster" - // TypeImage is the type for mounting another image's filesystem - TypeImage Type = "image" -) - -// Mount represents a mount (volume). -type Mount struct { - Type Type `json:",omitempty"` - // Source specifies the name of the mount. Depending on mount type, this - // may be a volume name or a host path, or even ignored. - // Source is not supported for tmpfs (must be an empty value) - Source string `json:",omitempty"` - Target string `json:",omitempty"` - ReadOnly bool `json:",omitempty"` // attempts recursive read-only if possible - Consistency Consistency `json:",omitempty"` - - BindOptions *BindOptions `json:",omitempty"` - VolumeOptions *VolumeOptions `json:",omitempty"` - ImageOptions *ImageOptions `json:",omitempty"` - TmpfsOptions *TmpfsOptions `json:",omitempty"` - ClusterOptions *ClusterOptions `json:",omitempty"` -} - -// Propagation represents the propagation of a mount. -type Propagation string - -const ( - // PropagationRPrivate RPRIVATE - PropagationRPrivate Propagation = "rprivate" - // PropagationPrivate PRIVATE - PropagationPrivate Propagation = "private" - // PropagationRShared RSHARED - PropagationRShared Propagation = "rshared" - // PropagationShared SHARED - PropagationShared Propagation = "shared" - // PropagationRSlave RSLAVE - PropagationRSlave Propagation = "rslave" - // PropagationSlave SLAVE - PropagationSlave Propagation = "slave" -) - -// Propagations is the list of all valid mount propagations -var Propagations = []Propagation{ - PropagationRPrivate, - PropagationPrivate, - PropagationRShared, - PropagationShared, - PropagationRSlave, - PropagationSlave, -} - -// Consistency represents the consistency requirements of a mount. -type Consistency string - -const ( - // ConsistencyFull guarantees bind mount-like consistency - ConsistencyFull Consistency = "consistent" - // ConsistencyCached mounts can cache read data and FS structure - ConsistencyCached Consistency = "cached" - // ConsistencyDelegated mounts can cache read and written data and structure - ConsistencyDelegated Consistency = "delegated" - // ConsistencyDefault provides "consistent" behavior unless overridden - ConsistencyDefault Consistency = "default" -) - -// BindOptions defines options specific to mounts of type "bind". -type BindOptions struct { - Propagation Propagation `json:",omitempty"` - NonRecursive bool `json:",omitempty"` - CreateMountpoint bool `json:",omitempty"` - // ReadOnlyNonRecursive makes the mount non-recursively read-only, but still leaves the mount recursive - // (unless NonRecursive is set to true in conjunction). - ReadOnlyNonRecursive bool `json:",omitempty"` - // ReadOnlyForceRecursive raises an error if the mount cannot be made recursively read-only. - ReadOnlyForceRecursive bool `json:",omitempty"` -} - -// VolumeOptions represents the options for a mount of type volume. -type VolumeOptions struct { - NoCopy bool `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Subpath string `json:",omitempty"` - DriverConfig *Driver `json:",omitempty"` -} - -type ImageOptions struct { - Subpath string `json:",omitempty"` -} - -// Driver represents a volume driver. -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TmpfsOptions defines options specific to mounts of type "tmpfs". -type TmpfsOptions struct { - // Size sets the size of the tmpfs, in bytes. - // - // This will be converted to an operating system specific value - // depending on the host. For example, on linux, it will be converted to - // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with - // docker, uses a straight byte value. - // - // Percentages are not supported. - SizeBytes int64 `json:",omitempty"` - // Mode of the tmpfs upon creation - Mode os.FileMode `json:",omitempty"` - // Options to be passed to the tmpfs mount. An array of arrays. Flag - // options should be provided as 1-length arrays. Other types should be - // provided as 2-length arrays, where the first item is the key and the - // second the value. - Options [][]string `json:",omitempty"` - // TODO(stevvooe): There are several more tmpfs flags, specified in the - // daemon, that are accepted. Only the most basic are added for now. - // - // From https://github.com/moby/sys/blob/mount/v0.1.1/mount/flags.go#L47-L56 - // - // var validFlags = map[string]bool{ - // "": true, - // "size": true, X - // "mode": true, X - // "uid": true, - // "gid": true, - // "nr_inodes": true, - // "nr_blocks": true, - // "mpol": true, - // } - // - // Some of these may be straightforward to add, but others, such as - // uid/gid have implications in a clustered system. -} - -// ClusterOptions specifies options for a Cluster volume. -type ClusterOptions struct { - // intentionally empty -} diff --git a/vendor/github.com/docker/docker/api/types/network/create_response.go b/vendor/github.com/docker/docker/api/types/network/create_response.go deleted file mode 100644 index c32b35bff52..00000000000 --- a/vendor/github.com/docker/docker/api/types/network/create_response.go +++ /dev/null @@ -1,19 +0,0 @@ -package network - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// CreateResponse NetworkCreateResponse -// -// OK response to NetworkCreate operation -// swagger:model CreateResponse -type CreateResponse struct { - - // The ID of the created network. - // Required: true - ID string `json:"Id"` - - // Warnings encountered when creating the container - // Required: true - Warning string `json:"Warning"` -} diff --git a/vendor/github.com/docker/docker/api/types/network/endpoint.go b/vendor/github.com/docker/docker/api/types/network/endpoint.go deleted file mode 100644 index cdc06c6c900..00000000000 --- a/vendor/github.com/docker/docker/api/types/network/endpoint.go +++ /dev/null @@ -1,151 +0,0 @@ -package network - -import ( - "errors" - "fmt" - "net" -) - -// EndpointSettings stores the network endpoint details -type EndpointSettings struct { - // Configurations - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string // Aliases holds the list of extra, user-specified DNS names for this endpoint. - // MacAddress may be used to specify a MAC address when the container is created. - // Once the container is running, it becomes operational data (it may contain a - // generated address). - MacAddress string - DriverOpts map[string]string - - // GwPriority determines which endpoint will provide the default gateway - // for the container. The endpoint with the highest priority will be used. - // If multiple endpoints have the same priority, they are lexicographically - // sorted based on their network name, and the one that sorts first is picked. - GwPriority int - // Operational data - NetworkID string - EndpointID string - Gateway string - IPAddress string - IPPrefixLen int - IPv6Gateway string - GlobalIPv6Address string - GlobalIPv6PrefixLen int - // DNSNames holds all the (non fully qualified) DNS names associated to this endpoint. First entry is used to - // generate PTR records. - DNSNames []string -} - -// Copy makes a deep copy of `EndpointSettings` -func (es *EndpointSettings) Copy() *EndpointSettings { - epCopy := *es - if es.IPAMConfig != nil { - epCopy.IPAMConfig = es.IPAMConfig.Copy() - } - - if es.Links != nil { - links := make([]string, 0, len(es.Links)) - epCopy.Links = append(links, es.Links...) - } - - if es.Aliases != nil { - aliases := make([]string, 0, len(es.Aliases)) - epCopy.Aliases = append(aliases, es.Aliases...) - } - - if len(es.DNSNames) > 0 { - epCopy.DNSNames = make([]string, len(es.DNSNames)) - copy(epCopy.DNSNames, es.DNSNames) - } - - return &epCopy -} - -// EndpointIPAMConfig represents IPAM configurations for the endpoint -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` - LinkLocalIPs []string `json:",omitempty"` -} - -// Copy makes a copy of the endpoint ipam config -func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { - cfgCopy := *cfg - cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) - cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) - return &cfgCopy -} - -// NetworkSubnet describes a user-defined subnet for a specific network. It's only used to validate if an -// EndpointIPAMConfig is valid for a specific network. -type NetworkSubnet interface { - // Contains checks whether the NetworkSubnet contains [addr]. - Contains(addr net.IP) bool - // IsStatic checks whether the subnet was statically allocated (ie. user-defined). - IsStatic() bool -} - -// IsInRange checks whether static IP addresses are valid in a specific network. -func (cfg *EndpointIPAMConfig) IsInRange(v4Subnets []NetworkSubnet, v6Subnets []NetworkSubnet) error { - var errs []error - - if err := validateEndpointIPAddress(cfg.IPv4Address, v4Subnets); err != nil { - errs = append(errs, err) - } - if err := validateEndpointIPAddress(cfg.IPv6Address, v6Subnets); err != nil { - errs = append(errs, err) - } - - return errJoin(errs...) -} - -func validateEndpointIPAddress(epAddr string, ipamSubnets []NetworkSubnet) error { - if epAddr == "" { - return nil - } - - var staticSubnet bool - parsedAddr := net.ParseIP(epAddr) - for _, subnet := range ipamSubnets { - if subnet.IsStatic() { - staticSubnet = true - if subnet.Contains(parsedAddr) { - return nil - } - } - } - - if staticSubnet { - return fmt.Errorf("no configured subnet or ip-range contain the IP address %s", epAddr) - } - - return errors.New("user specified IP address is supported only when connecting to networks with user configured subnets") -} - -// Validate checks whether cfg is valid. -func (cfg *EndpointIPAMConfig) Validate() error { - if cfg == nil { - return nil - } - - var errs []error - - if cfg.IPv4Address != "" { - if addr := net.ParseIP(cfg.IPv4Address); addr == nil || addr.To4() == nil || addr.IsUnspecified() { - errs = append(errs, fmt.Errorf("invalid IPv4 address: %s", cfg.IPv4Address)) - } - } - if cfg.IPv6Address != "" { - if addr := net.ParseIP(cfg.IPv6Address); addr == nil || addr.To4() != nil || addr.IsUnspecified() { - errs = append(errs, fmt.Errorf("invalid IPv6 address: %s", cfg.IPv6Address)) - } - } - for _, addr := range cfg.LinkLocalIPs { - if parsed := net.ParseIP(addr); parsed == nil || parsed.IsUnspecified() { - errs = append(errs, fmt.Errorf("invalid link-local IP address: %s", addr)) - } - } - - return errJoin(errs...) -} diff --git a/vendor/github.com/docker/docker/api/types/network/ipam.go b/vendor/github.com/docker/docker/api/types/network/ipam.go deleted file mode 100644 index f9a9ff9b358..00000000000 --- a/vendor/github.com/docker/docker/api/types/network/ipam.go +++ /dev/null @@ -1,173 +0,0 @@ -package network - -import ( - "errors" - "fmt" - "net/netip" - "strings" -) - -// IPAM represents IP Address Management -type IPAM struct { - Driver string - Options map[string]string // Per network IPAM driver options - Config []IPAMConfig -} - -// IPAMConfig represents IPAM configurations -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -type ipFamily string - -const ( - ip4 ipFamily = "IPv4" - ip6 ipFamily = "IPv6" -) - -// ValidateIPAM checks whether the network's IPAM passed as argument is valid. It returns a joinError of the list of -// errors found. -func ValidateIPAM(ipam *IPAM, enableIPv6 bool) error { - if ipam == nil { - return nil - } - - var errs []error - for _, cfg := range ipam.Config { - subnet, err := netip.ParsePrefix(cfg.Subnet) - if err != nil { - errs = append(errs, fmt.Errorf("invalid subnet %s: invalid CIDR block notation", cfg.Subnet)) - continue - } - subnetFamily := ip4 - if subnet.Addr().Is6() { - subnetFamily = ip6 - } - - if !enableIPv6 && subnetFamily == ip6 { - continue - } - - if subnet != subnet.Masked() { - errs = append(errs, fmt.Errorf("invalid subnet %s: it should be %s", subnet, subnet.Masked())) - } - - if ipRangeErrs := validateIPRange(cfg.IPRange, subnet, subnetFamily); len(ipRangeErrs) > 0 { - errs = append(errs, ipRangeErrs...) - } - - if err := validateAddress(cfg.Gateway, subnet, subnetFamily); err != nil { - errs = append(errs, fmt.Errorf("invalid gateway %s: %w", cfg.Gateway, err)) - } - - for auxName, aux := range cfg.AuxAddress { - if err := validateAddress(aux, subnet, subnetFamily); err != nil { - errs = append(errs, fmt.Errorf("invalid auxiliary address %s: %w", auxName, err)) - } - } - } - - if err := errJoin(errs...); err != nil { - return fmt.Errorf("invalid network config:\n%w", err) - } - - return nil -} - -func validateIPRange(ipRange string, subnet netip.Prefix, subnetFamily ipFamily) []error { - if ipRange == "" { - return nil - } - prefix, err := netip.ParsePrefix(ipRange) - if err != nil { - return []error{fmt.Errorf("invalid ip-range %s: invalid CIDR block notation", ipRange)} - } - family := ip4 - if prefix.Addr().Is6() { - family = ip6 - } - - if family != subnetFamily { - return []error{fmt.Errorf("invalid ip-range %s: parent subnet is an %s block", ipRange, subnetFamily)} - } - - var errs []error - if prefix.Bits() < subnet.Bits() { - errs = append(errs, fmt.Errorf("invalid ip-range %s: CIDR block is bigger than its parent subnet %s", ipRange, subnet)) - } - if prefix != prefix.Masked() { - errs = append(errs, fmt.Errorf("invalid ip-range %s: it should be %s", prefix, prefix.Masked())) - } - if !subnet.Overlaps(prefix) { - errs = append(errs, fmt.Errorf("invalid ip-range %s: parent subnet %s doesn't contain ip-range", ipRange, subnet)) - } - - return errs -} - -func validateAddress(address string, subnet netip.Prefix, subnetFamily ipFamily) error { - if address == "" { - return nil - } - addr, err := netip.ParseAddr(address) - if err != nil { - return errors.New("invalid address") - } - family := ip4 - if addr.Is6() { - family = ip6 - } - - if family != subnetFamily { - return fmt.Errorf("parent subnet is an %s block", subnetFamily) - } - if !subnet.Contains(addr) { - return fmt.Errorf("parent subnet %s doesn't contain this address", subnet) - } - - return nil -} - -func errJoin(errs ...error) error { - n := 0 - for _, err := range errs { - if err != nil { - n++ - } - } - if n == 0 { - return nil - } - e := &joinError{ - errs: make([]error, 0, n), - } - for _, err := range errs { - if err != nil { - e.errs = append(e.errs, err) - } - } - return e -} - -type joinError struct { - errs []error -} - -func (e *joinError) Error() string { - if len(e.errs) == 1 { - return strings.TrimSpace(e.errs[0].Error()) - } - stringErrs := make([]string, 0, len(e.errs)) - for _, subErr := range e.errs { - stringErrs = append(stringErrs, strings.ReplaceAll(subErr.Error(), "\n", "\n\t")) - } - return "* " + strings.Join(stringErrs, "\n* ") -} - -func (e *joinError) Unwrap() []error { - return e.errs -} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go deleted file mode 100644 index 4a0cb479848..00000000000 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ /dev/null @@ -1,168 +0,0 @@ -package network - -import ( - "time" - - "github.com/docker/docker/api/types/filters" -) - -const ( - // NetworkDefault is a platform-independent alias to choose the platform-specific default network stack. - NetworkDefault = "default" - // NetworkHost is the name of the predefined network used when the NetworkMode host is selected (only available on Linux) - NetworkHost = "host" - // NetworkNone is the name of the predefined network used when the NetworkMode none is selected (available on both Linux and Windows) - NetworkNone = "none" - // NetworkBridge is the name of the default network on Linux - NetworkBridge = "bridge" - // NetworkNat is the name of the default network on Windows - NetworkNat = "nat" -) - -// CreateRequest is the request message sent to the server for network create call. -type CreateRequest struct { - CreateOptions - Name string // Name is the requested name of the network. - - // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client - // package to older daemons. - CheckDuplicate *bool `json:",omitempty"` -} - -// CreateOptions holds options to create a network. -type CreateOptions struct { - Driver string // Driver is the driver-name used to create the network (e.g. `bridge`, `overlay`) - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level). - EnableIPv4 *bool `json:",omitempty"` // EnableIPv4 represents whether to enable IPv4. - EnableIPv6 *bool `json:",omitempty"` // EnableIPv6 represents whether to enable IPv6. - IPAM *IPAM // IPAM is the network's IP Address Management. - Internal bool // Internal represents if the network is used internal only. - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigOnly bool // ConfigOnly creates a config-only network. Config-only networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - ConfigFrom *ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. The specified network must be a config-only network; see [CreateOptions.ConfigOnly]. - Options map[string]string // Options specifies the network-specific options to use for when creating the network. - Labels map[string]string // Labels holds metadata specific to the network being created. -} - -// ListOptions holds parameters to filter the list of networks with. -type ListOptions struct { - Filters filters.Args -} - -// InspectOptions holds parameters to inspect network. -type InspectOptions struct { - Scope string - Verbose bool -} - -// ConnectOptions represents the data to be used to connect a container to the -// network. -type ConnectOptions struct { - Container string - EndpointConfig *EndpointSettings `json:",omitempty"` -} - -// DisconnectOptions represents the data to be used to disconnect a container -// from the network. -type DisconnectOptions struct { - Container string - Force bool -} - -// Inspect is the body of the "get network" http response message. -type Inspect struct { - Name string // Name is the name of the network - ID string `json:"Id"` // ID uniquely identifies a network on a single machine - Created time.Time // Created is the time the network created - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) - Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) - EnableIPv4 bool // EnableIPv4 represents whether IPv4 is enabled - EnableIPv6 bool // EnableIPv6 represents whether IPv6 is enabled - IPAM IPAM // IPAM is the network's IP Address Management - Internal bool // Internal represents if the network is used internal only - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigFrom ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. - ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - Containers map[string]EndpointResource // Containers contains endpoints belonging to the network - Options map[string]string // Options holds the network specific options to use for when creating the network - Labels map[string]string // Labels holds metadata specific to the network being created - Peers []PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network - Services map[string]ServiceInfo `json:",omitempty"` -} - -// Summary is used as response when listing networks. It currently is an alias -// for [Inspect], but may diverge in the future, as not all information may -// be included when listing networks. -type Summary = Inspect - -// Address represents an IP address -type Address struct { - Addr string - PrefixLen int -} - -// PeerInfo represents one peer of an overlay network -type PeerInfo struct { - Name string - IP string -} - -// Task carries the information about one backend task -type Task struct { - Name string - EndpointID string - EndpointIP string - Info map[string]string -} - -// ServiceInfo represents service parameters with the list of service's tasks -type ServiceInfo struct { - VIP string - Ports []string - LocalLBIndex int - Tasks []Task -} - -// EndpointResource contains network resources allocated and used for a -// container in a network. -type EndpointResource struct { - Name string - EndpointID string - MacAddress string - IPv4Address string - IPv6Address string -} - -// NetworkingConfig represents the container's networking configuration for each of its interfaces -// Carries the networking configs specified in the `docker run` and `docker network connect` commands -type NetworkingConfig struct { - EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network -} - -// ConfigReference specifies the source which provides a network's configuration -type ConfigReference struct { - Network string -} - -var acceptedFilters = map[string]bool{ - "dangling": true, - "driver": true, - "id": true, - "label": true, - "name": true, - "scope": true, - "type": true, -} - -// ValidateFilters validates the list of filter args with the available filters. -func ValidateFilters(filter filters.Args) error { - return filter.Validate(acceptedFilters) -} - -// PruneReport contains the response for Engine API: -// POST "/networks/prune" -type PruneReport struct { - NetworksDeleted []string -} diff --git a/vendor/github.com/docker/docker/api/types/registry/authconfig.go b/vendor/github.com/docker/docker/api/types/registry/authconfig.go deleted file mode 100644 index 4c6d7ab2bad..00000000000 --- a/vendor/github.com/docker/docker/api/types/registry/authconfig.go +++ /dev/null @@ -1,112 +0,0 @@ -package registry - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "strings" -) - -// AuthHeader is the name of the header used to send encoded registry -// authorization credentials for registry operations (push/pull). -const AuthHeader = "X-Registry-Auth" - -// RequestAuthConfig is a function interface that clients can supply -// to retry operations after getting an authorization error. -// -// The function must return the [AuthHeader] value ([AuthConfig]), encoded -// in base64url format ([RFC4648, section 5]), which can be decoded by -// [DecodeAuthConfig]. -// -// It must return an error if the privilege request fails. -// -// [RFC4648, section 5]: https://tools.ietf.org/html/rfc4648#section-5 -type RequestAuthConfig func(context.Context) (string, error) - -// AuthConfig contains authorization information for connecting to a Registry. -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // - // Deprecated: This field is deprecated since docker 1.11 (API v1.23) and will be removed in the next release. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} - -// EncodeAuthConfig serializes the auth configuration as a base64url encoded -// ([RFC4648, section 5]) JSON string for sending through the X-Registry-Auth header. -// -// [RFC4648, section 5]: https://tools.ietf.org/html/rfc4648#section-5 -func EncodeAuthConfig(authConfig AuthConfig) (string, error) { - buf, err := json.Marshal(authConfig) - if err != nil { - return "", errInvalidParameter{err} - } - return base64.URLEncoding.EncodeToString(buf), nil -} - -// DecodeAuthConfig decodes base64url encoded ([RFC4648, section 5]) JSON -// authentication information as sent through the X-Registry-Auth header. -// -// This function always returns an [AuthConfig], even if an error occurs. It is up -// to the caller to decide if authentication is required, and if the error can -// be ignored. -// -// [RFC4648, section 5]: https://tools.ietf.org/html/rfc4648#section-5 -func DecodeAuthConfig(authEncoded string) (*AuthConfig, error) { - if authEncoded == "" { - return &AuthConfig{}, nil - } - - authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) - return decodeAuthConfigFromReader(authJSON) -} - -// DecodeAuthConfigBody decodes authentication information as sent as JSON in the -// body of a request. This function is to provide backward compatibility with old -// clients and API versions. Current clients and API versions expect authentication -// to be provided through the X-Registry-Auth header. -// -// Like [DecodeAuthConfig], this function always returns an [AuthConfig], even if an -// error occurs. It is up to the caller to decide if authentication is required, -// and if the error can be ignored. -// -// Deprecated: this function is no longer used and will be removed in the next release. -func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) { - return decodeAuthConfigFromReader(rdr) -} - -func decodeAuthConfigFromReader(rdr io.Reader) (*AuthConfig, error) { - authConfig := &AuthConfig{} - if err := json.NewDecoder(rdr).Decode(authConfig); err != nil { - // always return an (empty) AuthConfig to increase compatibility with - // the existing API. - return &AuthConfig{}, invalid(err) - } - return authConfig, nil -} - -func invalid(err error) error { - return errInvalidParameter{fmt.Errorf("invalid X-Registry-Auth header: %w", err)} -} - -type errInvalidParameter struct{ error } - -func (errInvalidParameter) InvalidParameter() {} - -func (e errInvalidParameter) Cause() error { return e.error } - -func (e errInvalidParameter) Unwrap() error { return e.error } diff --git a/vendor/github.com/docker/docker/api/types/registry/authenticate.go b/vendor/github.com/docker/docker/api/types/registry/authenticate.go deleted file mode 100644 index 42cac4430a6..00000000000 --- a/vendor/github.com/docker/docker/api/types/registry/authenticate.go +++ /dev/null @@ -1,21 +0,0 @@ -package registry - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// AuthenticateOKBody authenticate o k body -// swagger:model AuthenticateOKBody -type AuthenticateOKBody struct { - - // An opaque token used to authenticate a user after a successful login - // Required: true - IdentityToken string `json:"IdentityToken"` - - // The status of the authentication - // Required: true - Status string `json:"Status"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go deleted file mode 100644 index 9319c964cdb..00000000000 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ /dev/null @@ -1,122 +0,0 @@ -// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: -//go:build go1.23 - -package registry - -import ( - "encoding/json" - "net" - - ocispec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// ServiceConfig stores daemon registry services configuration. -type ServiceConfig struct { - AllowNondistributableArtifactsCIDRs []*NetIPNet `json:"AllowNondistributableArtifactsCIDRs,omitempty"` // Deprecated: non-distributable artifacts are deprecated and enabled by default. This field will be removed in the next release. - AllowNondistributableArtifactsHostnames []string `json:"AllowNondistributableArtifactsHostnames,omitempty"` // Deprecated: non-distributable artifacts are deprecated and enabled by default. This field will be removed in the next release. - - InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` - IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` - Mirrors []string - - // ExtraFields is for internal use to include deprecated fields on older API versions. - ExtraFields map[string]any `json:"-"` -} - -// MarshalJSON implements a custom marshaler to include legacy fields -// in API responses. -func (sc *ServiceConfig) MarshalJSON() ([]byte, error) { - type tmp ServiceConfig - base, err := json.Marshal((*tmp)(sc)) - if err != nil { - return nil, err - } - var merged map[string]any - _ = json.Unmarshal(base, &merged) - - for k, v := range sc.ExtraFields { - merged[k] = v - } - return json.Marshal(merged) -} - -// NetIPNet is the net.IPNet type, which can be marshalled and -// unmarshalled to JSON -type NetIPNet net.IPNet - -// String returns the CIDR notation of ipnet -func (ipnet *NetIPNet) String() string { - return (*net.IPNet)(ipnet).String() -} - -// MarshalJSON returns the JSON representation of the IPNet -func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(ipnet).String()) -} - -// UnmarshalJSON sets the IPNet from a byte array of JSON -func (ipnet *NetIPNet) UnmarshalJSON(b []byte) error { - var ipnetStr string - if err := json.Unmarshal(b, &ipnetStr); err != nil { - return err - } - _, cidr, err := net.ParseCIDR(ipnetStr) - if err != nil { - return err - } - *ipnet = NetIPNet(*cidr) - return nil -} - -// IndexInfo contains information about a registry -// -// RepositoryInfo Examples: -// -// { -// "Index" : { -// "Name" : "docker.io", -// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], -// "Secure" : true, -// "Official" : true, -// }, -// "RemoteName" : "library/debian", -// "LocalName" : "debian", -// "CanonicalName" : "docker.io/debian" -// "Official" : true, -// } -// -// { -// "Index" : { -// "Name" : "127.0.0.1:5000", -// "Mirrors" : [], -// "Secure" : false, -// "Official" : false, -// }, -// "RemoteName" : "user/repo", -// "LocalName" : "127.0.0.1:5000/user/repo", -// "CanonicalName" : "127.0.0.1:5000/user/repo", -// "Official" : false, -// } -type IndexInfo struct { - // Name is the name of the registry, such as "docker.io" - Name string - // Mirrors is a list of mirrors, expressed as URIs - Mirrors []string - // Secure is set to false if the registry is part of the list of - // insecure registries. Insecure registries accept HTTP and/or accept - // HTTPS with certificates from unknown CAs. - Secure bool - // Official indicates whether this is an official registry - Official bool -} - -// DistributionInspect describes the result obtained from contacting the -// registry to retrieve image metadata -type DistributionInspect struct { - // Descriptor contains information about the manifest, including - // the content addressable digest - Descriptor ocispec.Descriptor - // Platforms contains the list of platforms supported by the image, - // obtained by parsing the manifest - Platforms []ocispec.Platform -} diff --git a/vendor/github.com/docker/docker/api/types/registry/search.go b/vendor/github.com/docker/docker/api/types/registry/search.go deleted file mode 100644 index 994ca4c6f96..00000000000 --- a/vendor/github.com/docker/docker/api/types/registry/search.go +++ /dev/null @@ -1,48 +0,0 @@ -package registry - -import ( - "context" - - "github.com/docker/docker/api/types/filters" -) - -// SearchOptions holds parameters to search images with. -type SearchOptions struct { - RegistryAuth string - - // PrivilegeFunc is a function that clients can supply to retry operations - // after getting an authorization error. This function returns the registry - // authentication header value in base64 encoded format, or an error if the - // privilege request fails. - // - // For details, refer to [github.com/docker/docker/api/types/registry.RequestAuthConfig]. - PrivilegeFunc func(context.Context) (string, error) - Filters filters.Args - Limit int -} - -// SearchResult describes a search result returned from a registry -type SearchResult struct { - // StarCount indicates the number of stars this repository has - StarCount int `json:"star_count"` - // IsOfficial is true if the result is from an official repository. - IsOfficial bool `json:"is_official"` - // Name is the name of the repository - Name string `json:"name"` - // IsAutomated indicates whether the result is automated. - // - // Deprecated: the "is_automated" field is deprecated and will always be "false". - IsAutomated bool `json:"is_automated"` - // Description is a textual description of the repository - Description string `json:"description"` -} - -// SearchResults lists a collection search results returned from a registry -type SearchResults struct { - // Query contains the query string that generated the search results - Query string `json:"query"` - // NumResults indicates the number of results the query returned - NumResults int `json:"num_results"` - // Results is a slice containing the actual results for the search - Results []SearchResult `json:"results"` -} diff --git a/vendor/github.com/docker/docker/api/types/storage/driver_data.go b/vendor/github.com/docker/docker/api/types/storage/driver_data.go deleted file mode 100644 index 009e2130950..00000000000 --- a/vendor/github.com/docker/docker/api/types/storage/driver_data.go +++ /dev/null @@ -1,23 +0,0 @@ -package storage - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// DriverData Information about the storage driver used to store the container's and -// image's filesystem. -// -// swagger:model DriverData -type DriverData struct { - - // Low-level storage metadata, provided as key/value pairs. - // - // This information is driver-specific, and depends on the storage-driver - // in use, and should be used for informational purposes only. - // - // Required: true - Data map[string]string `json:"Data"` - - // Name of the storage driver. - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/strslice/strslice.go b/vendor/github.com/docker/docker/api/types/strslice/strslice.go deleted file mode 100644 index bad493fb89f..00000000000 --- a/vendor/github.com/docker/docker/api/types/strslice/strslice.go +++ /dev/null @@ -1,30 +0,0 @@ -package strslice - -import "encoding/json" - -// StrSlice represents a string or an array of strings. -// We need to override the json decoder to accept both options. -type StrSlice []string - -// UnmarshalJSON decodes the byte slice whether it's a string or an array of -// strings. This method is needed to implement json.Unmarshaler. -func (e *StrSlice) UnmarshalJSON(b []byte) error { - if len(b) == 0 { - // With no input, we preserve the existing value by returning nil and - // leaving the target alone. This allows defining default values for - // the type. - return nil - } - - p := make([]string, 0, 1) - if err := json.Unmarshal(b, &p); err != nil { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - p = append(p, s) - } - - *e = p - return nil -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/common.go b/vendor/github.com/docker/docker/api/types/swarm/common.go deleted file mode 100644 index b42812e03f1..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/common.go +++ /dev/null @@ -1,48 +0,0 @@ -package swarm - -import ( - "strconv" - "time" -) - -// Version represents the internal object version. -type Version struct { - Index uint64 `json:",omitempty"` -} - -// String implements fmt.Stringer interface. -func (v Version) String() string { - return strconv.FormatUint(v.Index, 10) -} - -// Meta is a base object inherited by most of the other once. -type Meta struct { - Version Version `json:",omitempty"` - CreatedAt time.Time `json:",omitempty"` - UpdatedAt time.Time `json:",omitempty"` -} - -// Annotations represents how to describe an object. -type Annotations struct { - Name string `json:",omitempty"` - Labels map[string]string `json:"Labels"` -} - -// Driver represents a driver (network, logging, secrets backend). -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TLSInfo represents the TLS information about what CA certificate is trusted, -// and who the issuer for a TLS certificate is -type TLSInfo struct { - // TrustRoot is the trusted CA root certificate in PEM format - TrustRoot string `json:",omitempty"` - - // CertIssuer is the raw subject bytes of the issuer - CertIssuerSubject []byte `json:",omitempty"` - - // CertIssuerPublicKey is the raw public key bytes of the issuer - CertIssuerPublicKey []byte `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/config.go b/vendor/github.com/docker/docker/api/types/swarm/config.go deleted file mode 100644 index 80a6ffdb9aa..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/config.go +++ /dev/null @@ -1,62 +0,0 @@ -package swarm - -import ( - "os" - - "github.com/docker/docker/api/types/filters" -) - -// Config represents a config. -type Config struct { - ID string - Meta - Spec ConfigSpec -} - -// ConfigSpec represents a config specification from a config in swarm -type ConfigSpec struct { - Annotations - - // Data is the data to store as a config. - // - // The maximum allowed size is 1000KB, as defined in [MaxConfigSize]. - // - // [MaxConfigSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/manager/controlapi#MaxConfigSize - Data []byte `json:",omitempty"` - - // Templating controls whether and how to evaluate the config payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// ConfigReferenceFileTarget is a file target in a config reference -type ConfigReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// ConfigReferenceRuntimeTarget is a target for a config specifying that it -// isn't mounted into the container but instead has some other purpose. -type ConfigReferenceRuntimeTarget struct{} - -// ConfigReference is a reference to a config in swarm -type ConfigReference struct { - File *ConfigReferenceFileTarget `json:",omitempty"` - Runtime *ConfigReferenceRuntimeTarget `json:",omitempty"` - ConfigID string - ConfigName string -} - -// ConfigCreateResponse contains the information returned to a client -// on the creation of a new config. -type ConfigCreateResponse struct { - // ID is the id of the created config. - ID string -} - -// ConfigListOptions holds parameters to list configs -type ConfigListOptions struct { - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go deleted file mode 100644 index f9416bacca6..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ /dev/null @@ -1,119 +0,0 @@ -package swarm - -import ( - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" -) - -// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) -// Detailed documentation is available in: -// http://man7.org/linux/man-pages/man5/resolv.conf.5.html -// `nameserver`, `search`, `options` have been supported. -// TODO: `domain` is not supported yet. -type DNSConfig struct { - // Nameservers specifies the IP addresses of the name servers - Nameservers []string `json:",omitempty"` - // Search specifies the search list for host-name lookup - Search []string `json:",omitempty"` - // Options allows certain internal resolver variables to be modified - Options []string `json:",omitempty"` -} - -// SELinuxContext contains the SELinux labels of the container. -type SELinuxContext struct { - Disable bool - - User string - Role string - Type string - Level string -} - -// SeccompMode is the type used for the enumeration of possible seccomp modes -// in SeccompOpts -type SeccompMode string - -const ( - SeccompModeDefault SeccompMode = "default" - SeccompModeUnconfined SeccompMode = "unconfined" - SeccompModeCustom SeccompMode = "custom" -) - -// SeccompOpts defines the options for configuring seccomp on a swarm-managed -// container. -type SeccompOpts struct { - // Mode is the SeccompMode used for the container. - Mode SeccompMode `json:",omitempty"` - // Profile is the custom seccomp profile as a json object to be used with - // the container. Mode should be set to SeccompModeCustom when using a - // custom profile in this manner. - Profile []byte `json:",omitempty"` -} - -// AppArmorMode is type used for the enumeration of possible AppArmor modes in -// AppArmorOpts -type AppArmorMode string - -const ( - AppArmorModeDefault AppArmorMode = "default" - AppArmorModeDisabled AppArmorMode = "disabled" -) - -// AppArmorOpts defines the options for configuring AppArmor on a swarm-managed -// container. Currently, custom AppArmor profiles are not supported. -type AppArmorOpts struct { - Mode AppArmorMode `json:",omitempty"` -} - -// CredentialSpec for managed service account (Windows only) -type CredentialSpec struct { - Config string - File string - Registry string -} - -// Privileges defines the security options for the container. -type Privileges struct { - CredentialSpec *CredentialSpec - SELinuxContext *SELinuxContext - Seccomp *SeccompOpts `json:",omitempty"` - AppArmor *AppArmorOpts `json:",omitempty"` - NoNewPrivileges bool -} - -// ContainerSpec represents the spec of a container. -type ContainerSpec struct { - Image string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Command []string `json:",omitempty"` - Args []string `json:",omitempty"` - Hostname string `json:",omitempty"` - Env []string `json:",omitempty"` - Dir string `json:",omitempty"` - User string `json:",omitempty"` - Groups []string `json:",omitempty"` - Privileges *Privileges `json:",omitempty"` - Init *bool `json:",omitempty"` - StopSignal string `json:",omitempty"` - TTY bool `json:",omitempty"` - OpenStdin bool `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Mounts []mount.Mount `json:",omitempty"` - StopGracePeriod *time.Duration `json:",omitempty"` - Healthcheck *container.HealthConfig `json:",omitempty"` - // The format of extra hosts on swarmkit is specified in: - // http://man7.org/linux/man-pages/man5/hosts.5.html - // IP_address canonical_hostname [aliases...] - Hosts []string `json:",omitempty"` - DNSConfig *DNSConfig `json:",omitempty"` - Secrets []*SecretReference `json:",omitempty"` - Configs []*ConfigReference `json:",omitempty"` - Isolation container.Isolation `json:",omitempty"` - Sysctls map[string]string `json:",omitempty"` - CapabilityAdd []string `json:",omitempty"` - CapabilityDrop []string `json:",omitempty"` - Ulimits []*container.Ulimit `json:",omitempty"` - OomScoreAdj int64 `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/network.go b/vendor/github.com/docker/docker/api/types/swarm/network.go deleted file mode 100644 index 4b880723399..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/network.go +++ /dev/null @@ -1,121 +0,0 @@ -package swarm - -import ( - "github.com/docker/docker/api/types/network" -) - -// Endpoint represents an endpoint. -type Endpoint struct { - Spec EndpointSpec `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` - VirtualIPs []EndpointVirtualIP `json:",omitempty"` -} - -// EndpointSpec represents the spec of an endpoint. -type EndpointSpec struct { - Mode ResolutionMode `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` -} - -// ResolutionMode represents a resolution mode. -type ResolutionMode string - -const ( - // ResolutionModeVIP VIP - ResolutionModeVIP ResolutionMode = "vip" - // ResolutionModeDNSRR DNSRR - ResolutionModeDNSRR ResolutionMode = "dnsrr" -) - -// PortConfig represents the config of a port. -type PortConfig struct { - Name string `json:",omitempty"` - Protocol PortConfigProtocol `json:",omitempty"` - // TargetPort is the port inside the container - TargetPort uint32 `json:",omitempty"` - // PublishedPort is the port on the swarm hosts - PublishedPort uint32 `json:",omitempty"` - // PublishMode is the mode in which port is published - PublishMode PortConfigPublishMode `json:",omitempty"` -} - -// PortConfigPublishMode represents the mode in which the port is to -// be published. -type PortConfigPublishMode string - -const ( - // PortConfigPublishModeIngress is used for ports published - // for ingress load balancing using routing mesh. - PortConfigPublishModeIngress PortConfigPublishMode = "ingress" - // PortConfigPublishModeHost is used for ports published - // for direct host level access on the host where the task is running. - PortConfigPublishModeHost PortConfigPublishMode = "host" -) - -// PortConfigProtocol represents the protocol of a port. -type PortConfigProtocol string - -const ( - // TODO(stevvooe): These should be used generally, not just for PortConfig. - - // PortConfigProtocolTCP TCP - PortConfigProtocolTCP PortConfigProtocol = "tcp" - // PortConfigProtocolUDP UDP - PortConfigProtocolUDP PortConfigProtocol = "udp" - // PortConfigProtocolSCTP SCTP - PortConfigProtocolSCTP PortConfigProtocol = "sctp" -) - -// EndpointVirtualIP represents the virtual ip of a port. -type EndpointVirtualIP struct { - NetworkID string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Network represents a network. -type Network struct { - ID string - Meta - Spec NetworkSpec `json:",omitempty"` - DriverState Driver `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` -} - -// NetworkSpec represents the spec of a network. -type NetworkSpec struct { - Annotations - DriverConfiguration *Driver `json:",omitempty"` - IPv6Enabled bool `json:",omitempty"` - Internal bool `json:",omitempty"` - Attachable bool `json:",omitempty"` - Ingress bool `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` - ConfigFrom *network.ConfigReference `json:",omitempty"` - Scope string `json:",omitempty"` -} - -// NetworkAttachmentConfig represents the configuration of a network attachment. -type NetworkAttachmentConfig struct { - Target string `json:",omitempty"` - Aliases []string `json:",omitempty"` - DriverOpts map[string]string `json:",omitempty"` -} - -// NetworkAttachment represents a network attachment. -type NetworkAttachment struct { - Network Network `json:",omitempty"` - Addresses []string `json:",omitempty"` -} - -// IPAMOptions represents ipam options. -type IPAMOptions struct { - Driver Driver `json:",omitempty"` - Configs []IPAMConfig `json:",omitempty"` -} - -// IPAMConfig represents ipam configuration. -type IPAMConfig struct { - Subnet string `json:",omitempty"` - Range string `json:",omitempty"` - Gateway string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/node.go b/vendor/github.com/docker/docker/api/types/swarm/node.go deleted file mode 100644 index 2018a031bbf..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/node.go +++ /dev/null @@ -1,151 +0,0 @@ -package swarm - -import "github.com/docker/docker/api/types/filters" - -// Node represents a node. -type Node struct { - ID string - Meta - // Spec defines the desired state of the node as specified by the user. - // The system will honor this and will *never* modify it. - Spec NodeSpec `json:",omitempty"` - // Description encapsulates the properties of the Node as reported by the - // agent. - Description NodeDescription `json:",omitempty"` - // Status provides the current status of the node, as seen by the manager. - Status NodeStatus `json:",omitempty"` - // ManagerStatus provides the current status of the node's manager - // component, if the node is a manager. - ManagerStatus *ManagerStatus `json:",omitempty"` -} - -// NodeSpec represents the spec of a node. -type NodeSpec struct { - Annotations - Role NodeRole `json:",omitempty"` - Availability NodeAvailability `json:",omitempty"` -} - -// NodeRole represents the role of a node. -type NodeRole string - -const ( - // NodeRoleWorker WORKER - NodeRoleWorker NodeRole = "worker" - // NodeRoleManager MANAGER - NodeRoleManager NodeRole = "manager" -) - -// NodeAvailability represents the availability of a node. -type NodeAvailability string - -const ( - // NodeAvailabilityActive ACTIVE - NodeAvailabilityActive NodeAvailability = "active" - // NodeAvailabilityPause PAUSE - NodeAvailabilityPause NodeAvailability = "pause" - // NodeAvailabilityDrain DRAIN - NodeAvailabilityDrain NodeAvailability = "drain" -) - -// NodeDescription represents the description of a node. -type NodeDescription struct { - Hostname string `json:",omitempty"` - Platform Platform `json:",omitempty"` - Resources Resources `json:",omitempty"` - Engine EngineDescription `json:",omitempty"` - TLSInfo TLSInfo `json:",omitempty"` - CSIInfo []NodeCSIInfo `json:",omitempty"` -} - -// Platform represents the platform (Arch/OS). -type Platform struct { - Architecture string `json:",omitempty"` - OS string `json:",omitempty"` -} - -// EngineDescription represents the description of an engine. -type EngineDescription struct { - EngineVersion string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Plugins []PluginDescription `json:",omitempty"` -} - -// NodeCSIInfo represents information about a CSI plugin available on the node -type NodeCSIInfo struct { - // PluginName is the name of the CSI plugin. - PluginName string `json:",omitempty"` - // NodeID is the ID of the node as reported by the CSI plugin. This is - // different from the swarm node ID. - NodeID string `json:",omitempty"` - // MaxVolumesPerNode is the maximum number of volumes that may be published - // to this node - MaxVolumesPerNode int64 `json:",omitempty"` - // AccessibleTopology indicates the location of this node in the CSI - // plugin's topology - AccessibleTopology *Topology `json:",omitempty"` -} - -// PluginDescription represents the description of an engine plugin. -type PluginDescription struct { - Type string `json:",omitempty"` - Name string `json:",omitempty"` -} - -// NodeStatus represents the status of a node. -type NodeStatus struct { - State NodeState `json:",omitempty"` - Message string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Reachability represents the reachability of a node. -type Reachability string - -const ( - // ReachabilityUnknown UNKNOWN - ReachabilityUnknown Reachability = "unknown" - // ReachabilityUnreachable UNREACHABLE - ReachabilityUnreachable Reachability = "unreachable" - // ReachabilityReachable REACHABLE - ReachabilityReachable Reachability = "reachable" -) - -// ManagerStatus represents the status of a manager. -type ManagerStatus struct { - Leader bool `json:",omitempty"` - Reachability Reachability `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// NodeState represents the state of a node. -type NodeState string - -const ( - // NodeStateUnknown UNKNOWN - NodeStateUnknown NodeState = "unknown" - // NodeStateDown DOWN - NodeStateDown NodeState = "down" - // NodeStateReady READY - NodeStateReady NodeState = "ready" - // NodeStateDisconnected DISCONNECTED - NodeStateDisconnected NodeState = "disconnected" -) - -// Topology defines the CSI topology of this node. This type is a duplicate of -// github.com/docker/docker/api/types.Topology. Because the type definition -// is so simple and to avoid complicated structure or circular imports, we just -// duplicate it here. See that type for full documentation -type Topology struct { - Segments map[string]string `json:",omitempty"` -} - -// NodeListOptions holds parameters to list nodes with. -type NodeListOptions struct { - Filters filters.Args -} - -// NodeRemoveOptions holds parameters to remove nodes with. -type NodeRemoveOptions struct { - Force bool -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime.go deleted file mode 100644 index 3fda4ca65d1..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime.go +++ /dev/null @@ -1,37 +0,0 @@ -package swarm - -import "github.com/docker/docker/api/types/swarm/runtime" - -// RuntimeType is the type of runtime used for the TaskSpec -type RuntimeType string - -// RuntimeURL is the proto type url -type RuntimeURL string - -const ( - // RuntimeContainer is the container based runtime - RuntimeContainer RuntimeType = "container" - // RuntimePlugin is the plugin based runtime - RuntimePlugin RuntimeType = "plugin" - // RuntimeNetworkAttachment is the network attachment runtime - RuntimeNetworkAttachment RuntimeType = "attachment" - - // RuntimeURLContainer is the proto url for the container type - RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" - // RuntimeURLPlugin is the proto url for the plugin type - RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" -) - -// NetworkAttachmentSpec represents the runtime spec type for network -// attachment tasks -type NetworkAttachmentSpec struct { - ContainerID string -} - -// RuntimeSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -type RuntimeSpec = runtime.PluginSpec - -// RuntimePrivilege describes a permission the user has to accept -// upon installing a plugin. -type RuntimePrivilege = runtime.PluginPrivilege diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/runtime.go deleted file mode 100644 index 95176b26818..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/runtime.go +++ /dev/null @@ -1,27 +0,0 @@ -package runtime - -import "fmt" - -// PluginSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -type PluginSpec struct { - Name string `json:"name,omitempty"` - Remote string `json:"remote,omitempty"` - Privileges []*PluginPrivilege `json:"privileges,omitempty"` - Disabled bool `json:"disabled,omitempty"` - Env []string `json:"env,omitempty"` -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Value []string `json:"value,omitempty"` -} - -var ( - ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") // Deprecated: this error was only used internally and is no longer used. - ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") // Deprecated: this error was only used internally and is no longer used. - ErrUnexpectedEndOfGroupPlugin = fmt.Errorf("proto: unexpected end of group") // Deprecated: this error was only used internally and is no longer used. -) diff --git a/vendor/github.com/docker/docker/api/types/swarm/secret.go b/vendor/github.com/docker/docker/api/types/swarm/secret.go deleted file mode 100644 index d9482ab56d1..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/secret.go +++ /dev/null @@ -1,66 +0,0 @@ -package swarm - -import ( - "os" - - "github.com/docker/docker/api/types/filters" -) - -// Secret represents a secret. -type Secret struct { - ID string - Meta - Spec SecretSpec -} - -// SecretSpec represents a secret specification from a secret in swarm -type SecretSpec struct { - Annotations - - // Data is the data to store as a secret. It must be empty if a - // [Driver] is used, in which case the data is loaded from an external - // secret store. The maximum allowed size is 500KB, as defined in - // [MaxSecretSize]. - // - // This field is only used to create the secret, and is not returned - // by other endpoints. - // - // [MaxSecretSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/api/validation#MaxSecretSize - Data []byte `json:",omitempty"` - - // Driver is the name of the secrets driver used to fetch the secret's - // value from an external secret store. If not set, the default built-in - // store is used. - Driver *Driver `json:",omitempty"` - - // Templating controls whether and how to evaluate the secret payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// SecretReferenceFileTarget is a file target in a secret reference -type SecretReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// SecretReference is a reference to a secret in swarm -type SecretReference struct { - File *SecretReferenceFileTarget - SecretID string - SecretName string -} - -// SecretCreateResponse contains the information returned to a client -// on the creation of a new secret. -type SecretCreateResponse struct { - // ID is the id of the created secret. - ID string -} - -// SecretListOptions holds parameters to list secrets -type SecretListOptions struct { - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go deleted file mode 100644 index 56c660c1f0c..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ /dev/null @@ -1,272 +0,0 @@ -package swarm - -import ( - "time" - - "github.com/docker/docker/api/types/filters" -) - -// Service represents a service. -type Service struct { - ID string - Meta - Spec ServiceSpec `json:",omitempty"` - PreviousSpec *ServiceSpec `json:",omitempty"` - Endpoint Endpoint `json:",omitempty"` - UpdateStatus *UpdateStatus `json:",omitempty"` - - // ServiceStatus is an optional, extra field indicating the number of - // desired and running tasks. It is provided primarily as a shortcut to - // calculating these values client-side, which otherwise would require - // listing all tasks for a service, an operation that could be - // computation and network expensive. - ServiceStatus *ServiceStatus `json:",omitempty"` - - // JobStatus is the status of a Service which is in one of ReplicatedJob or - // GlobalJob modes. It is absent on Replicated and Global services. - JobStatus *JobStatus `json:",omitempty"` -} - -// ServiceSpec represents the spec of a service. -type ServiceSpec struct { - Annotations - - // TaskTemplate defines how the service should construct new tasks when - // orchestrating this service. - TaskTemplate TaskSpec `json:",omitempty"` - Mode ServiceMode `json:",omitempty"` - UpdateConfig *UpdateConfig `json:",omitempty"` - RollbackConfig *UpdateConfig `json:",omitempty"` - - // Networks specifies which networks the service should attach to. - // - // Deprecated: This field is deprecated since v1.44. The Networks field in TaskSpec should be used instead. - Networks []NetworkAttachmentConfig `json:",omitempty"` - EndpointSpec *EndpointSpec `json:",omitempty"` -} - -// ServiceMode represents the mode of a service. -type ServiceMode struct { - Replicated *ReplicatedService `json:",omitempty"` - Global *GlobalService `json:",omitempty"` - ReplicatedJob *ReplicatedJob `json:",omitempty"` - GlobalJob *GlobalJob `json:",omitempty"` -} - -// UpdateState is the state of a service update. -type UpdateState string - -const ( - // UpdateStateUpdating is the updating state. - UpdateStateUpdating UpdateState = "updating" - // UpdateStatePaused is the paused state. - UpdateStatePaused UpdateState = "paused" - // UpdateStateCompleted is the completed state. - UpdateStateCompleted UpdateState = "completed" - // UpdateStateRollbackStarted is the state with a rollback in progress. - UpdateStateRollbackStarted UpdateState = "rollback_started" - // UpdateStateRollbackPaused is the state with a rollback in progress. - UpdateStateRollbackPaused UpdateState = "rollback_paused" - // UpdateStateRollbackCompleted is the state with a rollback in progress. - UpdateStateRollbackCompleted UpdateState = "rollback_completed" -) - -// UpdateStatus reports the status of a service update. -type UpdateStatus struct { - State UpdateState `json:",omitempty"` - StartedAt *time.Time `json:",omitempty"` - CompletedAt *time.Time `json:",omitempty"` - Message string `json:",omitempty"` -} - -// ReplicatedService is a kind of ServiceMode. -type ReplicatedService struct { - Replicas *uint64 `json:",omitempty"` -} - -// GlobalService is a kind of ServiceMode. -type GlobalService struct{} - -// ReplicatedJob is the a type of Service which executes a defined Tasks -// in parallel until the specified number of Tasks have succeeded. -type ReplicatedJob struct { - // MaxConcurrent indicates the maximum number of Tasks that should be - // executing simultaneously for this job at any given time. There may be - // fewer Tasks that MaxConcurrent executing simultaneously; for example, if - // there are fewer than MaxConcurrent tasks needed to reach - // TotalCompletions. - // - // If this field is empty, it will default to a max concurrency of 1. - MaxConcurrent *uint64 `json:",omitempty"` - - // TotalCompletions is the total number of Tasks desired to run to - // completion. - // - // If this field is empty, the value of MaxConcurrent will be used. - TotalCompletions *uint64 `json:",omitempty"` -} - -// GlobalJob is the type of a Service which executes a Task on every Node -// matching the Service's placement constraints. These tasks run to completion -// and then exit. -// -// This type is deliberately empty. -type GlobalJob struct{} - -const ( - // UpdateFailureActionPause PAUSE - UpdateFailureActionPause = "pause" - // UpdateFailureActionContinue CONTINUE - UpdateFailureActionContinue = "continue" - // UpdateFailureActionRollback ROLLBACK - UpdateFailureActionRollback = "rollback" - - // UpdateOrderStopFirst STOP_FIRST - UpdateOrderStopFirst = "stop-first" - // UpdateOrderStartFirst START_FIRST - UpdateOrderStartFirst = "start-first" -) - -// UpdateConfig represents the update configuration. -type UpdateConfig struct { - // Maximum number of tasks to be updated in one iteration. - // 0 means unlimited parallelism. - Parallelism uint64 - - // Amount of time between updates. - Delay time.Duration `json:",omitempty"` - - // FailureAction is the action to take when an update failures. - FailureAction string `json:",omitempty"` - - // Monitor indicates how long to monitor a task for failure after it is - // created. If the task fails by ending up in one of the states - // REJECTED, COMPLETED, or FAILED, within Monitor from its creation, - // this counts as a failure. If it fails after Monitor, it does not - // count as a failure. If Monitor is unspecified, a default value will - // be used. - Monitor time.Duration `json:",omitempty"` - - // MaxFailureRatio is the fraction of tasks that may fail during - // an update before the failure action is invoked. Any task created by - // the current update which ends up in one of the states REJECTED, - // COMPLETED or FAILED within Monitor from its creation counts as a - // failure. The number of failures is divided by the number of tasks - // being updated, and if this fraction is greater than - // MaxFailureRatio, the failure action is invoked. - // - // If the failure action is CONTINUE, there is no effect. - // If the failure action is PAUSE, no more tasks will be updated until - // another update is started. - MaxFailureRatio float32 - - // Order indicates the order of operations when rolling out an updated - // task. Either the old task is shut down before the new task is - // started, or the new task is started before the old task is shut down. - Order string -} - -// ServiceStatus represents the number of running tasks in a service and the -// number of tasks desired to be running. -type ServiceStatus struct { - // RunningTasks is the number of tasks for the service actually in the - // Running state - RunningTasks uint64 - - // DesiredTasks is the number of tasks desired to be running by the - // service. For replicated services, this is the replica count. For global - // services, this is computed by taking the number of tasks with desired - // state of not-Shutdown. - DesiredTasks uint64 - - // CompletedTasks is the number of tasks in the state Completed, if this - // service is in ReplicatedJob or GlobalJob mode. This field must be - // cross-referenced with the service type, because the default value of 0 - // may mean that a service is not in a job mode, or it may mean that the - // job has yet to complete any tasks. - CompletedTasks uint64 -} - -// JobStatus is the status of a job-type service. -type JobStatus struct { - // JobIteration is a value increased each time a Job is executed, - // successfully or otherwise. "Executed", in this case, means the job as a - // whole has been started, not that an individual Task has been launched. A - // job is "Executed" when its ServiceSpec is updated. JobIteration can be - // used to disambiguate Tasks belonging to different executions of a job. - // - // Though JobIteration will increase with each subsequent execution, it may - // not necessarily increase by 1, and so JobIteration should not be used to - // keep track of the number of times a job has been executed. - JobIteration Version - - // LastExecution is the time that the job was last executed, as observed by - // Swarm manager. - LastExecution time.Time `json:",omitempty"` -} - -// ServiceCreateOptions contains the options to use when creating a service. -type ServiceCreateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// Values for RegistryAuthFrom in ServiceUpdateOptions -const ( - RegistryAuthFromSpec = "spec" - RegistryAuthFromPreviousSpec = "previous-spec" -) - -// ServiceUpdateOptions contains the options to be used for updating services. -type ServiceUpdateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // TODO(stevvooe): Consider moving the version parameter of ServiceUpdate - // into this field. While it does open API users up to racy writes, most - // users may not need that level of consistency in practice. - - // RegistryAuthFrom specifies where to find the registry authorization - // credentials if they are not given in EncodedRegistryAuth. Valid - // values are "spec" and "previous-spec". - RegistryAuthFrom string - - // Rollback indicates whether a server-side rollback should be - // performed. When this is set, the provided spec will be ignored. - // The valid values are "previous" and "none". An empty value is the - // same as "none". - Rollback string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// ServiceListOptions holds parameters to list services with. -type ServiceListOptions struct { - Filters filters.Args - - // Status indicates whether the server should include the service task - // count of running and desired tasks. - Status bool -} - -// ServiceInspectOptions holds parameters related to the "service inspect" -// operation. -type ServiceInspectOptions struct { - InsertDefaults bool -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go deleted file mode 100644 index 9a268ff1b93..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service_create_response.go +++ /dev/null @@ -1,20 +0,0 @@ -package swarm - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ServiceCreateResponse contains the information returned to a client on the -// creation of a new service. -// -// swagger:model ServiceCreateResponse -type ServiceCreateResponse struct { - - // The ID of the created service. - ID string `json:"ID,omitempty"` - - // Optional warning message. - // - // FIXME(thaJeztah): this should have "omitempty" in the generated type. - // - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go b/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go deleted file mode 100644 index 0417467dae3..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service_update_response.go +++ /dev/null @@ -1,12 +0,0 @@ -package swarm - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ServiceUpdateResponse service update response -// swagger:model ServiceUpdateResponse -type ServiceUpdateResponse struct { - - // Optional warning messages - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/swarm.go b/vendor/github.com/docker/docker/api/types/swarm/swarm.go deleted file mode 100644 index 38f3e6666d1..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/swarm.go +++ /dev/null @@ -1,244 +0,0 @@ -package swarm - -import ( - "time" -) - -// ClusterInfo represents info about the cluster for outputting in "info" -// it contains the same information as "Swarm", but without the JoinTokens -type ClusterInfo struct { - ID string - Meta - Spec Spec - TLSInfo TLSInfo - RootRotationInProgress bool - DefaultAddrPool []string - SubnetSize uint32 - DataPathPort uint32 -} - -// Swarm represents a swarm. -type Swarm struct { - ClusterInfo - JoinTokens JoinTokens -} - -// JoinTokens contains the tokens workers and managers need to join the swarm. -type JoinTokens struct { - // Worker is the join token workers may use to join the swarm. - Worker string - // Manager is the join token managers may use to join the swarm. - Manager string -} - -// Spec represents the spec of a swarm. -type Spec struct { - Annotations - - Orchestration OrchestrationConfig `json:",omitempty"` - Raft RaftConfig `json:",omitempty"` - Dispatcher DispatcherConfig `json:",omitempty"` - CAConfig CAConfig `json:",omitempty"` - TaskDefaults TaskDefaults `json:",omitempty"` - EncryptionConfig EncryptionConfig `json:",omitempty"` -} - -// OrchestrationConfig represents orchestration configuration. -type OrchestrationConfig struct { - // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or - // node. If negative, never remove completed or failed tasks. - TaskHistoryRetentionLimit *int64 `json:",omitempty"` -} - -// TaskDefaults parameterizes cluster-level task creation with default values. -type TaskDefaults struct { - // LogDriver selects the log driver to use for tasks created in the - // orchestrator if unspecified by a service. - // - // Updating this value will only have an affect on new tasks. Old tasks - // will continue use their previously configured log driver until - // recreated. - LogDriver *Driver `json:",omitempty"` -} - -// EncryptionConfig controls at-rest encryption of data and keys. -type EncryptionConfig struct { - // AutoLockManagers specifies whether or not managers TLS keys and raft data - // should be encrypted at rest in such a way that they must be unlocked - // before the manager node starts up again. - AutoLockManagers bool -} - -// RaftConfig represents raft configuration. -type RaftConfig struct { - // SnapshotInterval is the number of log entries between snapshots. - SnapshotInterval uint64 `json:",omitempty"` - - // KeepOldSnapshots is the number of snapshots to keep beyond the - // current snapshot. - KeepOldSnapshots *uint64 `json:",omitempty"` - - // LogEntriesForSlowFollowers is the number of log entries to keep - // around to sync up slow followers after a snapshot is created. - LogEntriesForSlowFollowers uint64 `json:",omitempty"` - - // ElectionTick is the number of ticks that a follower will wait for a message - // from the leader before becoming a candidate and starting an election. - // ElectionTick must be greater than HeartbeatTick. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - ElectionTick int - - // HeartbeatTick is the number of ticks between heartbeats. Every - // HeartbeatTick ticks, the leader will send a heartbeat to the - // followers. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - HeartbeatTick int -} - -// DispatcherConfig represents dispatcher configuration. -type DispatcherConfig struct { - // HeartbeatPeriod defines how often agent should send heartbeats to - // dispatcher. - HeartbeatPeriod time.Duration `json:",omitempty"` -} - -// CAConfig represents CA configuration. -type CAConfig struct { - // NodeCertExpiry is the duration certificates should be issued for - NodeCertExpiry time.Duration `json:",omitempty"` - - // ExternalCAs is a list of CAs to which a manager node will make - // certificate signing requests for node certificates. - ExternalCAs []*ExternalCA `json:",omitempty"` - - // SigningCACert and SigningCAKey specify the desired signing root CA and - // root CA key for the swarm. When inspecting the cluster, the key will - // be redacted. - SigningCACert string `json:",omitempty"` - SigningCAKey string `json:",omitempty"` - - // If this value changes, and there is no specified signing cert and key, - // then the swarm is forced to generate a new root certificate and key. - ForceRotate uint64 `json:",omitempty"` -} - -// ExternalCAProtocol represents type of external CA. -type ExternalCAProtocol string - -// ExternalCAProtocolCFSSL CFSSL -const ExternalCAProtocolCFSSL ExternalCAProtocol = "cfssl" - -// ExternalCA defines external CA to be used by the cluster. -type ExternalCA struct { - // Protocol is the protocol used by this external CA. - Protocol ExternalCAProtocol - - // URL is the URL where the external CA can be reached. - URL string - - // Options is a set of additional key/value pairs whose interpretation - // depends on the specified CA type. - Options map[string]string `json:",omitempty"` - - // CACert specifies which root CA is used by this external CA. This certificate must - // be in PEM format. - CACert string -} - -// InitRequest is the request used to init a swarm. -type InitRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - DataPathPort uint32 - ForceNewCluster bool - Spec Spec - AutoLockManagers bool - Availability NodeAvailability - DefaultAddrPool []string - SubnetSize uint32 -} - -// JoinRequest is the request used to join a swarm. -type JoinRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - RemoteAddrs []string - JoinToken string // accept by secret - Availability NodeAvailability -} - -// UnlockRequest is the request used to unlock a swarm. -type UnlockRequest struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// LocalNodeState represents the state of the local node. -type LocalNodeState string - -const ( - // LocalNodeStateInactive INACTIVE - LocalNodeStateInactive LocalNodeState = "inactive" - // LocalNodeStatePending PENDING - LocalNodeStatePending LocalNodeState = "pending" - // LocalNodeStateActive ACTIVE - LocalNodeStateActive LocalNodeState = "active" - // LocalNodeStateError ERROR - LocalNodeStateError LocalNodeState = "error" - // LocalNodeStateLocked LOCKED - LocalNodeStateLocked LocalNodeState = "locked" -) - -// Info represents generic information about swarm. -type Info struct { - NodeID string - NodeAddr string - - LocalNodeState LocalNodeState - ControlAvailable bool - Error string - - RemoteManagers []Peer - Nodes int `json:",omitempty"` - Managers int `json:",omitempty"` - - Cluster *ClusterInfo `json:",omitempty"` - - Warnings []string `json:",omitempty"` -} - -// Status provides information about the current swarm status and role, -// obtained from the "Swarm" header in the API response. -type Status struct { - // NodeState represents the state of the node. - NodeState LocalNodeState - - // ControlAvailable indicates if the node is a swarm manager. - ControlAvailable bool -} - -// Peer represents a peer. -type Peer struct { - NodeID string - Addr string -} - -// UpdateFlags contains flags for SwarmUpdate. -type UpdateFlags struct { - RotateWorkerToken bool - RotateManagerToken bool - RotateManagerUnlockKey bool -} - -// UnlockKeyResponse contains the response for Engine API: -// GET /swarm/unlockkey -type UnlockKeyResponse struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/task.go b/vendor/github.com/docker/docker/api/types/swarm/task.go deleted file mode 100644 index e143f844fa8..00000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/task.go +++ /dev/null @@ -1,230 +0,0 @@ -package swarm - -import ( - "time" - - "github.com/docker/docker/api/types/filters" -) - -// TaskState represents the state of a task. -type TaskState string - -const ( - // TaskStateNew NEW - TaskStateNew TaskState = "new" - // TaskStateAllocated ALLOCATED - TaskStateAllocated TaskState = "allocated" - // TaskStatePending PENDING - TaskStatePending TaskState = "pending" - // TaskStateAssigned ASSIGNED - TaskStateAssigned TaskState = "assigned" - // TaskStateAccepted ACCEPTED - TaskStateAccepted TaskState = "accepted" - // TaskStatePreparing PREPARING - TaskStatePreparing TaskState = "preparing" - // TaskStateReady READY - TaskStateReady TaskState = "ready" - // TaskStateStarting STARTING - TaskStateStarting TaskState = "starting" - // TaskStateRunning RUNNING - TaskStateRunning TaskState = "running" - // TaskStateComplete COMPLETE - TaskStateComplete TaskState = "complete" - // TaskStateShutdown SHUTDOWN - TaskStateShutdown TaskState = "shutdown" - // TaskStateFailed FAILED - TaskStateFailed TaskState = "failed" - // TaskStateRejected REJECTED - TaskStateRejected TaskState = "rejected" - // TaskStateRemove REMOVE - TaskStateRemove TaskState = "remove" - // TaskStateOrphaned ORPHANED - TaskStateOrphaned TaskState = "orphaned" -) - -// Task represents a task. -type Task struct { - ID string - Meta - Annotations - - Spec TaskSpec `json:",omitempty"` - ServiceID string `json:",omitempty"` - Slot int `json:",omitempty"` - NodeID string `json:",omitempty"` - Status TaskStatus `json:",omitempty"` - DesiredState TaskState `json:",omitempty"` - NetworksAttachments []NetworkAttachment `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` - - // JobIteration is the JobIteration of the Service that this Task was - // spawned from, if the Service is a ReplicatedJob or GlobalJob. This is - // used to determine which Tasks belong to which run of the job. This field - // is absent if the Service mode is Replicated or Global. - JobIteration *Version `json:",omitempty"` - - // Volumes is the list of VolumeAttachments for this task. It specifies - // which particular volumes are to be used by this particular task, and - // fulfilling what mounts in the spec. - Volumes []VolumeAttachment -} - -// TaskSpec represents the spec of a task. -type TaskSpec struct { - // ContainerSpec, NetworkAttachmentSpec, and PluginSpec are mutually exclusive. - // PluginSpec is only used when the `Runtime` field is set to `plugin` - // NetworkAttachmentSpec is used if the `Runtime` field is set to - // `attachment`. - ContainerSpec *ContainerSpec `json:",omitempty"` - PluginSpec *RuntimeSpec `json:",omitempty"` - NetworkAttachmentSpec *NetworkAttachmentSpec `json:",omitempty"` - - Resources *ResourceRequirements `json:",omitempty"` - RestartPolicy *RestartPolicy `json:",omitempty"` - Placement *Placement `json:",omitempty"` - Networks []NetworkAttachmentConfig `json:",omitempty"` - - // LogDriver specifies the LogDriver to use for tasks created from this - // spec. If not present, the one on cluster default on swarm.Spec will be - // used, finally falling back to the engine default if not specified. - LogDriver *Driver `json:",omitempty"` - - // ForceUpdate is a counter that triggers an update even if no relevant - // parameters have been changed. - ForceUpdate uint64 - - Runtime RuntimeType `json:",omitempty"` -} - -// Resources represents resources (CPU/Memory) which can be advertised by a -// node and requested to be reserved for a task. -type Resources struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` -} - -// Limit describes limits on resources which can be requested by a task. -type Limit struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - Pids int64 `json:",omitempty"` -} - -// GenericResource represents a "user defined" resource which can -// be either an integer (e.g: SSD=3) or a string (e.g: SSD=sda1) -type GenericResource struct { - NamedResourceSpec *NamedGenericResource `json:",omitempty"` - DiscreteResourceSpec *DiscreteGenericResource `json:",omitempty"` -} - -// NamedGenericResource represents a "user defined" resource which is defined -// as a string. -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to identify the resource (GPU="UUID-1", FPGA="/dev/sdb5", ...) -type NamedGenericResource struct { - Kind string `json:",omitempty"` - Value string `json:",omitempty"` -} - -// DiscreteGenericResource represents a "user defined" resource which is defined -// as an integer -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to count the resource (SSD=5, HDD=3, ...) -type DiscreteGenericResource struct { - Kind string `json:",omitempty"` - Value int64 `json:",omitempty"` -} - -// ResourceRequirements represents resources requirements. -type ResourceRequirements struct { - Limits *Limit `json:",omitempty"` - Reservations *Resources `json:",omitempty"` -} - -// Placement represents orchestration parameters. -type Placement struct { - Constraints []string `json:",omitempty"` - Preferences []PlacementPreference `json:",omitempty"` - MaxReplicas uint64 `json:",omitempty"` - - // Platforms stores all the platforms that the image can run on. - // This field is used in the platform filter for scheduling. If empty, - // then the platform filter is off, meaning there are no scheduling restrictions. - Platforms []Platform `json:",omitempty"` -} - -// PlacementPreference provides a way to make the scheduler aware of factors -// such as topology. -type PlacementPreference struct { - Spread *SpreadOver -} - -// SpreadOver is a scheduling preference that instructs the scheduler to spread -// tasks evenly over groups of nodes identified by labels. -type SpreadOver struct { - // label descriptor, such as engine.labels.az - SpreadDescriptor string -} - -// RestartPolicy represents the restart policy. -type RestartPolicy struct { - Condition RestartPolicyCondition `json:",omitempty"` - Delay *time.Duration `json:",omitempty"` - MaxAttempts *uint64 `json:",omitempty"` - Window *time.Duration `json:",omitempty"` -} - -// RestartPolicyCondition represents when to restart. -type RestartPolicyCondition string - -const ( - // RestartPolicyConditionNone NONE - RestartPolicyConditionNone RestartPolicyCondition = "none" - // RestartPolicyConditionOnFailure ON_FAILURE - RestartPolicyConditionOnFailure RestartPolicyCondition = "on-failure" - // RestartPolicyConditionAny ANY - RestartPolicyConditionAny RestartPolicyCondition = "any" -) - -// TaskStatus represents the status of a task. -type TaskStatus struct { - Timestamp time.Time `json:",omitempty"` - State TaskState `json:",omitempty"` - Message string `json:",omitempty"` - Err string `json:",omitempty"` - ContainerStatus *ContainerStatus `json:",omitempty"` - PortStatus PortStatus `json:",omitempty"` -} - -// ContainerStatus represents the status of a container. -type ContainerStatus struct { - ContainerID string - PID int - ExitCode int -} - -// PortStatus represents the port status of a task's host ports whose -// service has published host ports -type PortStatus struct { - Ports []PortConfig `json:",omitempty"` -} - -// VolumeAttachment contains the associating a Volume to a Task. -type VolumeAttachment struct { - // ID is the Swarmkit ID of the Volume. This is not the CSI VolumeId. - ID string `json:",omitempty"` - - // Source, together with Target, indicates the Mount, as specified in the - // ContainerSpec, that this volume fulfills. - Source string `json:",omitempty"` - - // Target, together with Source, indicates the Mount, as specified - // in the ContainerSpec, that this volume fulfills. - Target string `json:",omitempty"` -} - -// TaskListOptions holds parameters to list tasks with. -type TaskListOptions struct { - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go deleted file mode 100644 index 1a0325c7eda..00000000000 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ /dev/null @@ -1,65 +0,0 @@ -package versions - -import ( - "strconv" - "strings" -) - -// compare compares two version strings -// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. -func compare(v1, v2 string) int { - if v1 == v2 { - return 0 - } - var ( - currTab = strings.Split(v1, ".") - otherTab = strings.Split(v2, ".") - ) - - maxVer := len(currTab) - if len(otherTab) > maxVer { - maxVer = len(otherTab) - } - for i := 0; i < maxVer; i++ { - var currInt, otherInt int - - if len(currTab) > i { - currInt, _ = strconv.Atoi(currTab[i]) - } - if len(otherTab) > i { - otherInt, _ = strconv.Atoi(otherTab[i]) - } - if currInt > otherInt { - return 1 - } - if otherInt > currInt { - return -1 - } - } - return 0 -} - -// LessThan checks if a version is less than another -func LessThan(v, other string) bool { - return compare(v, other) == -1 -} - -// LessThanOrEqualTo checks if a version is less than or equal to another -func LessThanOrEqualTo(v, other string) bool { - return compare(v, other) <= 0 -} - -// GreaterThan checks if a version is greater than another -func GreaterThan(v, other string) bool { - return compare(v, other) == 1 -} - -// GreaterThanOrEqualTo checks if a version is greater than or equal to another -func GreaterThanOrEqualTo(v, other string) bool { - return compare(v, other) >= 0 -} - -// Equal checks if a version is equal to another -func Equal(v, other string) bool { - return compare(v, other) == 0 -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go deleted file mode 100644 index 469395f16e2..00000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go +++ /dev/null @@ -1,105 +0,0 @@ -package homedir - -import ( - "errors" - "os" - "path/filepath" - "strings" -) - -// GetRuntimeDir returns XDG_RUNTIME_DIR. -// XDG_RUNTIME_DIR is typically configured via pam_systemd. -// GetRuntimeDir returns non-nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetRuntimeDir() (string, error) { - if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" { - return xdgRuntimeDir, nil - } - return "", errors.New("could not get XDG_RUNTIME_DIR") -} - -// StickRuntimeDirContents sets the sticky bit on files that are under -// XDG_RUNTIME_DIR, so that the files won't be periodically removed by the system. -// -// StickyRuntimeDir returns slice of sticked files. -// StickyRuntimeDir returns nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func StickRuntimeDirContents(files []string) ([]string, error) { - runtimeDir, err := GetRuntimeDir() - if err != nil { - // ignore error if runtimeDir is empty - return nil, nil - } - runtimeDir, err = filepath.Abs(runtimeDir) - if err != nil { - return nil, err - } - var sticked []string - for _, f := range files { - f, err = filepath.Abs(f) - if err != nil { - return sticked, err - } - if strings.HasPrefix(f, runtimeDir+"/") { - if err = stick(f); err != nil { - return sticked, err - } - sticked = append(sticked, f) - } - } - return sticked, nil -} - -func stick(f string) error { - st, err := os.Stat(f) - if err != nil { - return err - } - m := st.Mode() - m |= os.ModeSticky - return os.Chmod(f, m) -} - -// GetDataHome returns XDG_DATA_HOME. -// GetDataHome returns $HOME/.local/share and nil error if XDG_DATA_HOME is not set. -// If HOME and XDG_DATA_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetDataHome() (string, error) { - if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { - return xdgDataHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_DATA_HOME or HOME") - } - return filepath.Join(home, ".local", "share"), nil -} - -// GetConfigHome returns XDG_CONFIG_HOME. -// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. -// If HOME and XDG_CONFIG_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetConfigHome() (string, error) { - if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { - return xdgConfigHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") - } - return filepath.Join(home, ".config"), nil -} - -// GetLibHome returns $HOME/.local/lib -// If HOME is not set, getpwent(3) is consulted to determine the users home directory. -func GetLibHome() (string, error) { - home := Get() - if home == "" { - return "", errors.New("could not get HOME") - } - return filepath.Join(home, ".local/lib"), nil -} diff --git a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go deleted file mode 100644 index 13df228c622..00000000000 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ /dev/null @@ -1,314 +0,0 @@ -package jsonmessage - -import ( - "encoding/json" - "fmt" - "io" - "strings" - "time" - - "github.com/docker/go-units" - "github.com/moby/term" - "github.com/morikuni/aec" -) - -// RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to -// ensure the formatted time isalways the same number of characters. -const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" - -// JSONError wraps a concrete Code and Message, Code is -// an integer error code, Message is the error message. -type JSONError struct { - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` -} - -func (e *JSONError) Error() string { - return e.Message -} - -// JSONProgress describes a progress message in a JSON stream. -type JSONProgress struct { - // Current is the current status and value of the progress made towards Total. - Current int64 `json:"current,omitempty"` - // Total is the end value describing when we made 100% progress for an operation. - Total int64 `json:"total,omitempty"` - // Start is the initial value for the operation. - Start int64 `json:"start,omitempty"` - // HideCounts. if true, hides the progress count indicator (xB/yB). - HideCounts bool `json:"hidecounts,omitempty"` - // Units is the unit to print for progress. It defaults to "bytes" if empty. - Units string `json:"units,omitempty"` - - // terminalFd is the fd of the current terminal, if any. It is used - // to get the terminal width. - terminalFd uintptr - - // nowFunc is used to override the current time in tests. - nowFunc func() time.Time - - // winSize is used to override the terminal width in tests. - winSize int -} - -func (p *JSONProgress) String() string { - var ( - width = p.width() - pbBox string - numbersBox string - ) - if p.Current <= 0 && p.Total <= 0 { - return "" - } - if p.Total <= 0 { - switch p.Units { - case "": - return fmt.Sprintf("%8v", units.HumanSize(float64(p.Current))) - default: - return fmt.Sprintf("%d %s", p.Current, p.Units) - } - } - - percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 - if percentage > 50 { - percentage = 50 - } - if width > 110 { - // this number can't be negative gh#7136 - numSpaces := 0 - if 50-percentage > 0 { - numSpaces = 50 - percentage - } - pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) - } - - switch { - case p.HideCounts: - case p.Units == "": // no units, use bytes - current := units.HumanSize(float64(p.Current)) - total := units.HumanSize(float64(p.Total)) - - numbersBox = fmt.Sprintf("%8v/%v", current, total) - - if p.Current > p.Total { - // remove total display if the reported current is wonky. - numbersBox = fmt.Sprintf("%8v", current) - } - default: - numbersBox = fmt.Sprintf("%d/%d %s", p.Current, p.Total, p.Units) - - if p.Current > p.Total { - // remove total display if the reported current is wonky. - numbersBox = fmt.Sprintf("%d %s", p.Current, p.Units) - } - } - - // Show approximation of remaining time if there's enough width. - var timeLeftBox string - if width > 50 { - if p.Current > 0 && p.Start > 0 && percentage < 50 { - fromStart := p.now().Sub(time.Unix(p.Start, 0)) - perEntry := fromStart / time.Duration(p.Current) - left := time.Duration(p.Total-p.Current) * perEntry - timeLeftBox = " " + left.Round(time.Second).String() - } - } - return pbBox + numbersBox + timeLeftBox -} - -// now returns the current time in UTC, but can be overridden in tests -// by setting JSONProgress.nowFunc to a custom function. -func (p *JSONProgress) now() time.Time { - if p.nowFunc != nil { - return p.nowFunc() - } - return time.Now().UTC() -} - -// width returns the current terminal's width, but can be overridden -// in tests by setting JSONProgress.winSize to a non-zero value. -func (p *JSONProgress) width() int { - if p.winSize != 0 { - return p.winSize - } - ws, err := term.GetWinsize(p.terminalFd) - if err == nil { - return int(ws.Width) - } - return 200 -} - -// JSONMessage defines a message struct. It describes -// the created time, where it from, status, ID of the -// message. It's used for docker events. -type JSONMessage struct { - Stream string `json:"stream,omitempty"` - Status string `json:"status,omitempty"` - Progress *JSONProgress `json:"progressDetail,omitempty"` - - // ProgressMessage is a pre-formatted presentation of [Progress]. - // - // Deprecated: this field is deprecated since docker v0.7.1 / API v1.8. Use the information in [Progress] instead. This field will be omitted in a future release. - ProgressMessage string `json:"progress,omitempty"` - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` // Deprecated: this field is no longer set in stream responses and should not be used. - Time int64 `json:"time,omitempty"` // Deprecated: this field is no longer set in stream responses and should not be used. - TimeNano int64 `json:"timeNano,omitempty"` // Deprecated: this field is no longer set in stream responses and should not be used. - Error *JSONError `json:"errorDetail,omitempty"` - - // ErrorMessage contains errors encountered during the operation. - // - // Deprecated: this field is deprecated since docker v0.6.0 / API v1.4. Use [Error.Message] instead. This field will be omitted in a future release. - ErrorMessage string `json:"error,omitempty"` // deprecated - // Aux contains out-of-band data, such as digests for push signing and image id after building. - Aux *json.RawMessage `json:"aux,omitempty"` -} - -func clearLine(out io.Writer) { - eraseMode := aec.EraseModes.All - cl := aec.EraseLine(eraseMode) - fmt.Fprint(out, cl) -} - -func cursorUp(out io.Writer, l uint) { - fmt.Fprint(out, aec.Up(l)) -} - -func cursorDown(out io.Writer, l uint) { - fmt.Fprint(out, aec.Down(l)) -} - -// Display prints the JSONMessage to out. If isTerminal is true, it erases -// the entire current line when displaying the progressbar. It returns an -// error if the [JSONMessage.Error] field is non-nil. -func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { - if jm.Error != nil { - return jm.Error - } - var endl string - if isTerminal && jm.Stream == "" && jm.Progress != nil { - clearLine(out) - endl = "\r" - fmt.Fprint(out, endl) - } else if jm.Progress != nil && jm.Progress.String() != "" { // disable progressbar in non-terminal - return nil - } - if jm.TimeNano != 0 { - fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(RFC3339NanoFixed)) - } else if jm.Time != 0 { - fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(RFC3339NanoFixed)) - } - if jm.ID != "" { - fmt.Fprintf(out, "%s: ", jm.ID) - } - if jm.From != "" { - fmt.Fprintf(out, "(from %s) ", jm.From) - } - if jm.Progress != nil && isTerminal { - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl) - } else if jm.ProgressMessage != "" { // deprecated - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl) - } else if jm.Stream != "" { - fmt.Fprintf(out, "%s%s", jm.Stream, endl) - } else { - fmt.Fprintf(out, "%s%s\n", jm.Status, endl) - } - return nil -} - -// DisplayJSONMessagesStream reads a JSON message stream from in, and writes -// each [JSONMessage] to out. It returns an error if an invalid JSONMessage -// is received, or if a JSONMessage containers a non-zero [JSONMessage.Error]. -// -// Presentation of the JSONMessage depends on whether a terminal is attached, -// and on the terminal width. Progress bars ([JSONProgress]) are suppressed -// on narrower terminals (< 110 characters). -// -// - isTerminal describes if out is a terminal, in which case it prints -// a newline ("\n") at the end of each line and moves the cursor while -// displaying. -// - terminalFd is the fd of the current terminal (if any), and used -// to get the terminal width. -// - auxCallback allows handling the [JSONMessage.Aux] field. It is -// called if a JSONMessage contains an Aux field, in which case -// DisplayJSONMessagesStream does not present the JSONMessage. -func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(JSONMessage)) error { - var ( - dec = json.NewDecoder(in) - ids = make(map[string]uint) - ) - - for { - var diff uint - var jm JSONMessage - if err := dec.Decode(&jm); err != nil { - if err == io.EOF { - break - } - return err - } - - if jm.Aux != nil { - if auxCallback != nil { - auxCallback(jm) - } - continue - } - - if jm.Progress != nil { - jm.Progress.terminalFd = terminalFd - } - if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") { - line, ok := ids[jm.ID] - if !ok { - // NOTE: This approach of using len(id) to - // figure out the number of lines of history - // only works as long as we clear the history - // when we output something that's not - // accounted for in the map, such as a line - // with no ID. - line = uint(len(ids)) - ids[jm.ID] = line - if isTerminal { - fmt.Fprintf(out, "\n") - } - } - diff = uint(len(ids)) - line - if isTerminal { - cursorUp(out, diff) - } - } else { - // When outputting something that isn't progress - // output, clear the history of previous lines. We - // don't want progress entries from some previous - // operation to be updated (for example, pull -a - // with multiple tags). - ids = make(map[string]uint) - } - err := jm.Display(out, isTerminal) - if jm.ID != "" && isTerminal { - cursorDown(out, diff) - } - if err != nil { - return err - } - } - return nil -} - -// Stream is an io.Writer for output with utilities to get the output's file -// descriptor and to detect whether it's a terminal. -// -// it is subset of the streams.Out type in -// https://pkg.go.dev/github.com/docker/cli@v20.10.17+incompatible/cli/streams#Out -type Stream interface { - io.Writer - FD() uintptr - IsTerminal() bool -} - -// DisplayJSONMessagesToStream prints json messages to the output Stream. It is -// used by the Docker CLI to print JSONMessage streams. -func DisplayJSONMessagesToStream(in io.Reader, stream Stream, auxCallback func(JSONMessage)) error { - return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/client.go b/vendor/github.com/fsouza/go-dockerclient/client.go index e1a42001771..16ae3dbf087 100644 --- a/vendor/github.com/fsouza/go-dockerclient/client.go +++ b/vendor/github.com/fsouza/go-dockerclient/client.go @@ -30,9 +30,9 @@ import ( "sync/atomic" "time" - "github.com/docker/docker/pkg/homedir" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/stdcopy" + "github.com/moby/moby/api/pkg/stdcopy" + "github.com/moby/moby/client/pkg/jsonmessage" + "github.com/moby/moby/v2/pkg/homedir" ) const ( @@ -654,7 +654,7 @@ func handleStreamResponse(resp *http.Response, streamOptions *streamOptions) err return err } if st, ok := streamOptions.stdout.(stream); ok { - err = jsonmessage.DisplayJSONMessagesToStream(resp.Body, st, nil) + err = jsonmessage.DisplayJSONMessagesStream(resp.Body, st, st.FD(), st.IsTerminal(), nil) } else { err = jsonmessage.DisplayJSONMessagesStream(resp.Body, streamOptions.stdout, 0, false, nil) } diff --git a/vendor/github.com/fsouza/go-dockerclient/container.go b/vendor/github.com/fsouza/go-dockerclient/container.go index e5dafe0faa7..c62807149cd 100644 --- a/vendor/github.com/fsouza/go-dockerclient/container.go +++ b/vendor/github.com/fsouza/go-dockerclient/container.go @@ -185,6 +185,7 @@ type ContainerNetwork struct { Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty" toml:"Gateway,omitempty"` EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty" toml:"EndpointID,omitempty"` NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty" toml:"NetworkID,omitempty"` + DNSNames []string `json:"DNSNames,omitempty" yaml:"DNSNames,omitempty" toml:"DNSNames,omitempty"` } // NetworkSettings contains network-related information about a container @@ -485,79 +486,80 @@ type BlockLimit struct { // HostConfig contains the container options related to starting a container on // a given host type HostConfig struct { - Binds []string `json:"Binds,omitempty" yaml:"Binds,omitempty" toml:"Binds,omitempty"` - CapAdd []string `json:"CapAdd,omitempty" yaml:"CapAdd,omitempty" toml:"CapAdd,omitempty"` - CapDrop []string `json:"CapDrop,omitempty" yaml:"CapDrop,omitempty" toml:"CapDrop,omitempty"` - Capabilities []string `json:"Capabilities,omitempty" yaml:"Capabilities,omitempty" toml:"Capabilities,omitempty"` // Mutually exclusive w.r.t. CapAdd and CapDrop API v1.40 - GroupAdd []string `json:"GroupAdd,omitempty" yaml:"GroupAdd,omitempty" toml:"GroupAdd,omitempty"` - ContainerIDFile string `json:"ContainerIDFile,omitempty" yaml:"ContainerIDFile,omitempty" toml:"ContainerIDFile,omitempty"` - LxcConf []KeyValuePair `json:"LxcConf,omitempty" yaml:"LxcConf,omitempty" toml:"LxcConf,omitempty"` - PortBindings map[Port][]PortBinding `json:"PortBindings,omitempty" yaml:"PortBindings,omitempty" toml:"PortBindings,omitempty"` - Links []string `json:"Links,omitempty" yaml:"Links,omitempty" toml:"Links,omitempty"` - DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty" toml:"Dns,omitempty"` // For Docker API v1.10 and above only - DNSOptions []string `json:"DnsOptions,omitempty" yaml:"DnsOptions,omitempty" toml:"DnsOptions,omitempty"` - DNSSearch []string `json:"DnsSearch,omitempty" yaml:"DnsSearch,omitempty" toml:"DnsSearch,omitempty"` - ExtraHosts []string `json:"ExtraHosts,omitempty" yaml:"ExtraHosts,omitempty" toml:"ExtraHosts,omitempty"` - VolumesFrom []string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty" toml:"VolumesFrom,omitempty"` - UsernsMode string `json:"UsernsMode,omitempty" yaml:"UsernsMode,omitempty" toml:"UsernsMode,omitempty"` - NetworkMode string `json:"NetworkMode,omitempty" yaml:"NetworkMode,omitempty" toml:"NetworkMode,omitempty"` - IpcMode string `json:"IpcMode,omitempty" yaml:"IpcMode,omitempty" toml:"IpcMode,omitempty"` - Isolation string `json:"Isolation,omitempty" yaml:"Isolation,omitempty" toml:"Isolation,omitempty"` // Windows only - ConsoleSize [2]int `json:"ConsoleSize,omitempty" yaml:"ConsoleSize,omitempty" toml:"ConsoleSize,omitempty"` // Windows only height x width - PidMode string `json:"PidMode,omitempty" yaml:"PidMode,omitempty" toml:"PidMode,omitempty"` - UTSMode string `json:"UTSMode,omitempty" yaml:"UTSMode,omitempty" toml:"UTSMode,omitempty"` - RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty" yaml:"RestartPolicy,omitempty" toml:"RestartPolicy,omitempty"` - Devices []Device `json:"Devices,omitempty" yaml:"Devices,omitempty" toml:"Devices,omitempty"` - DeviceCgroupRules []string `json:"DeviceCgroupRules,omitempty" yaml:"DeviceCgroupRules,omitempty" toml:"DeviceCgroupRules,omitempty"` - DeviceRequests []DeviceRequest `json:"DeviceRequests,omitempty" yaml:"DeviceRequests,omitempty" toml:"DeviceRequests,omitempty"` - LogConfig LogConfig `json:"LogConfig,omitempty" yaml:"LogConfig,omitempty" toml:"LogConfig,omitempty"` - SecurityOpt []string `json:"SecurityOpt,omitempty" yaml:"SecurityOpt,omitempty" toml:"SecurityOpt,omitempty"` - CgroupnsMode string `json:"CgroupnsMode,omitempty" yaml:"CgroupnsMode,omitempty" toml:"CgroupnsMode,omitempty"` // v1.40+ - Cgroup string `json:"Cgroup,omitempty" yaml:"Cgroup,omitempty" toml:"Cgroup,omitempty"` - CgroupParent string `json:"CgroupParent,omitempty" yaml:"CgroupParent,omitempty" toml:"CgroupParent,omitempty"` - Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty" toml:"Memory,omitempty"` - MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty" toml:"MemoryReservation,omitempty"` - KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty" toml:"KernelMemory,omitempty"` - MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty" toml:"MemorySwap,omitempty"` - CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty" toml:"CpuShares,omitempty"` - CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty" toml:"Cpuset,omitempty"` - CPUSetCPUs string `json:"CpusetCpus,omitempty" yaml:"CpusetCpus,omitempty" toml:"CpusetCpus,omitempty"` - CPUSetMEMs string `json:"CpusetMems,omitempty" yaml:"CpusetMems,omitempty" toml:"CpusetMems,omitempty"` - CPUQuota int64 `json:"CpuQuota,omitempty" yaml:"CpuQuota,omitempty" toml:"CpuQuota,omitempty"` - CPUPeriod int64 `json:"CpuPeriod,omitempty" yaml:"CpuPeriod,omitempty" toml:"CpuPeriod,omitempty"` - CPURealtimePeriod int64 `json:"CpuRealtimePeriod,omitempty" yaml:"CpuRealtimePeriod,omitempty" toml:"CpuRealtimePeriod,omitempty"` - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime,omitempty" yaml:"CpuRealtimeRuntime,omitempty" toml:"CpuRealtimeRuntime,omitempty"` - NanoCPUs int64 `json:"NanoCpus,omitempty" yaml:"NanoCpus,omitempty" toml:"NanoCpus,omitempty"` - BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight,omitempty" toml:"BlkioWeight,omitempty"` - BlkioWeightDevice []BlockWeight `json:"BlkioWeightDevice,omitempty" yaml:"BlkioWeightDevice,omitempty" toml:"BlkioWeightDevice,omitempty"` - BlkioDeviceReadBps []BlockLimit `json:"BlkioDeviceReadBps,omitempty" yaml:"BlkioDeviceReadBps,omitempty" toml:"BlkioDeviceReadBps,omitempty"` - BlkioDeviceReadIOps []BlockLimit `json:"BlkioDeviceReadIOps,omitempty" yaml:"BlkioDeviceReadIOps,omitempty" toml:"BlkioDeviceReadIOps,omitempty"` - BlkioDeviceWriteBps []BlockLimit `json:"BlkioDeviceWriteBps,omitempty" yaml:"BlkioDeviceWriteBps,omitempty" toml:"BlkioDeviceWriteBps,omitempty"` - BlkioDeviceWriteIOps []BlockLimit `json:"BlkioDeviceWriteIOps,omitempty" yaml:"BlkioDeviceWriteIOps,omitempty" toml:"BlkioDeviceWriteIOps,omitempty"` - Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty" toml:"Ulimits,omitempty"` - VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty" toml:"VolumeDriver,omitempty"` - OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty" toml:"OomScoreAdj,omitempty"` - MemorySwappiness *int64 `json:"MemorySwappiness,omitempty" yaml:"MemorySwappiness,omitempty" toml:"MemorySwappiness,omitempty"` - PidsLimit *int64 `json:"PidsLimit,omitempty" yaml:"PidsLimit,omitempty" toml:"PidsLimit,omitempty"` - OOMKillDisable *bool `json:"OomKillDisable,omitempty" yaml:"OomKillDisable,omitempty" toml:"OomKillDisable,omitempty"` - ShmSize int64 `json:"ShmSize,omitempty" yaml:"ShmSize,omitempty" toml:"ShmSize,omitempty"` - Tmpfs map[string]string `json:"Tmpfs,omitempty" yaml:"Tmpfs,omitempty" toml:"Tmpfs,omitempty"` - StorageOpt map[string]string `json:"StorageOpt,omitempty" yaml:"StorageOpt,omitempty" toml:"StorageOpt,omitempty"` - Sysctls map[string]string `json:"Sysctls,omitempty" yaml:"Sysctls,omitempty" toml:"Sysctls,omitempty"` - CPUCount int64 `json:"CpuCount,omitempty" yaml:"CpuCount,omitempty"` - CPUPercent int64 `json:"CpuPercent,omitempty" yaml:"CpuPercent,omitempty"` - IOMaximumBandwidth int64 `json:"IOMaximumBandwidth,omitempty" yaml:"IOMaximumBandwidth,omitempty"` - IOMaximumIOps int64 `json:"IOMaximumIOps,omitempty" yaml:"IOMaximumIOps,omitempty"` - Mounts []HostMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` - MaskedPaths []string `json:"MaskedPaths,omitempty" yaml:"MaskedPaths,omitempty" toml:"MaskedPaths,omitempty"` - ReadonlyPaths []string `json:"ReadonlyPaths,omitempty" yaml:"ReadonlyPaths,omitempty" toml:"ReadonlyPaths,omitempty"` - Runtime string `json:"Runtime,omitempty" yaml:"Runtime,omitempty" toml:"Runtime,omitempty"` - Init bool `json:",omitempty" yaml:",omitempty"` - Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty" toml:"Privileged,omitempty"` - PublishAllPorts bool `json:"PublishAllPorts,omitempty" yaml:"PublishAllPorts,omitempty" toml:"PublishAllPorts,omitempty"` - ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty" yaml:"ReadonlyRootfs,omitempty" toml:"ReadonlyRootfs,omitempty"` - AutoRemove bool `json:"AutoRemove,omitempty" yaml:"AutoRemove,omitempty" toml:"AutoRemove,omitempty"` - Annotations map[string]string `json:"Annotations,omitempty" yaml:"Annotations,omitempty" toml:"Annotations,omitempty"` + Binds []string `json:"Binds,omitempty" yaml:"Binds,omitempty" toml:"Binds,omitempty"` + CapAdd []string `json:"CapAdd,omitempty" yaml:"CapAdd,omitempty" toml:"CapAdd,omitempty"` + CapDrop []string `json:"CapDrop,omitempty" yaml:"CapDrop,omitempty" toml:"CapDrop,omitempty"` + Capabilities []string `json:"Capabilities,omitempty" yaml:"Capabilities,omitempty" toml:"Capabilities,omitempty"` // Mutually exclusive w.r.t. CapAdd and CapDrop API v1.40 + GroupAdd []string `json:"GroupAdd,omitempty" yaml:"GroupAdd,omitempty" toml:"GroupAdd,omitempty"` + ContainerIDFile string `json:"ContainerIDFile,omitempty" yaml:"ContainerIDFile,omitempty" toml:"ContainerIDFile,omitempty"` + LxcConf []KeyValuePair `json:"LxcConf,omitempty" yaml:"LxcConf,omitempty" toml:"LxcConf,omitempty"` + PortBindings map[Port][]PortBinding `json:"PortBindings,omitempty" yaml:"PortBindings,omitempty" toml:"PortBindings,omitempty"` + Links []string `json:"Links,omitempty" yaml:"Links,omitempty" toml:"Links,omitempty"` + DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty" toml:"Dns,omitempty"` // For Docker API v1.10 and above only + DNSOptions []string `json:"DnsOptions,omitempty" yaml:"DnsOptions,omitempty" toml:"DnsOptions,omitempty"` + DNSSearch []string `json:"DnsSearch,omitempty" yaml:"DnsSearch,omitempty" toml:"DnsSearch,omitempty"` + ExtraHosts []string `json:"ExtraHosts,omitempty" yaml:"ExtraHosts,omitempty" toml:"ExtraHosts,omitempty"` + VolumesFrom []string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty" toml:"VolumesFrom,omitempty"` + UsernsMode string `json:"UsernsMode,omitempty" yaml:"UsernsMode,omitempty" toml:"UsernsMode,omitempty"` + NetworkMode string `json:"NetworkMode,omitempty" yaml:"NetworkMode,omitempty" toml:"NetworkMode,omitempty"` + IpcMode string `json:"IpcMode,omitempty" yaml:"IpcMode,omitempty" toml:"IpcMode,omitempty"` + Isolation string `json:"Isolation,omitempty" yaml:"Isolation,omitempty" toml:"Isolation,omitempty"` // Windows only + ConsoleSize [2]int `json:"ConsoleSize,omitempty" yaml:"ConsoleSize,omitempty" toml:"ConsoleSize,omitempty"` // Windows only height x width + PidMode string `json:"PidMode,omitempty" yaml:"PidMode,omitempty" toml:"PidMode,omitempty"` + UTSMode string `json:"UTSMode,omitempty" yaml:"UTSMode,omitempty" toml:"UTSMode,omitempty"` + RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty" yaml:"RestartPolicy,omitempty" toml:"RestartPolicy,omitempty"` + Devices []Device `json:"Devices,omitempty" yaml:"Devices,omitempty" toml:"Devices,omitempty"` + DeviceCgroupRules []string `json:"DeviceCgroupRules,omitempty" yaml:"DeviceCgroupRules,omitempty" toml:"DeviceCgroupRules,omitempty"` + DeviceRequests []DeviceRequest `json:"DeviceRequests,omitempty" yaml:"DeviceRequests,omitempty" toml:"DeviceRequests,omitempty"` + LogConfig LogConfig `json:"LogConfig,omitempty" yaml:"LogConfig,omitempty" toml:"LogConfig,omitempty"` + SecurityOpt []string `json:"SecurityOpt,omitempty" yaml:"SecurityOpt,omitempty" toml:"SecurityOpt,omitempty"` + CgroupnsMode string `json:"CgroupnsMode,omitempty" yaml:"CgroupnsMode,omitempty" toml:"CgroupnsMode,omitempty"` // v1.40+ + Cgroup string `json:"Cgroup,omitempty" yaml:"Cgroup,omitempty" toml:"Cgroup,omitempty"` + CgroupParent string `json:"CgroupParent,omitempty" yaml:"CgroupParent,omitempty" toml:"CgroupParent,omitempty"` + Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty" toml:"Memory,omitempty"` + MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty" toml:"MemoryReservation,omitempty"` + // Deprecated: KernelMemory is deprecated as of API 1.42 and removed in API 1.52. + KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty" toml:"KernelMemory,omitempty"` + MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty" toml:"MemorySwap,omitempty"` + CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty" toml:"CpuShares,omitempty"` + CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty" toml:"Cpuset,omitempty"` + CPUSetCPUs string `json:"CpusetCpus,omitempty" yaml:"CpusetCpus,omitempty" toml:"CpusetCpus,omitempty"` + CPUSetMEMs string `json:"CpusetMems,omitempty" yaml:"CpusetMems,omitempty" toml:"CpusetMems,omitempty"` + CPUQuota int64 `json:"CpuQuota,omitempty" yaml:"CpuQuota,omitempty" toml:"CpuQuota,omitempty"` + CPUPeriod int64 `json:"CpuPeriod,omitempty" yaml:"CpuPeriod,omitempty" toml:"CpuPeriod,omitempty"` + CPURealtimePeriod int64 `json:"CpuRealtimePeriod,omitempty" yaml:"CpuRealtimePeriod,omitempty" toml:"CpuRealtimePeriod,omitempty"` + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime,omitempty" yaml:"CpuRealtimeRuntime,omitempty" toml:"CpuRealtimeRuntime,omitempty"` + NanoCPUs int64 `json:"NanoCpus,omitempty" yaml:"NanoCpus,omitempty" toml:"NanoCpus,omitempty"` + BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight,omitempty" toml:"BlkioWeight,omitempty"` + BlkioWeightDevice []BlockWeight `json:"BlkioWeightDevice,omitempty" yaml:"BlkioWeightDevice,omitempty" toml:"BlkioWeightDevice,omitempty"` + BlkioDeviceReadBps []BlockLimit `json:"BlkioDeviceReadBps,omitempty" yaml:"BlkioDeviceReadBps,omitempty" toml:"BlkioDeviceReadBps,omitempty"` + BlkioDeviceReadIOps []BlockLimit `json:"BlkioDeviceReadIOps,omitempty" yaml:"BlkioDeviceReadIOps,omitempty" toml:"BlkioDeviceReadIOps,omitempty"` + BlkioDeviceWriteBps []BlockLimit `json:"BlkioDeviceWriteBps,omitempty" yaml:"BlkioDeviceWriteBps,omitempty" toml:"BlkioDeviceWriteBps,omitempty"` + BlkioDeviceWriteIOps []BlockLimit `json:"BlkioDeviceWriteIOps,omitempty" yaml:"BlkioDeviceWriteIOps,omitempty" toml:"BlkioDeviceWriteIOps,omitempty"` + Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty" toml:"Ulimits,omitempty"` + VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty" toml:"VolumeDriver,omitempty"` + OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty" toml:"OomScoreAdj,omitempty"` + MemorySwappiness *int64 `json:"MemorySwappiness,omitempty" yaml:"MemorySwappiness,omitempty" toml:"MemorySwappiness,omitempty"` + PidsLimit *int64 `json:"PidsLimit,omitempty" yaml:"PidsLimit,omitempty" toml:"PidsLimit,omitempty"` + OOMKillDisable *bool `json:"OomKillDisable,omitempty" yaml:"OomKillDisable,omitempty" toml:"OomKillDisable,omitempty"` + ShmSize int64 `json:"ShmSize,omitempty" yaml:"ShmSize,omitempty" toml:"ShmSize,omitempty"` + Tmpfs map[string]string `json:"Tmpfs,omitempty" yaml:"Tmpfs,omitempty" toml:"Tmpfs,omitempty"` + StorageOpt map[string]string `json:"StorageOpt,omitempty" yaml:"StorageOpt,omitempty" toml:"StorageOpt,omitempty"` + Sysctls map[string]string `json:"Sysctls,omitempty" yaml:"Sysctls,omitempty" toml:"Sysctls,omitempty"` + CPUCount int64 `json:"CpuCount,omitempty" yaml:"CpuCount,omitempty"` + CPUPercent int64 `json:"CpuPercent,omitempty" yaml:"CpuPercent,omitempty"` + IOMaximumBandwidth int64 `json:"IOMaximumBandwidth,omitempty" yaml:"IOMaximumBandwidth,omitempty"` + IOMaximumIOps int64 `json:"IOMaximumIOps,omitempty" yaml:"IOMaximumIOps,omitempty"` + Mounts []HostMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + MaskedPaths []string `json:"MaskedPaths,omitempty" yaml:"MaskedPaths,omitempty" toml:"MaskedPaths,omitempty"` + ReadonlyPaths []string `json:"ReadonlyPaths,omitempty" yaml:"ReadonlyPaths,omitempty" toml:"ReadonlyPaths,omitempty"` + Runtime string `json:"Runtime,omitempty" yaml:"Runtime,omitempty" toml:"Runtime,omitempty"` + Init bool `json:",omitempty" yaml:",omitempty"` + Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty" toml:"Privileged,omitempty"` + PublishAllPorts bool `json:"PublishAllPorts,omitempty" yaml:"PublishAllPorts,omitempty" toml:"PublishAllPorts,omitempty"` + ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty" yaml:"ReadonlyRootfs,omitempty" toml:"ReadonlyRootfs,omitempty"` + AutoRemove bool `json:"AutoRemove,omitempty" yaml:"AutoRemove,omitempty" toml:"AutoRemove,omitempty"` + Annotations map[string]string `json:"Annotations,omitempty" yaml:"Annotations,omitempty" toml:"Annotations,omitempty"` } // NetworkingConfig represents the container's networking configuration for each of its interfaces diff --git a/vendor/github.com/fsouza/go-dockerclient/container_update.go b/vendor/github.com/fsouza/go-dockerclient/container_update.go index d2116dbd738..b44fc8478bb 100644 --- a/vendor/github.com/fsouza/go-dockerclient/container_update.go +++ b/vendor/github.com/fsouza/go-dockerclient/container_update.go @@ -10,20 +10,21 @@ import ( // // See https://goo.gl/Y6fXUy for more details. type UpdateContainerOptions struct { - BlkioWeight int `json:"BlkioWeight"` - CPUShares int `json:"CpuShares"` - CPUPeriod int `json:"CpuPeriod"` - CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` - CPUQuota int `json:"CpuQuota"` - CpusetCpus string `json:"CpusetCpus"` - CpusetMems string `json:"CpusetMems"` - Memory int `json:"Memory"` - MemorySwap int `json:"MemorySwap"` - MemoryReservation int `json:"MemoryReservation"` - KernelMemory int `json:"KernelMemory"` - RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty"` - Context context.Context + BlkioWeight int `json:"BlkioWeight"` + CPUShares int `json:"CpuShares"` + CPUPeriod int `json:"CpuPeriod"` + CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` + CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` + CPUQuota int `json:"CpuQuota"` + CpusetCpus string `json:"CpusetCpus"` + CpusetMems string `json:"CpusetMems"` + Memory int `json:"Memory"` + MemorySwap int `json:"MemorySwap"` + MemoryReservation int `json:"MemoryReservation"` + // Deprecated: KernelMemory is deprecated as of API 1.42 and removed in API 1.52. + KernelMemory int `json:"KernelMemory"` + RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty"` + Context context.Context } // UpdateContainer updates the container at ID with the options diff --git a/vendor/github.com/fsouza/go-dockerclient/distribution.go b/vendor/github.com/fsouza/go-dockerclient/distribution.go index 6e5e12f7dd3..e892be5d87f 100644 --- a/vendor/github.com/fsouza/go-dockerclient/distribution.go +++ b/vendor/github.com/fsouza/go-dockerclient/distribution.go @@ -8,7 +8,7 @@ import ( "encoding/json" "net/http" - "github.com/docker/docker/api/types/registry" + "github.com/moby/moby/api/types/registry" ) // InspectDistribution returns image digest and platform information by contacting the registry diff --git a/vendor/github.com/fsouza/go-dockerclient/image.go b/vendor/github.com/fsouza/go-dockerclient/image.go index 614908c6606..5998ea70dd7 100644 --- a/vendor/github.com/fsouza/go-dockerclient/image.go +++ b/vendor/github.com/fsouza/go-dockerclient/image.go @@ -20,10 +20,11 @@ import ( // APIImages represent an image returned in the ListImages call. type APIImages struct { - ID string `json:"Id" yaml:"Id" toml:"Id"` - RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty" toml:"RepoTags,omitempty"` - Created int64 `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` - Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` + ID string `json:"Id" yaml:"Id" toml:"Id"` + RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty" toml:"RepoTags,omitempty"` + Created int64 `json:"Created,omitempty" yaml:"Created,omitempty" toml:"Created,omitempty"` + Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` + // Deprecated: VirtualSize is deprecated as of API 1.44. Use Size instead. VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty" toml:"VirtualSize,omitempty"` ParentID string `json:"ParentId,omitempty" yaml:"ParentId,omitempty" toml:"ParentId,omitempty"` RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty" toml:"RepoDigests,omitempty"` @@ -50,10 +51,11 @@ type Image struct { Config *Config `json:"Config,omitempty" yaml:"Config,omitempty" toml:"Config,omitempty"` Architecture string `json:"Architecture,omitempty" yaml:"Architecture,omitempty"` Size int64 `json:"Size,omitempty" yaml:"Size,omitempty" toml:"Size,omitempty"` - VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty" toml:"VirtualSize,omitempty"` - RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty" toml:"RepoDigests,omitempty"` - RootFS *RootFS `json:"RootFS,omitempty" yaml:"RootFS,omitempty" toml:"RootFS,omitempty"` - OS string `json:"Os,omitempty" yaml:"Os,omitempty" toml:"Os,omitempty"` + // Deprecated: VirtualSize is deprecated as of API 1.44. Use Size instead. + VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty" toml:"VirtualSize,omitempty"` + RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty" toml:"RepoDigests,omitempty"` + RootFS *RootFS `json:"RootFS,omitempty" yaml:"RootFS,omitempty" toml:"RootFS,omitempty"` + OS string `json:"Os,omitempty" yaml:"Os,omitempty" toml:"Os,omitempty"` } // ImagePre012 serves the same purpose as the Image type except that it is for diff --git a/vendor/github.com/fsouza/go-dockerclient/misc.go b/vendor/github.com/fsouza/go-dockerclient/misc.go index 827cd29dfc1..7fd5f841a16 100644 --- a/vendor/github.com/fsouza/go-dockerclient/misc.go +++ b/vendor/github.com/fsouza/go-dockerclient/misc.go @@ -10,8 +10,6 @@ import ( "net" "net/http" "strings" - - "github.com/docker/docker/api/types/swarm" ) // Version returns version information about the docker server. @@ -78,21 +76,24 @@ type DockerInfo struct { Isolation string InitBinary string DefaultRuntime string - Swarm swarm.Info + Swarm SwarmInfo LiveRestoreEnabled bool MemoryLimit bool SwapLimit bool - KernelMemory bool - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - OomKillDisable bool - ExperimentalBuild bool + // Deprecated: KernelMemory is deprecated as of API 1.42 and removed in API 1.52. + KernelMemory bool + CPUCfsPeriod bool `json:"CpuCfsPeriod"` + CPUCfsQuota bool `json:"CpuCfsQuota"` + CPUShares bool + CPUSet bool + IPv4Forwarding bool + BridgeNfIptables bool + BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` + Debug bool + OomKillDisable bool + ExperimentalBuild bool + CDISpecDirs []string `json:"CDISpecDirs,omitempty"` + Containerd *ContainerdInfo `json:"Containerd,omitempty"` } // Runtime describes an OCI runtime @@ -103,6 +104,22 @@ type Runtime struct { Args []string `json:"runtimeArgs"` } +// ContainerdInfo contains information about the containerd instance. +type ContainerdInfo struct { + Address string `json:"Address,omitempty"` + Namespaces struct { + Containers string `json:"Containers,omitempty"` + Plugins string `json:"Plugins,omitempty"` + } `json:"Namespaces,omitempty"` +} + +// SwarmInfo contains basic swarm information from docker info. +// Deprecated: Docker Swarm is deprecated. +type SwarmInfo struct { + NodeID string + NodeAddr string +} + // PluginsInfo is a struct with the plugins registered with the docker daemon // // for more information, see: https://goo.gl/bHUoz9 diff --git a/vendor/github.com/fsouza/go-dockerclient/network.go b/vendor/github.com/fsouza/go-dockerclient/network.go index 6932c8d8721..8bb77322ac8 100644 --- a/vendor/github.com/fsouza/go-dockerclient/network.go +++ b/vendor/github.com/fsouza/go-dockerclient/network.go @@ -123,6 +123,7 @@ type CreateNetworkOptions struct { CheckDuplicate bool `json:"CheckDuplicate" yaml:"CheckDuplicate" toml:"CheckDuplicate"` Internal bool `json:"Internal" yaml:"Internal" toml:"Internal"` EnableIPv6 bool `json:"EnableIPv6" yaml:"EnableIPv6" toml:"EnableIPv6"` + EnableIPv4 bool `json:"EnableIPv4,omitempty" yaml:"EnableIPv4,omitempty" toml:"EnableIPv4,omitempty"` Attachable bool `json:"Attachable" yaml:"Attachable" toml:"Attachable"` ConfigOnly bool `json:"ConfigOnly" yaml:"ConfigOnly" toml:"ConfigOnly"` Ingress bool `json:"Ingress" yaml:"Ingress" toml:"Ingress"` @@ -239,6 +240,7 @@ type EndpointConfig struct { GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty" toml:"GlobalIPv6PrefixLen,omitempty"` MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty" toml:"MacAddress,omitempty"` DriverOpts map[string]string `json:"DriverOpts,omitempty" yaml:"DriverOpts,omitempty" toml:"DriverOpts,omitempty"` + GwPriority int `json:"GwPriority,omitempty" yaml:"GwPriority,omitempty" toml:"GwPriority,omitempty"` } // EndpointIPAMConfig represents IPAM configurations for an diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm.go b/vendor/github.com/fsouza/go-dockerclient/swarm.go deleted file mode 100644 index ae37cd1e8c3..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -var ( - // ErrNodeAlreadyInSwarm is the error returned by InitSwarm and JoinSwarm - // when the node is already part of a Swarm. - ErrNodeAlreadyInSwarm = errors.New("node already in a Swarm") - - // ErrNodeNotInSwarm is the error returned by LeaveSwarm and UpdateSwarm - // when the node is not part of a Swarm. - ErrNodeNotInSwarm = errors.New("node is not in a Swarm") -) - -// InitSwarmOptions specify parameters to the InitSwarm function. -// See https://goo.gl/hzkgWu for more details. -type InitSwarmOptions struct { - swarm.InitRequest - Context context.Context -} - -// InitSwarm initializes a new Swarm and returns the node ID. -// See https://goo.gl/ZWyG1M for more details. -func (c *Client) InitSwarm(opts InitSwarmOptions) (string, error) { - path := "/swarm/init" - resp, err := c.do(http.MethodPost, path, doOptions{ - data: opts.InitRequest, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && (e.Status == http.StatusNotAcceptable || e.Status == http.StatusServiceUnavailable) { - return "", ErrNodeAlreadyInSwarm - } - return "", err - } - defer resp.Body.Close() - var response string - if err := json.NewDecoder(resp.Body).Decode(&response); err != nil { - return "", err - } - return response, nil -} - -// JoinSwarmOptions specify parameters to the JoinSwarm function. -// See https://goo.gl/TdhJWU for more details. -type JoinSwarmOptions struct { - swarm.JoinRequest - Context context.Context -} - -// JoinSwarm joins an existing Swarm. -// See https://goo.gl/N59IP1 for more details. -func (c *Client) JoinSwarm(opts JoinSwarmOptions) error { - path := "/swarm/join" - resp, err := c.do(http.MethodPost, path, doOptions{ - data: opts.JoinRequest, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && (e.Status == http.StatusNotAcceptable || e.Status == http.StatusServiceUnavailable) { - return ErrNodeAlreadyInSwarm - } - } - resp.Body.Close() - return err -} - -// LeaveSwarmOptions specify parameters to the LeaveSwarm function. -// See https://goo.gl/UWDlLg for more details. -type LeaveSwarmOptions struct { - Force bool - Context context.Context -} - -// LeaveSwarm leaves a Swarm. -// See https://goo.gl/FTX1aD for more details. -func (c *Client) LeaveSwarm(opts LeaveSwarmOptions) error { - params := make(url.Values) - params.Set("force", strconv.FormatBool(opts.Force)) - path := "/swarm/leave?" + params.Encode() - resp, err := c.do(http.MethodPost, path, doOptions{ - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && (e.Status == http.StatusNotAcceptable || e.Status == http.StatusServiceUnavailable) { - return ErrNodeNotInSwarm - } - } - resp.Body.Close() - return err -} - -// UpdateSwarmOptions specify parameters to the UpdateSwarm function. -// See https://goo.gl/vFbq36 for more details. -type UpdateSwarmOptions struct { - Version int - RotateWorkerToken bool - RotateManagerToken bool - Swarm swarm.Spec - Context context.Context -} - -// UpdateSwarm updates a Swarm. -// See https://goo.gl/iJFnsw for more details. -func (c *Client) UpdateSwarm(opts UpdateSwarmOptions) error { - params := make(url.Values) - params.Set("version", strconv.Itoa(opts.Version)) - params.Set("rotateWorkerToken", strconv.FormatBool(opts.RotateWorkerToken)) - params.Set("rotateManagerToken", strconv.FormatBool(opts.RotateManagerToken)) - path := "/swarm/update?" + params.Encode() - resp, err := c.do(http.MethodPost, path, doOptions{ - data: opts.Swarm, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && (e.Status == http.StatusNotAcceptable || e.Status == http.StatusServiceUnavailable) { - return ErrNodeNotInSwarm - } - } - resp.Body.Close() - return err -} - -// InspectSwarm inspects a Swarm. -// See https://goo.gl/MFwgX9 for more details. -func (c *Client) InspectSwarm(ctx context.Context) (swarm.Swarm, error) { - response := swarm.Swarm{} - resp, err := c.do(http.MethodGet, "/swarm", doOptions{ - context: ctx, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && (e.Status == http.StatusNotAcceptable || e.Status == http.StatusServiceUnavailable) { - return response, ErrNodeNotInSwarm - } - return response, err - } - defer resp.Body.Close() - err = json.NewDecoder(resp.Body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm_configs.go b/vendor/github.com/fsouza/go-dockerclient/swarm_configs.go deleted file mode 100644 index 055e99544aa..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm_configs.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2017 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// NoSuchConfig is the error returned when a given config does not exist. -type NoSuchConfig struct { - ID string - Err error -} - -func (err *NoSuchConfig) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such config: " + err.ID -} - -// CreateConfigOptions specify parameters to the CreateConfig function. -// -// See https://goo.gl/KrVjHz for more details. -type CreateConfigOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.ConfigSpec - Context context.Context -} - -// CreateConfig creates a new config, returning the config instance -// or an error in case of failure. -// -// See https://goo.gl/KrVjHz for more details. -func (c *Client) CreateConfig(opts CreateConfigOptions) (*swarm.Config, error) { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return nil, err - } - path := "/configs/create?" + queryString(opts) - resp, err := c.do(http.MethodPost, path, doOptions{ - headers: headers, - data: opts.ConfigSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var config swarm.Config - if err := json.NewDecoder(resp.Body).Decode(&config); err != nil { - return nil, err - } - return &config, nil -} - -// RemoveConfigOptions encapsulates options to remove a config. -// -// See https://goo.gl/Tqrtya for more details. -type RemoveConfigOptions struct { - ID string `qs:"-"` - Context context.Context -} - -// RemoveConfig removes a config, returning an error in case of failure. -// -// See https://goo.gl/Tqrtya for more details. -func (c *Client) RemoveConfig(opts RemoveConfigOptions) error { - path := "/configs/" + opts.ID - resp, err := c.do(http.MethodDelete, path, doOptions{context: opts.Context}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchConfig{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} - -// UpdateConfigOptions specify parameters to the UpdateConfig function. -// -// See https://goo.gl/wu3MmS for more details. -type UpdateConfigOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.ConfigSpec - Context context.Context - Version uint64 -} - -// UpdateConfig updates the config at ID with the options -// -// Only label can be updated -// https://docs.docker.com/engine/api/v1.33/#operation/ConfigUpdate -// See https://goo.gl/wu3MmS for more details. -func (c *Client) UpdateConfig(id string, opts UpdateConfigOptions) error { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return err - } - params := make(url.Values) - params.Set("version", strconv.FormatUint(opts.Version, 10)) - resp, err := c.do(http.MethodPost, "/configs/"+id+"/update?"+params.Encode(), doOptions{ - headers: headers, - data: opts.ConfigSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchConfig{ID: id} - } - return err - } - defer resp.Body.Close() - return nil -} - -// InspectConfig returns information about a config by its ID. -// -// See https://goo.gl/dHmr75 for more details. -func (c *Client) InspectConfig(id string) (*swarm.Config, error) { - path := "/configs/" + id - resp, err := c.do(http.MethodGet, path, doOptions{}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return nil, &NoSuchConfig{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var config swarm.Config - if err := json.NewDecoder(resp.Body).Decode(&config); err != nil { - return nil, err - } - return &config, nil -} - -// ListConfigsOptions specify parameters to the ListConfigs function. -// -// See https://goo.gl/DwvNMd for more details. -type ListConfigsOptions struct { - Filters map[string][]string - Context context.Context -} - -// ListConfigs returns a slice of configs matching the given criteria. -// -// See https://goo.gl/DwvNMd for more details. -func (c *Client) ListConfigs(opts ListConfigsOptions) ([]swarm.Config, error) { - path := "/configs?" + queryString(opts) - resp, err := c.do(http.MethodGet, path, doOptions{context: opts.Context}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var configs []swarm.Config - if err := json.NewDecoder(resp.Body).Decode(&configs); err != nil { - return nil, err - } - return configs, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm_node.go b/vendor/github.com/fsouza/go-dockerclient/swarm_node.go deleted file mode 100644 index 8538a167b96..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm_node.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// NoSuchNode is the error returned when a given node does not exist. -type NoSuchNode struct { - ID string - Err error -} - -func (err *NoSuchNode) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such node: " + err.ID -} - -// ListNodesOptions specify parameters to the ListNodes function. -// -// See http://goo.gl/3K4GwU for more details. -type ListNodesOptions struct { - Filters map[string][]string - Context context.Context -} - -// ListNodes returns a slice of nodes matching the given criteria. -// -// See http://goo.gl/3K4GwU for more details. -func (c *Client) ListNodes(opts ListNodesOptions) ([]swarm.Node, error) { - path := "/nodes?" + queryString(opts) - resp, err := c.do(http.MethodGet, path, doOptions{context: opts.Context}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var nodes []swarm.Node - if err := json.NewDecoder(resp.Body).Decode(&nodes); err != nil { - return nil, err - } - return nodes, nil -} - -// InspectNode returns information about a node by its ID. -// -// See http://goo.gl/WjkTOk for more details. -func (c *Client) InspectNode(id string) (*swarm.Node, error) { - resp, err := c.do(http.MethodGet, "/nodes/"+id, doOptions{}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return nil, &NoSuchNode{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var node swarm.Node - if err := json.NewDecoder(resp.Body).Decode(&node); err != nil { - return nil, err - } - return &node, nil -} - -// UpdateNodeOptions specify parameters to the NodeUpdate function. -// -// See http://goo.gl/VPBFgA for more details. -type UpdateNodeOptions struct { - swarm.NodeSpec - Version uint64 - Context context.Context -} - -// UpdateNode updates a node. -// -// See http://goo.gl/VPBFgA for more details. -func (c *Client) UpdateNode(id string, opts UpdateNodeOptions) error { - params := make(url.Values) - params.Set("version", strconv.FormatUint(opts.Version, 10)) - path := "/nodes/" + id + "/update?" + params.Encode() - resp, err := c.do(http.MethodPost, path, doOptions{ - context: opts.Context, - forceJSON: true, - data: opts.NodeSpec, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchNode{ID: id} - } - return err - } - resp.Body.Close() - return nil -} - -// RemoveNodeOptions specify parameters to the RemoveNode function. -// -// See http://goo.gl/0SNvYg for more details. -type RemoveNodeOptions struct { - ID string - Force bool - Context context.Context -} - -// RemoveNode removes a node. -// -// See http://goo.gl/0SNvYg for more details. -func (c *Client) RemoveNode(opts RemoveNodeOptions) error { - params := make(url.Values) - params.Set("force", strconv.FormatBool(opts.Force)) - path := "/nodes/" + opts.ID + "?" + params.Encode() - resp, err := c.do(http.MethodDelete, path, doOptions{context: opts.Context}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchNode{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm_secrets.go b/vendor/github.com/fsouza/go-dockerclient/swarm_secrets.go deleted file mode 100644 index 375e6e5ba37..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm_secrets.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "net/http" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// NoSuchSecret is the error returned when a given secret does not exist. -type NoSuchSecret struct { - ID string - Err error -} - -func (err *NoSuchSecret) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such secret: " + err.ID -} - -// CreateSecretOptions specify parameters to the CreateSecret function. -// -// See https://goo.gl/KrVjHz for more details. -type CreateSecretOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.SecretSpec - Context context.Context -} - -// CreateSecret creates a new secret, returning the secret instance -// or an error in case of failure. -// -// See https://goo.gl/KrVjHz for more details. -func (c *Client) CreateSecret(opts CreateSecretOptions) (*swarm.Secret, error) { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return nil, err - } - path := "/secrets/create?" + queryString(opts) - resp, err := c.do(http.MethodPost, path, doOptions{ - headers: headers, - data: opts.SecretSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var secret swarm.Secret - if err := json.NewDecoder(resp.Body).Decode(&secret); err != nil { - return nil, err - } - return &secret, nil -} - -// RemoveSecretOptions encapsulates options to remove a secret. -// -// See https://goo.gl/Tqrtya for more details. -type RemoveSecretOptions struct { - ID string `qs:"-"` - Context context.Context -} - -// RemoveSecret removes a secret, returning an error in case of failure. -// -// See https://goo.gl/Tqrtya for more details. -func (c *Client) RemoveSecret(opts RemoveSecretOptions) error { - path := "/secrets/" + opts.ID - resp, err := c.do(http.MethodDelete, path, doOptions{context: opts.Context}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchSecret{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} - -// UpdateSecretOptions specify parameters to the UpdateSecret function. -// -// Only label can be updated -// See https://docs.docker.com/engine/api/v1.33/#operation/SecretUpdate -// See https://goo.gl/wu3MmS for more details. -type UpdateSecretOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.SecretSpec - Context context.Context - Version uint64 -} - -// UpdateSecret updates the secret at ID with the options -// -// See https://goo.gl/wu3MmS for more details. -func (c *Client) UpdateSecret(id string, opts UpdateSecretOptions) error { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return err - } - params := make(url.Values) - params.Set("version", strconv.FormatUint(opts.Version, 10)) - resp, err := c.do(http.MethodPost, "/secrets/"+id+"/update?"+params.Encode(), doOptions{ - headers: headers, - data: opts.SecretSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchSecret{ID: id} - } - return err - } - defer resp.Body.Close() - return nil -} - -// InspectSecret returns information about a secret by its ID. -// -// See https://goo.gl/dHmr75 for more details. -func (c *Client) InspectSecret(id string) (*swarm.Secret, error) { - path := "/secrets/" + id - resp, err := c.do(http.MethodGet, path, doOptions{}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return nil, &NoSuchSecret{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var secret swarm.Secret - if err := json.NewDecoder(resp.Body).Decode(&secret); err != nil { - return nil, err - } - return &secret, nil -} - -// ListSecretsOptions specify parameters to the ListSecrets function. -// -// See https://goo.gl/DwvNMd for more details. -type ListSecretsOptions struct { - Filters map[string][]string - Context context.Context -} - -// ListSecrets returns a slice of secrets matching the given criteria. -// -// See https://goo.gl/DwvNMd for more details. -func (c *Client) ListSecrets(opts ListSecretsOptions) ([]swarm.Secret, error) { - path := "/secrets?" + queryString(opts) - resp, err := c.do(http.MethodGet, path, doOptions{context: opts.Context}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var secrets []swarm.Secret - if err := json.NewDecoder(resp.Body).Decode(&secrets); err != nil { - return nil, err - } - return secrets, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm_service.go b/vendor/github.com/fsouza/go-dockerclient/swarm_service.go deleted file mode 100644 index 0d0f007b722..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm_service.go +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "time" - - "github.com/docker/docker/api/types/swarm" -) - -// NoSuchService is the error returned when a given service does not exist. -type NoSuchService struct { - ID string - Err error -} - -func (err *NoSuchService) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such service: " + err.ID -} - -// CreateServiceOptions specify parameters to the CreateService function. -// -// See https://goo.gl/KrVjHz for more details. -type CreateServiceOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.ServiceSpec - Context context.Context -} - -// CreateService creates a new service, returning the service instance -// or an error in case of failure. -// -// See https://goo.gl/KrVjHz for more details. -func (c *Client) CreateService(opts CreateServiceOptions) (*swarm.Service, error) { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return nil, err - } - path := "/services/create?" + queryString(opts) - resp, err := c.do(http.MethodPost, path, doOptions{ - headers: headers, - data: opts.ServiceSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var service swarm.Service - if err := json.NewDecoder(resp.Body).Decode(&service); err != nil { - return nil, err - } - return &service, nil -} - -// RemoveServiceOptions encapsulates options to remove a service. -// -// See https://goo.gl/Tqrtya for more details. -type RemoveServiceOptions struct { - ID string `qs:"-"` - Context context.Context -} - -// RemoveService removes a service, returning an error in case of failure. -// -// See https://goo.gl/Tqrtya for more details. -func (c *Client) RemoveService(opts RemoveServiceOptions) error { - path := "/services/" + opts.ID - resp, err := c.do(http.MethodDelete, path, doOptions{context: opts.Context}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchService{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} - -// UpdateServiceOptions specify parameters to the UpdateService function. -// -// See https://goo.gl/wu3MmS for more details. -type UpdateServiceOptions struct { - Auth AuthConfiguration `qs:"-"` - swarm.ServiceSpec `qs:"-"` - Context context.Context - Version uint64 - Rollback string -} - -// UpdateService updates the service at ID with the options -// -// See https://goo.gl/wu3MmS for more details. -func (c *Client) UpdateService(id string, opts UpdateServiceOptions) error { - headers, err := headersWithAuth(opts.Auth) - if err != nil { - return err - } - resp, err := c.do(http.MethodPost, "/services/"+id+"/update?"+queryString(opts), doOptions{ - headers: headers, - data: opts.ServiceSpec, - forceJSON: true, - context: opts.Context, - }) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return &NoSuchService{ID: id} - } - return err - } - defer resp.Body.Close() - return nil -} - -// InspectService returns information about a service by its ID. -// -// See https://goo.gl/dHmr75 for more details. -func (c *Client) InspectService(id string) (*swarm.Service, error) { - path := "/services/" + id - resp, err := c.do(http.MethodGet, path, doOptions{}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return nil, &NoSuchService{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var service swarm.Service - if err := json.NewDecoder(resp.Body).Decode(&service); err != nil { - return nil, err - } - return &service, nil -} - -// ListServicesOptions specify parameters to the ListServices function. -// -// See https://goo.gl/DwvNMd for more details. -type ListServicesOptions struct { - Filters map[string][]string - Status bool - Context context.Context -} - -// ListServices returns a slice of services matching the given criteria. -// -// See https://goo.gl/DwvNMd for more details. -func (c *Client) ListServices(opts ListServicesOptions) ([]swarm.Service, error) { - path := "/services?" + queryString(opts) - resp, err := c.do(http.MethodGet, path, doOptions{context: opts.Context}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var services []swarm.Service - if err := json.NewDecoder(resp.Body).Decode(&services); err != nil { - return nil, err - } - return services, nil -} - -// LogsServiceOptions represents the set of options used when getting logs from a -// service. -type LogsServiceOptions struct { - Context context.Context - Service string `qs:"-"` - OutputStream io.Writer `qs:"-"` - ErrorStream io.Writer `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` - Tail string - Since int64 - - // Use raw terminal? Usually true when the container contains a TTY. - RawTerminal bool `qs:"-"` - Follow bool - Stdout bool - Stderr bool - Timestamps bool - Details bool -} - -// GetServiceLogs gets stdout and stderr logs from the specified service. -// -// When LogsServiceOptions.RawTerminal is set to false, go-dockerclient will multiplex -// the streams and send the containers stdout to LogsServiceOptions.OutputStream, and -// stderr to LogsServiceOptions.ErrorStream. -// -// When LogsServiceOptions.RawTerminal is true, callers will get the raw stream on -// LogsServiceOptions.OutputStream. -func (c *Client) GetServiceLogs(opts LogsServiceOptions) error { - if opts.Service == "" { - return &NoSuchService{ID: opts.Service} - } - if opts.Tail == "" { - opts.Tail = "all" - } - path := "/services/" + opts.Service + "/logs?" + queryString(opts) - return c.stream(http.MethodGet, path, streamOptions{ - setRawTerminal: opts.RawTerminal, - stdout: opts.OutputStream, - stderr: opts.ErrorStream, - inactivityTimeout: opts.InactivityTimeout, - context: opts.Context, - }) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/swarm_task.go b/vendor/github.com/fsouza/go-dockerclient/swarm_task.go deleted file mode 100644 index 9321368d3f3..00000000000 --- a/vendor/github.com/fsouza/go-dockerclient/swarm_task.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "context" - "encoding/json" - "errors" - "net/http" - - "github.com/docker/docker/api/types/swarm" -) - -// NoSuchTask is the error returned when a given task does not exist. -type NoSuchTask struct { - ID string - Err error -} - -func (err *NoSuchTask) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such task: " + err.ID -} - -// ListTasksOptions specify parameters to the ListTasks function. -// -// See http://goo.gl/rByLzw for more details. -type ListTasksOptions struct { - Filters map[string][]string - Context context.Context -} - -// ListTasks returns a slice of tasks matching the given criteria. -// -// See http://goo.gl/rByLzw for more details. -func (c *Client) ListTasks(opts ListTasksOptions) ([]swarm.Task, error) { - path := "/tasks?" + queryString(opts) - resp, err := c.do(http.MethodGet, path, doOptions{context: opts.Context}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var tasks []swarm.Task - if err := json.NewDecoder(resp.Body).Decode(&tasks); err != nil { - return nil, err - } - return tasks, nil -} - -// InspectTask returns information about a task by its ID. -// -// See http://goo.gl/kyziuq for more details. -func (c *Client) InspectTask(id string) (*swarm.Task, error) { - resp, err := c.do(http.MethodGet, "/tasks/"+id, doOptions{}) - if err != nil { - var e *Error - if errors.As(err, &e) && e.Status == http.StatusNotFound { - return nil, &NoSuchTask{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var task swarm.Task - if err := json.NewDecoder(resp.Body).Decode(&task); err != nil { - return nil, err - } - return &task, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/tar.go b/vendor/github.com/fsouza/go-dockerclient/tar.go index 0d40c644abd..434a5b3d6af 100644 --- a/vendor/github.com/fsouza/go-dockerclient/tar.go +++ b/vendor/github.com/fsouza/go-dockerclient/tar.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/moby/go-archive" + "github.com/moby/go-archive/compression" "github.com/moby/patternmatcher" ) @@ -59,7 +60,7 @@ func createTarStream(srcPath, dockerfilePath string) (io.ReadCloser, error) { tarOpts := &archive.TarOptions{ ExcludePatterns: excludes, IncludeFiles: includes, - Compression: archive.Uncompressed, + Compression: compression.None, NoLchown: true, } return archive.TarWithOptions(srcPath, tarOpts) diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/config.go b/vendor/github.com/google/go-containerregistry/pkg/v1/config.go index 960c93b5f41..b62d8482691 100644 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/config.go +++ b/vendor/github.com/google/go-containerregistry/pkg/v1/config.go @@ -27,10 +27,11 @@ import ( // docker_version and os.version are not part of the spec but included // for backwards compatibility. type ConfigFile struct { - Architecture string `json:"architecture"` - Author string `json:"author,omitempty"` - Container string `json:"container,omitempty"` - Created Time `json:"created,omitempty"` + Architecture string `json:"architecture"` + Author string `json:"author,omitempty"` + Container string `json:"container,omitempty"` + Created Time `json:"created,omitempty"` + // Deprecated: This field is deprecated and will be removed in the next release. DockerVersion string `json:"docker_version,omitempty"` History []History `json:"history,omitempty"` OS string `json:"os"` diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/directives.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/directives.go index b757e7548de..6638170cdb1 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/directives.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/directives.go @@ -4,9 +4,10 @@ import ( "bufio" "bytes" "encoding/json" - "fmt" "regexp" "strings" + "sync" + "unicode" "github.com/pkg/errors" ) @@ -32,14 +33,18 @@ type Directive struct { // DirectiveParser is a parser for Dockerfile directives that enforces the // quirks of the directive parser. type DirectiveParser struct { - line int - regexp *regexp.Regexp - seen map[string]struct{} - done bool + line int + comment *string + seen map[string]struct{} + done bool } -func (d *DirectiveParser) setComment(comment string) { - d.regexp = regexp.MustCompile(fmt.Sprintf(`^%s\s*([a-zA-Z][a-zA-Z0-9]*)\s*=\s*(.+?)\s*$`, comment)) +var directiveRegexp = sync.OnceValue(func() *regexp.Regexp { + return regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9]*)\s*=\s*(.+?)\s*$`) +}) + +func (d *DirectiveParser) SetComment(comment string) { + d.comment = &comment } func (d *DirectiveParser) ParseLine(line []byte) (*Directive, error) { @@ -47,11 +52,18 @@ func (d *DirectiveParser) ParseLine(line []byte) (*Directive, error) { if d.done { return nil, nil } - if d.regexp == nil { - d.setComment("#") + if d.comment == nil { + d.SetComment("#") + } + + line, ok := bytes.CutPrefix(line, []byte(*d.comment)) + if !ok { + d.done = true + return nil, nil } + line = bytes.TrimLeftFunc(line, unicode.IsSpace) - match := d.regexp.FindSubmatch(line) + match := directiveRegexp().FindSubmatch(line) if len(match) == 0 { d.done = true return nil, nil @@ -142,7 +154,7 @@ func parseDirective(key string, dt []byte, anyFormat bool) (string, string, []Ra // use directive with different comment prefix, and search for //key= directiveParser = DirectiveParser{line: line} - directiveParser.setComment("//") + directiveParser.SetComment("//") if syntax, cmdline, loc, ok := detectDirectiveFromParser(key, dt, directiveParser); ok { return syntax, cmdline, loc, true } diff --git a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go index 2f0da0222ac..209562d35f6 100644 --- a/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go +++ b/vendor/github.com/moby/buildkit/frontend/dockerfile/parser/parser.go @@ -49,25 +49,29 @@ func (node *Node) Location() []Range { // Dump dumps the AST defined by `node` as a list of sexps. // Returns a string suitable for printing. func (node *Node) Dump() string { - str := strings.ToLower(node.Value) + var str strings.Builder + str.WriteString(strings.ToLower(node.Value)) if len(node.Flags) > 0 { - str += fmt.Sprintf(" %q", node.Flags) + fmt.Fprintf(&str, " %q", node.Flags) } for _, n := range node.Children { - str += "(" + n.Dump() + ")\n" + str.WriteByte('(') + str.WriteString(n.Dump()) + str.WriteString(")\n") } for n := node.Next; n != nil; n = n.Next { + str.WriteByte(' ') if len(n.Children) > 0 { - str += " " + n.Dump() + str.WriteString(n.Dump()) } else { - str += " " + strconv.Quote(n.Value) + str.WriteString(strconv.Quote(n.Value)) } } - return strings.TrimSpace(str) + return strings.TrimSpace(str.String()) } func (node *Node) lines(start, end int) { @@ -367,6 +371,8 @@ func Parse(rwc io.Reader) (*Result, error) { for _, heredoc := range heredocs { terminator := []byte(heredoc.Name) terminated := false + var content strings.Builder + content.WriteString(heredoc.Content) for scanner.Scan() { bytesRead := scanner.Bytes() currentLine++ @@ -379,12 +385,13 @@ func Parse(rwc io.Reader) (*Result, error) { terminated = true break } - heredoc.Content += string(bytesRead) + content.Write(bytesRead) } if !terminated { return nil, withLocation(errors.New("unterminated heredoc"), startLine, currentLine) } + heredoc.Content = content.String() child.Heredocs = append(child.Heredocs, heredoc) } } diff --git a/vendor/github.com/moby/buildkit/util/stack/stack.pb.go b/vendor/github.com/moby/buildkit/util/stack/stack.pb.go index 583565672bb..103e662ff35 100644 --- a/vendor/github.com/moby/buildkit/util/stack/stack.pb.go +++ b/vendor/github.com/moby/buildkit/util/stack/stack.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.10 +// protoc-gen-go v1.36.11 // protoc v3.11.4 // source: github.com/moby/buildkit/util/stack/stack.proto diff --git a/vendor/github.com/moby/go-archive/archive.go b/vendor/github.com/moby/go-archive/archive.go index 7a105aef189..8dce2e6e2af 100644 --- a/vendor/github.com/moby/go-archive/archive.go +++ b/vendor/github.com/moby/go-archive/archive.go @@ -36,10 +36,6 @@ import ( const ImpliedDirectoryMode = 0o755 type ( - // Compression is the state represents if compressed or not. - // - // Deprecated: use [compression.Compression]. - Compression = compression.Compression // WhiteoutFormat is the format of whiteouts unpacked WhiteoutFormat int @@ -95,14 +91,6 @@ func NewDefaultArchiver() *Archiver { // in order for the test to pass. type breakoutError error -const ( - Uncompressed = compression.None // Deprecated: use [compression.None]. - Bzip2 = compression.Bzip2 // Deprecated: use [compression.Bzip2]. - Gzip = compression.Gzip // Deprecated: use [compression.Gzip]. - Xz = compression.Xz // Deprecated: use [compression.Xz]. - Zstd = compression.Zstd // Deprecated: use [compression.Zstd]. -) - const ( AUFSWhiteoutFormat WhiteoutFormat = 0 // AUFSWhiteoutFormat is the default format for whiteouts OverlayWhiteoutFormat WhiteoutFormat = 1 // OverlayWhiteoutFormat formats whiteout according to the overlay standard. @@ -126,27 +114,6 @@ func IsArchivePath(path string) bool { return err == nil } -// DetectCompression detects the compression algorithm of the source. -// -// Deprecated: use [compression.Detect]. -func DetectCompression(source []byte) compression.Compression { - return compression.Detect(source) -} - -// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive. -// -// Deprecated: use [compression.DecompressStream]. -func DecompressStream(archive io.Reader) (io.ReadCloser, error) { - return compression.DecompressStream(archive) -} - -// CompressStream compresses the dest with specified compression algorithm. -// -// Deprecated: use [compression.CompressStream]. -func CompressStream(dest io.Writer, comp compression.Compression) (io.WriteCloser, error) { - return compression.CompressStream(dest, comp) -} - // TarModifierFunc is a function that can be passed to ReplaceFileTarWrapper to // modify the contents or header of an entry in the archive. If the file already // exists in the archive the TarModifierFunc will be called with the Header and @@ -235,13 +202,6 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi return pipeReader } -// FileInfoHeaderNoLookups creates a partially-populated tar.Header from fi. -// -// Deprecated: use [tarheader.FileInfoHeaderNoLookups]. -func FileInfoHeaderNoLookups(fi os.FileInfo, link string) (*tar.Header, error) { - return tarheader.FileInfoHeaderNoLookups(fi, link) -} - // FileInfoHeader creates a populated Header from fi. // // Compared to the archive/tar package, this function fills in less information diff --git a/vendor/github.com/moby/go-archive/xattr_supported_unix.go b/vendor/github.com/moby/go-archive/xattr_supported_unix.go index 4d8824158ea..58a03e4a637 100644 --- a/vendor/github.com/moby/go-archive/xattr_supported_unix.go +++ b/vendor/github.com/moby/go-archive/xattr_supported_unix.go @@ -1,4 +1,4 @@ -//go:build !linux && !windows +//go:build darwin || freebsd || netbsd package archive diff --git a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/moby/moby/api/pkg/stdcopy/stdcopy.go similarity index 50% rename from vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go rename to vendor/github.com/moby/moby/api/pkg/stdcopy/stdcopy.go index 611432a6261..948c6b6755d 100644 --- a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go +++ b/vendor/github.com/moby/moby/api/pkg/stdcopy/stdcopy.go @@ -1,12 +1,10 @@ package stdcopy import ( - "bytes" "encoding/binary" "errors" "fmt" "io" - "sync" ) // StdType is the type of standard stream @@ -14,16 +12,13 @@ import ( type StdType byte const ( - // Stdin represents standard input stream type. - Stdin StdType = iota - // Stdout represents standard output stream type. - Stdout - // Stderr represents standard error steam type. - Stderr - // Systemerr represents errors originating from the system that make it - // into the multiplexed stream. - Systemerr + Stdin StdType = 0 // Stdin represents standard input stream. It is present for completeness and should NOT be used. When reading the stream with [StdCopy] it is output on [Stdout]. + Stdout StdType = 1 // Stdout represents standard output stream. + Stderr StdType = 2 // Stderr represents standard error steam. + Systemerr StdType = 3 // Systemerr represents errors originating from the system. When reading the stream with [StdCopy] it is returned as an error. +) +const ( stdWriterPrefixLen = 8 stdWriterFdIndex = 0 stdWriterSizeIndex = 4 @@ -31,67 +26,28 @@ const ( startingBufLen = 32*1024 + stdWriterPrefixLen + 1 ) -var bufPool = &sync.Pool{New: func() interface{} { return bytes.NewBuffer(nil) }} - -// stdWriter is wrapper of io.Writer with extra customized info. -type stdWriter struct { - io.Writer - prefix byte -} - -// Write sends the buffer to the underneath writer. -// It inserts the prefix header before the buffer, -// so stdcopy.StdCopy knows where to multiplex the output. -// It makes stdWriter to implement io.Writer. -func (w *stdWriter) Write(p []byte) (int, error) { - if w == nil || w.Writer == nil { - return 0, errors.New("writer not instantiated") - } - if p == nil { - return 0, nil - } - - header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix} - binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p))) - buf := bufPool.Get().(*bytes.Buffer) - buf.Write(header[:]) - buf.Write(p) - - n, err := w.Writer.Write(buf.Bytes()) - n -= stdWriterPrefixLen - if n < 0 { - n = 0 - } - - buf.Reset() - bufPool.Put(buf) - return n, err -} - -// NewStdWriter instantiates a new Writer. -// Everything written to it will be encapsulated using a custom format, -// and written to the underlying `w` stream. -// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. -// `t` indicates the id of the stream to encapsulate. -// It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. -func NewStdWriter(w io.Writer, t StdType) io.Writer { - return &stdWriter{ - Writer: w, - prefix: byte(t), - } -} - -// StdCopy is a modified version of io.Copy. +// StdCopy is a modified version of [io.Copy] to de-multiplex messages +// from "multiplexedSource" and copy them to destination streams +// "destOut" and "destErr". +// +// StdCopy demultiplexes "multiplexedSource", assuming that it contains +// two streams, previously multiplexed using a writer created with +// [NewStdWriter]. // -// StdCopy will demultiplex `src`, assuming that it contains two streams, -// previously multiplexed together using a StdWriter instance. -// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. +// As it reads from "multiplexedSource", StdCopy writes [Stdout] messages +// to "destOut", and [Stderr] message to "destErr]. For backward-compatibility, +// [Stdin] messages are output to "destOut". The [Systemerr] stream provides +// errors produced by the daemon. It is returned as an error, and terminates +// processing the stream. // -// StdCopy will read until it hits EOF on `src`. It will then return a nil error. -// In other words: if `err` is non nil, it indicates a real underlying error. +// StdCopy it reads until it hits [io.EOF] on "multiplexedSource", after +// which it returns a nil error. In other words: any error returned indicates +// a real underlying error, which may be when an unknown [StdType] stream +// is received. // -// `written` will hold the total number of bytes written to `dstout` and `dsterr`. -func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, _ error) { +// The "written" return holds the total number of bytes written to "destOut" +// and "destErr" combined. +func StdCopy(destOut, destErr io.Writer, multiplexedSource io.Reader) (written int64, _ error) { var ( buf = make([]byte, startingBufLen) bufLen = len(buf) @@ -105,7 +61,7 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, _ error) { // Make sure we have at least a full header for nr < stdWriterPrefixLen { var nr2 int - nr2, err = src.Read(buf[nr:]) + nr2, err = multiplexedSource.Read(buf[nr:]) nr += nr2 if errors.Is(err, io.EOF) { if nr < stdWriterPrefixLen { @@ -118,24 +74,24 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, _ error) { } } - stream := StdType(buf[stdWriterFdIndex]) // Check the first byte to know where to write + stream := StdType(buf[stdWriterFdIndex]) switch stream { case Stdin: fallthrough case Stdout: // Write on stdout - out = dstout + out = destOut case Stderr: // Write on stderr - out = dsterr + out = destErr case Systemerr: // If we're on Systemerr, we won't write anywhere. // NB: if this code changes later, make sure you don't try to write // to outstream if Systemerr is the stream out = nil default: - return 0, fmt.Errorf("Unrecognized input header: %d", buf[stdWriterFdIndex]) + return 0, fmt.Errorf("unrecognized stream: %d", stream) } // Retrieve the size of the frame @@ -151,7 +107,7 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, _ error) { // While the amount of bytes read is less than the size of the frame + header, we keep reading for nr < frameSize+stdWriterPrefixLen { var nr2 int - nr2, err = src.Read(buf[nr:]) + nr2, err = multiplexedSource.Read(buf[nr:]) nr += nr2 if errors.Is(err, io.EOF) { if nr < frameSize+stdWriterPrefixLen { diff --git a/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go new file mode 100644 index 00000000000..0ae74fe7252 --- /dev/null +++ b/vendor/github.com/moby/moby/client/pkg/jsonmessage/jsonmessage.go @@ -0,0 +1,245 @@ +package jsonmessage + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "iter" + "strings" + "time" + + "github.com/docker/go-units" + "github.com/moby/moby/api/types/jsonstream" + "github.com/moby/term" +) + +var timeNow = time.Now // For overriding in tests. + +// RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to +// ensure the formatted time is always the same number of characters. +const RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" + +func RenderTUIProgress(p jsonstream.Progress, width uint16) string { + var ( + pbBox string + numbersBox string + ) + if p.Current <= 0 && p.Total <= 0 { + return "" + } + if p.Total <= 0 { + switch p.Units { + case "": + return fmt.Sprintf("%8v", units.HumanSize(float64(p.Current))) + default: + return fmt.Sprintf("%d %s", p.Current, p.Units) + } + } + + percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 + if percentage > 50 { + percentage = 50 + } + if width > 110 { + // this number can't be negative gh#7136 + numSpaces := 0 + if 50-percentage > 0 { + numSpaces = 50 - percentage + } + pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) + } + + switch { + case p.HideCounts: + case p.Units == "": // no units, use bytes + current := units.HumanSize(float64(p.Current)) + total := units.HumanSize(float64(p.Total)) + + numbersBox = fmt.Sprintf("%8v/%v", current, total) + + if p.Current > p.Total { + // remove total display if the reported current is wonky. + numbersBox = fmt.Sprintf("%8v", current) + } + default: + numbersBox = fmt.Sprintf("%d/%d %s", p.Current, p.Total, p.Units) + + if p.Current > p.Total { + // remove total display if the reported current is wonky. + numbersBox = fmt.Sprintf("%d %s", p.Current, p.Units) + } + } + + // Show approximation of remaining time if there's enough width. + var timeLeftBox string + if width > 50 { + if p.Current > 0 && p.Start > 0 && percentage < 50 { + fromStart := timeNow().UTC().Sub(time.Unix(p.Start, 0)) + perEntry := fromStart / time.Duration(p.Current) + left := time.Duration(p.Total-p.Current) * perEntry + timeLeftBox = " " + left.Round(time.Second).String() + } + } + return pbBox + numbersBox + timeLeftBox +} + +// We can probably use [aec.EmptyBuilder] for managing the output, but +// currently we're doing it all manually, so defining some consts for +// the basics we use. +// +// [aec.EmptyBuilder]: https://pkg.go.dev/github.com/morikuni/aec#EmptyBuilder +const ( + ansiEraseLine = "\x1b[2K" // Erase entire line + ansiCursorUpFmt = "\x1b[%dA" // Move cursor up N lines + ansiCursorDownFmt = "\x1b[%dB" // Move cursor down N lines +) + +func clearLine(out io.Writer) { + _, _ = out.Write([]byte(ansiEraseLine)) +} + +func cursorUp(out io.Writer, l uint) { + if l == 0 { + return + } + _, _ = fmt.Fprintf(out, ansiCursorUpFmt, l) +} + +func cursorDown(out io.Writer, l uint) { + if l == 0 { + return + } + _, _ = fmt.Fprintf(out, ansiCursorDownFmt, l) +} + +// Display prints the JSONMessage to out. If isTerminal is true, it erases +// the entire current line when displaying the progressbar. It returns an +// error if the [JSONMessage.Error] field is non-nil. +func Display(jm jsonstream.Message, out io.Writer, isTerminal bool, width uint16) error { + if jm.Error != nil { + return jm.Error + } + var endl string + if isTerminal && jm.Stream == "" && jm.Progress != nil { + clearLine(out) + endl = "\r" + _, _ = fmt.Fprint(out, endl) + } else if jm.Progress != nil && (jm.Progress.Current > 0 || jm.Progress.Total > 0) { // disable progressbar in non-terminal + return nil + } + if jm.ID != "" { + _, _ = fmt.Fprintf(out, "%s: ", jm.ID) + } + if jm.Progress != nil && isTerminal { + if width == 0 { + width = 200 + } + _, _ = fmt.Fprintf(out, "%s %s%s", jm.Status, RenderTUIProgress(*jm.Progress, width), endl) + } else if jm.Stream != "" { + _, _ = fmt.Fprintf(out, "%s%s", jm.Stream, endl) + } else { + _, _ = fmt.Fprintf(out, "%s%s\n", jm.Status, endl) + } + return nil +} + +type JSONMessagesStream = iter.Seq2[jsonstream.Message, error] + +// DisplayJSONMessagesStream reads a JSON message stream from in, and writes +// each [JSONMessage] to out. +// see DisplayJSONMessages for details +func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(jsonstream.Message)) error { + dec := json.NewDecoder(in) + f := func(yield func(jsonstream.Message, error) bool) { + for { + var jm jsonstream.Message + err := dec.Decode(&jm) + if errors.Is(err, io.EOF) { + break + } + if !yield(jm, err) { + return + } + } + } + + return DisplayJSONMessages(f, out, terminalFd, isTerminal, auxCallback) +} + +// DisplayJSONMessages writes each [JSONMessage] from stream to out. +// It returns an error if an invalid JSONMessage is received, or if +// a JSONMessage containers a non-zero [JSONMessage.Error]. +// +// Presentation of the JSONMessage depends on whether a terminal is attached, +// and on the terminal width. Progress bars ([JSONProgress]) are suppressed +// on narrower terminals (< 110 characters). +// +// - isTerminal describes if out is a terminal, in which case it prints +// a newline ("\n") at the end of each line and moves the cursor while +// displaying. +// - terminalFd is the fd of the current terminal (if any), and used +// to get the terminal width. +// - auxCallback allows handling the [JSONMessage.Aux] field. It is +// called if a JSONMessage contains an Aux field, in which case +// DisplayJSONMessagesStream does not present the JSONMessage. +func DisplayJSONMessages(messages iter.Seq2[jsonstream.Message, error], out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(jsonstream.Message)) error { + ids := make(map[string]uint) + var width uint16 = 200 + if isTerminal { + ws, err := term.GetWinsize(terminalFd) + if err == nil { + width = ws.Width + } + } + + for jm, err := range messages { + var diff uint + if err != nil { + return err + } + + if jm.Aux != nil { + if auxCallback != nil { + auxCallback(jm) + } + continue + } + + if jm.ID != "" && jm.Progress != nil { + line, ok := ids[jm.ID] + if !ok { + // NOTE: This approach of using len(id) to + // figure out the number of lines of history + // only works as long as we clear the history + // when we output something that's not + // accounted for in the map, such as a line + // with no ID. + line = uint(len(ids)) + ids[jm.ID] = line + if isTerminal { + _, _ = fmt.Fprintf(out, "\n") + } + } + diff = uint(len(ids)) - line + if isTerminal { + cursorUp(out, diff) + } + } else { + // When outputting something that isn't progress + // output, clear the history of previous lines. We + // don't want progress entries from some previous + // operation to be updated (for example, pull -a + // with multiple tags). + ids = make(map[string]uint) + } + err := Display(jm, out, isTerminal, width) + if jm.ID != "" && isTerminal { + cursorDown(out, diff) + } + if err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/moby/moby/v2/AUTHORS similarity index 99% rename from vendor/github.com/docker/docker/AUTHORS rename to vendor/github.com/moby/moby/v2/AUTHORS index c7c649471c2..cb9bc376936 100644 --- a/vendor/github.com/docker/docker/AUTHORS +++ b/vendor/github.com/moby/moby/v2/AUTHORS @@ -23,6 +23,7 @@ Abhishek Chanda Abhishek Sharma Abin Shahab Abirdcfly +Abubacarr Ceesay Ada Mancini Adam Avilla Adam Dobrawy @@ -49,6 +50,7 @@ Adrian Mouat Adrian Oprea Adrien Folie Adrien Gallouët +Adrien Pompée Ahmed Kamal Ahmet Alp Balkan Aidan Feldman @@ -81,6 +83,7 @@ Aleksandrs Fadins Alena Prokharchyk Alessandro Boch Alessio Biancalana +Alessio Perugini Alex Chan Alex Chen Alex Coventry @@ -171,6 +174,7 @@ Andrew Po Andrew Weiss Andrew Williams Andrews Medina +Andrey Epifanov Andrey Kolomentsev Andrey Petrov Andrey Stolbovsky @@ -200,6 +204,7 @@ Anthon van der Neut Anthony Baire Anthony Bishopric Anthony Dahanne +Anthony Nandaa Anthony Sottile Anton Löfgren Anton Nikitin @@ -345,6 +350,7 @@ Carlos Alexandro Becker Carlos de Paula Carlos Sanchez Carol Fager-Higgins +carsontham Cary Casey Bisson Catalin Pirvu @@ -871,6 +877,7 @@ haining.cao Hakan Özler Hamish Hutchings Hannes Ljungberg +Hannes Ortmeier Hans Kristian Flaatten Hans Rødtang Hao Shu Wei @@ -890,6 +897,7 @@ heartlock <21521209@zju.edu.cn> Hector Castro Helen Xie Henning Sprang +Henry Wang Hiroshi Hatake Hiroyuki Sasagawa Hobofan @@ -1089,6 +1097,7 @@ Jintao Zhang Jiri Appl Jiri Popelka Jiuyue Ma +Jiří Moravčík Jiří Župka jjimbo137 <115816493+jjimbo137@users.noreply.github.com> Joakim Roubert @@ -1320,6 +1329,7 @@ Leandro Motta Barros Leandro Siqueira Lee Calcote Lee Chao <932819864@qq.com> +Lee Gaines Lee, Meng-Han Lei Gong Lei Jitang @@ -1407,6 +1417,7 @@ Manuel Meurer Manuel Rüger Manuel Woelker mapk0y +Marat Abrarov Marat Radchenko Marc Abramowitz Marc Kuo @@ -1421,6 +1432,7 @@ Marcus Linke Marcus Martins Marcus Ramberg Marek Goldmann +Maria Glushenok Marian Marinov Marianna Tessel Mario Loriedo @@ -1504,6 +1516,7 @@ Maxime Petazzoni Maximiliano Maccanti Maxwell Meaglith Ma +Medhy DOHOU <52136144+PowerPixel@users.noreply.github.com> meejah Megan Kostick Mehul Kar @@ -1604,6 +1617,7 @@ Moysés Borges mrfly Mrunal Patel Muayyad Alsadi +Muhammad Daffa Dinaya Muhammad Zohaib Aslam Mustafa Akın Muthukumar R @@ -2023,12 +2037,14 @@ Sergey Alekseev Sergey Evstifeev Sergii Kabashniuk Sergio Lopez +Serhan Tutar Serhat Gülçiçek Serhii Nakon SeungUkLee Sevki Hasirci Shane Canon Shane da Silva +Shang Mu Shaun Kaasten Shaun Thompson shaunol @@ -2120,6 +2136,7 @@ Stéphane Este-Gracias Stig Larsson Su Wang Subhajit Ghosh +Sudheendra Gopinath Sujith Haridasan Sun Gengze <690388648@qq.com> Sun Jianbo @@ -2176,6 +2193,7 @@ Thomas Tanaka Thomas Texier Ti Zhou Tiago Seabra +Tiago Teixeira Tianon Gravi Tianyi Wang Tibor Vass @@ -2276,6 +2294,7 @@ Valentin Kulesh vanderliang Velko Ivanov Veres Lajos +Viacheslav Gagara Victor Algaze Victor Coisne Victor Costan @@ -2492,5 +2511,6 @@ Zunayed Ali 徐俊杰 慕陶 搏通 +纯真 <38834411+chunzhennn@users.noreply.github.com> 黄艳红00139573 정재영 diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/moby/moby/v2/LICENSE similarity index 100% rename from vendor/github.com/docker/docker/LICENSE rename to vendor/github.com/moby/moby/v2/LICENSE diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/moby/moby/v2/NOTICE similarity index 100% rename from vendor/github.com/docker/docker/NOTICE rename to vendor/github.com/moby/moby/v2/NOTICE diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir.go b/vendor/github.com/moby/moby/v2/pkg/homedir/homedir.go similarity index 100% rename from vendor/github.com/docker/docker/pkg/homedir/homedir.go rename to vendor/github.com/moby/moby/v2/pkg/homedir/homedir.go diff --git a/vendor/github.com/moby/moby/v2/pkg/homedir/homedir_linux.go b/vendor/github.com/moby/moby/v2/pkg/homedir/homedir_linux.go new file mode 100644 index 00000000000..aff85fadc7b --- /dev/null +++ b/vendor/github.com/moby/moby/v2/pkg/homedir/homedir_linux.go @@ -0,0 +1,125 @@ +package homedir + +import ( + "errors" + "os" + "path/filepath" + "strings" +) + +// GetRuntimeDir returns [XDG_RUNTIME_DIR]. It returns a non-nil error if +// XDG_RUNTIME_DIR is not set. XDG_RUNTIME_DIR is typically configured via +// [pam_systemd]. +// +// [XDG_RUNTIME_DIR]: https://specifications.freedesktop.org/basedir/0.8/#variables +// [pam_systemd]: https://man7.org/linux/man-pages/man8/pam_systemd.8.html +func GetRuntimeDir() (string, error) { + if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" { + return xdgRuntimeDir, nil + } + return "", errors.New("could not get XDG_RUNTIME_DIR") +} + +// StickRuntimeDirContents sets the sticky bit on files that are under +// [XDG_RUNTIME_DIR], so that the files won't be periodically removed by the +// system. +// +// It returns a slice of sticked files as absolute paths. The list of files may +// be empty (nil) if XDG_RUNTIME_DIR is not set, in which case no error is returned. +// StickyRuntimeDir produces an error when failing to resolve the absolute path +// for the returned files. +// +// [XDG_RUNTIME_DIR]: https://specifications.freedesktop.org/basedir/0.8/#variables +func StickRuntimeDirContents(files []string) ([]string, error) { + runtimeDir, err := GetRuntimeDir() + if err != nil { + // ignore error if runtimeDir is empty + return nil, nil + } + runtimeDir, err = filepath.Abs(runtimeDir) + if err != nil { + return nil, err + } + var sticked []string + for _, f := range files { + f, err = filepath.Abs(f) + if err != nil { + return sticked, err + } + if strings.HasPrefix(f, runtimeDir+"/") { + if err = stick(f); err != nil { + return sticked, err + } + sticked = append(sticked, f) + } + } + return sticked, nil +} + +func stick(f string) error { + st, err := os.Stat(f) + if err != nil { + return err + } + m := st.Mode() + m |= os.ModeSticky + return os.Chmod(f, m) +} + +// GetDataHome returns [XDG_DATA_HOME] or $HOME/.local/share and a nil error if +// [XDG_DATA_HOME] is not set. If neither HOME nor XDG_DATA_HOME are set, +// [getpwent(3)] is consulted to determine the users home directory. +// +// [XDG_DATA_HOME]: https://specifications.freedesktop.org/basedir/0.8/#variables +// [getpwent(3)]: https://man7.org/linux/man-pages/man3/getpwent.3.html +func GetDataHome() (string, error) { + if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { + return xdgDataHome, nil + } + home := Get() + if home == "" { + return "", errors.New("could not get either XDG_DATA_HOME or HOME") + } + return filepath.Join(home, ".local", "share"), nil +} + +// GetConfigHome returns [XDG_CONFIG_HOME] or $HOME/.config and a nil error if +// XDG_CONFIG_HOME is not set. If neither HOME nor XDG_CONFIG_HOME are set, +// [getpwent(3)] is consulted to determine the users home directory. +// +// [XDG_CONFIG_HOME]: https://specifications.freedesktop.org/basedir/0.8/#variables +// [getpwent(3)]: https://man7.org/linux/man-pages/man3/getpwent.3.html +func GetConfigHome() (string, error) { + if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { + return xdgConfigHome, nil + } + home := Get() + if home == "" { + return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") + } + return filepath.Join(home, ".config"), nil +} + +// GetLibHome returns $HOME/.local/lib. If HOME is not set, [getpwent(3)] is +// consulted to determine the users home directory. +// +// [getpwent(3)]: https://man7.org/linux/man-pages/man3/getpwent.3.html +func GetLibHome() (string, error) { + home := Get() + if home == "" { + return "", errors.New("could not get HOME") + } + return filepath.Join(home, ".local/lib"), nil +} + +// GetLibexecHome returns $HOME/.local/libexec. If HOME is not set, +// [getpwent(3)] is consulted to determine the users home directory. +// +// [getpwent(3)]: https://man7.org/linux/man-pages/man3/getpwent.3.html +func GetLibexecHome() (string, error) { + home := Get() + if home == "" { + return "", errors.New("could not get HOME") + } + return filepath.Join(home, ".local/libexec"), nil +} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go b/vendor/github.com/moby/moby/v2/pkg/homedir/homedir_others.go similarity index 84% rename from vendor/github.com/docker/docker/pkg/homedir/homedir_others.go rename to vendor/github.com/moby/moby/v2/pkg/homedir/homedir_others.go index 1e41e6aab51..ad4df82f7be 100644 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go +++ b/vendor/github.com/moby/moby/v2/pkg/homedir/homedir_others.go @@ -30,3 +30,8 @@ func GetConfigHome() (string, error) { func GetLibHome() (string, error) { return "", errors.New("homedir.GetLibHome() is not supported on this system") } + +// GetLibexecHome is unsupported on non-linux system. +func GetLibexecHome() (string, error) { + return "", errors.New("homedir.GetLibexecHome() is not supported on this system") +} diff --git a/vendor/github.com/morikuni/aec/LICENSE b/vendor/github.com/morikuni/aec/LICENSE deleted file mode 100644 index 1c264016419..00000000000 --- a/vendor/github.com/morikuni/aec/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Taihei Morikuni - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/morikuni/aec/README.md b/vendor/github.com/morikuni/aec/README.md deleted file mode 100644 index 3cbc4343ee2..00000000000 --- a/vendor/github.com/morikuni/aec/README.md +++ /dev/null @@ -1,178 +0,0 @@ -# aec - -[![GoDoc](https://godoc.org/github.com/morikuni/aec?status.svg)](https://godoc.org/github.com/morikuni/aec) - -Go wrapper for ANSI escape code. - -## Install - -```bash -go get github.com/morikuni/aec -``` - -## Features - -ANSI escape codes depend on terminal environment. -Some of these features may not work. -Check supported Font-Style/Font-Color features with [checkansi](./checkansi). - -[Wikipedia](https://en.wikipedia.org/wiki/ANSI_escape_code) for more detail. - -### Cursor - -- `Up(n)` -- `Down(n)` -- `Right(n)` -- `Left(n)` -- `NextLine(n)` -- `PreviousLine(n)` -- `Column(col)` -- `Position(row, col)` -- `Save` -- `Restore` -- `Hide` -- `Show` -- `Report` - -### Erase - -- `EraseDisplay(mode)` -- `EraseLine(mode)` - -### Scroll - -- `ScrollUp(n)` -- `ScrollDown(n)` - -### Font Style - -- `Bold` -- `Faint` -- `Italic` -- `Underline` -- `BlinkSlow` -- `BlinkRapid` -- `Inverse` -- `Conceal` -- `CrossOut` -- `Frame` -- `Encircle` -- `Overline` - -### Font Color - -Foreground color. - -- `DefaultF` -- `BlackF` -- `RedF` -- `GreenF` -- `YellowF` -- `BlueF` -- `MagentaF` -- `CyanF` -- `WhiteF` -- `LightBlackF` -- `LightRedF` -- `LightGreenF` -- `LightYellowF` -- `LightBlueF` -- `LightMagentaF` -- `LightCyanF` -- `LightWhiteF` -- `Color3BitF(color)` -- `Color8BitF(color)` -- `FullColorF(r, g, b)` - -Background color. - -- `DefaultB` -- `BlackB` -- `RedB` -- `GreenB` -- `YellowB` -- `BlueB` -- `MagentaB` -- `CyanB` -- `WhiteB` -- `LightBlackB` -- `LightRedB` -- `LightGreenB` -- `LightYellowB` -- `LightBlueB` -- `LightMagentaB` -- `LightCyanB` -- `LightWhiteB` -- `Color3BitB(color)` -- `Color8BitB(color)` -- `FullColorB(r, g, b)` - -### Color Converter - -24bit RGB color to ANSI color. - -- `NewRGB3Bit(r, g, b)` -- `NewRGB8Bit(r, g, b)` - -### Builder - -To mix these features. - -```go -custom := aec.EmptyBuilder.Right(2).RGB8BitF(128, 255, 64).RedB().ANSI -custom.Apply("Hello World") -``` - -## Usage - -1. Create ANSI by `aec.XXX().With(aec.YYY())` or `aec.EmptyBuilder.XXX().YYY().ANSI` -2. Print ANSI by `fmt.Print(ansi, "some string", aec.Reset)` or `fmt.Print(ansi.Apply("some string"))` - -`aec.Reset` should be added when using font style or font color features. - -## Example - -Simple progressbar. - -![sample](./sample.gif) - -```go -package main - -import ( - "fmt" - "strings" - "time" - - "github.com/morikuni/aec" -) - -func main() { - const n = 20 - builder := aec.EmptyBuilder - - up2 := aec.Up(2) - col := aec.Column(n + 2) - bar := aec.Color8BitF(aec.NewRGB8Bit(64, 255, 64)) - label := builder.LightRedF().Underline().With(col).Right(1).ANSI - - // for up2 - fmt.Println() - fmt.Println() - - for i := 0; i <= n; i++ { - fmt.Print(up2) - fmt.Println(label.Apply(fmt.Sprint(i, "/", n))) - fmt.Print("[") - fmt.Print(bar.Apply(strings.Repeat("=", i))) - fmt.Println(col.Apply("]")) - time.Sleep(100 * time.Millisecond) - } -} -``` - -## License - -[MIT](./LICENSE) - - diff --git a/vendor/github.com/morikuni/aec/aec.go b/vendor/github.com/morikuni/aec/aec.go deleted file mode 100644 index 566be6eb1ef..00000000000 --- a/vendor/github.com/morikuni/aec/aec.go +++ /dev/null @@ -1,137 +0,0 @@ -package aec - -import "fmt" - -// EraseMode is listed in a variable EraseModes. -type EraseMode uint - -var ( - // EraseModes is a list of EraseMode. - EraseModes struct { - // All erase all. - All EraseMode - - // Head erase to head. - Head EraseMode - - // Tail erase to tail. - Tail EraseMode - } - - // Save saves the cursor position. - Save ANSI - - // Restore restores the cursor position. - Restore ANSI - - // Hide hides the cursor. - Hide ANSI - - // Show shows the cursor. - Show ANSI - - // Report reports the cursor position. - Report ANSI -) - -// Up moves up the cursor. -func Up(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dA", n)) -} - -// Down moves down the cursor. -func Down(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dB", n)) -} - -// Right moves right the cursor. -func Right(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dC", n)) -} - -// Left moves left the cursor. -func Left(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dD", n)) -} - -// NextLine moves down the cursor to head of a line. -func NextLine(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dE", n)) -} - -// PreviousLine moves up the cursor to head of a line. -func PreviousLine(n uint) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dF", n)) -} - -// Column set the cursor position to a given column. -func Column(col uint) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dG", col)) -} - -// Position set the cursor position to a given absolute position. -func Position(row, col uint) ANSI { - return newAnsi(fmt.Sprintf(esc+"%d;%dH", row, col)) -} - -// EraseDisplay erases display by given EraseMode. -func EraseDisplay(m EraseMode) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dJ", m)) -} - -// EraseLine erases lines by given EraseMode. -func EraseLine(m EraseMode) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dK", m)) -} - -// ScrollUp scrolls up the page. -func ScrollUp(n int) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dS", n)) -} - -// ScrollDown scrolls down the page. -func ScrollDown(n int) ANSI { - if n == 0 { - return empty - } - return newAnsi(fmt.Sprintf(esc+"%dT", n)) -} - -func init() { - EraseModes = struct { - All EraseMode - Head EraseMode - Tail EraseMode - }{ - Tail: 0, - Head: 1, - All: 2, - } - - Save = newAnsi(esc + "s") - Restore = newAnsi(esc + "u") - Hide = newAnsi(esc + "?25l") - Show = newAnsi(esc + "?25h") - Report = newAnsi(esc + "6n") -} diff --git a/vendor/github.com/morikuni/aec/ansi.go b/vendor/github.com/morikuni/aec/ansi.go deleted file mode 100644 index e60722e6e60..00000000000 --- a/vendor/github.com/morikuni/aec/ansi.go +++ /dev/null @@ -1,59 +0,0 @@ -package aec - -import ( - "fmt" - "strings" -) - -const esc = "\x1b[" - -// Reset resets SGR effect. -const Reset string = "\x1b[0m" - -var empty = newAnsi("") - -// ANSI represents ANSI escape code. -type ANSI interface { - fmt.Stringer - - // With adapts given ANSIs. - With(...ANSI) ANSI - - // Apply wraps given string in ANSI. - Apply(string) string -} - -type ansiImpl string - -func newAnsi(s string) *ansiImpl { - r := ansiImpl(s) - return &r -} - -func (a *ansiImpl) With(ansi ...ANSI) ANSI { - return concat(append([]ANSI{a}, ansi...)) -} - -func (a *ansiImpl) Apply(s string) string { - return a.String() + s + Reset -} - -func (a *ansiImpl) String() string { - return string(*a) -} - -// Apply wraps given string in ANSIs. -func Apply(s string, ansi ...ANSI) string { - if len(ansi) == 0 { - return s - } - return concat(ansi).Apply(s) -} - -func concat(ansi []ANSI) ANSI { - strs := make([]string, 0, len(ansi)) - for _, p := range ansi { - strs = append(strs, p.String()) - } - return newAnsi(strings.Join(strs, "")) -} diff --git a/vendor/github.com/morikuni/aec/builder.go b/vendor/github.com/morikuni/aec/builder.go deleted file mode 100644 index 13bd002d4e3..00000000000 --- a/vendor/github.com/morikuni/aec/builder.go +++ /dev/null @@ -1,388 +0,0 @@ -package aec - -// Builder is a lightweight syntax to construct customized ANSI. -type Builder struct { - ANSI ANSI -} - -// EmptyBuilder is an initialized Builder. -var EmptyBuilder *Builder - -// NewBuilder creates a Builder from existing ANSI. -func NewBuilder(a ...ANSI) *Builder { - return &Builder{concat(a)} -} - -// With is a syntax for With. -func (builder *Builder) With(a ...ANSI) *Builder { - return NewBuilder(builder.ANSI.With(a...)) -} - -// Up is a syntax for Up. -func (builder *Builder) Up(n uint) *Builder { - return builder.With(Up(n)) -} - -// Down is a syntax for Down. -func (builder *Builder) Down(n uint) *Builder { - return builder.With(Down(n)) -} - -// Right is a syntax for Right. -func (builder *Builder) Right(n uint) *Builder { - return builder.With(Right(n)) -} - -// Left is a syntax for Left. -func (builder *Builder) Left(n uint) *Builder { - return builder.With(Left(n)) -} - -// NextLine is a syntax for NextLine. -func (builder *Builder) NextLine(n uint) *Builder { - return builder.With(NextLine(n)) -} - -// PreviousLine is a syntax for PreviousLine. -func (builder *Builder) PreviousLine(n uint) *Builder { - return builder.With(PreviousLine(n)) -} - -// Column is a syntax for Column. -func (builder *Builder) Column(col uint) *Builder { - return builder.With(Column(col)) -} - -// Position is a syntax for Position. -func (builder *Builder) Position(row, col uint) *Builder { - return builder.With(Position(row, col)) -} - -// EraseDisplay is a syntax for EraseDisplay. -func (builder *Builder) EraseDisplay(m EraseMode) *Builder { - return builder.With(EraseDisplay(m)) -} - -// EraseLine is a syntax for EraseLine. -func (builder *Builder) EraseLine(m EraseMode) *Builder { - return builder.With(EraseLine(m)) -} - -// ScrollUp is a syntax for ScrollUp. -func (builder *Builder) ScrollUp(n int) *Builder { - return builder.With(ScrollUp(n)) -} - -// ScrollDown is a syntax for ScrollDown. -func (builder *Builder) ScrollDown(n int) *Builder { - return builder.With(ScrollDown(n)) -} - -// Save is a syntax for Save. -func (builder *Builder) Save() *Builder { - return builder.With(Save) -} - -// Restore is a syntax for Restore. -func (builder *Builder) Restore() *Builder { - return builder.With(Restore) -} - -// Hide is a syntax for Hide. -func (builder *Builder) Hide() *Builder { - return builder.With(Hide) -} - -// Show is a syntax for Show. -func (builder *Builder) Show() *Builder { - return builder.With(Show) -} - -// Report is a syntax for Report. -func (builder *Builder) Report() *Builder { - return builder.With(Report) -} - -// Bold is a syntax for Bold. -func (builder *Builder) Bold() *Builder { - return builder.With(Bold) -} - -// Faint is a syntax for Faint. -func (builder *Builder) Faint() *Builder { - return builder.With(Faint) -} - -// Italic is a syntax for Italic. -func (builder *Builder) Italic() *Builder { - return builder.With(Italic) -} - -// Underline is a syntax for Underline. -func (builder *Builder) Underline() *Builder { - return builder.With(Underline) -} - -// BlinkSlow is a syntax for BlinkSlow. -func (builder *Builder) BlinkSlow() *Builder { - return builder.With(BlinkSlow) -} - -// BlinkRapid is a syntax for BlinkRapid. -func (builder *Builder) BlinkRapid() *Builder { - return builder.With(BlinkRapid) -} - -// Inverse is a syntax for Inverse. -func (builder *Builder) Inverse() *Builder { - return builder.With(Inverse) -} - -// Conceal is a syntax for Conceal. -func (builder *Builder) Conceal() *Builder { - return builder.With(Conceal) -} - -// CrossOut is a syntax for CrossOut. -func (builder *Builder) CrossOut() *Builder { - return builder.With(CrossOut) -} - -// BlackF is a syntax for BlackF. -func (builder *Builder) BlackF() *Builder { - return builder.With(BlackF) -} - -// RedF is a syntax for RedF. -func (builder *Builder) RedF() *Builder { - return builder.With(RedF) -} - -// GreenF is a syntax for GreenF. -func (builder *Builder) GreenF() *Builder { - return builder.With(GreenF) -} - -// YellowF is a syntax for YellowF. -func (builder *Builder) YellowF() *Builder { - return builder.With(YellowF) -} - -// BlueF is a syntax for BlueF. -func (builder *Builder) BlueF() *Builder { - return builder.With(BlueF) -} - -// MagentaF is a syntax for MagentaF. -func (builder *Builder) MagentaF() *Builder { - return builder.With(MagentaF) -} - -// CyanF is a syntax for CyanF. -func (builder *Builder) CyanF() *Builder { - return builder.With(CyanF) -} - -// WhiteF is a syntax for WhiteF. -func (builder *Builder) WhiteF() *Builder { - return builder.With(WhiteF) -} - -// DefaultF is a syntax for DefaultF. -func (builder *Builder) DefaultF() *Builder { - return builder.With(DefaultF) -} - -// BlackB is a syntax for BlackB. -func (builder *Builder) BlackB() *Builder { - return builder.With(BlackB) -} - -// RedB is a syntax for RedB. -func (builder *Builder) RedB() *Builder { - return builder.With(RedB) -} - -// GreenB is a syntax for GreenB. -func (builder *Builder) GreenB() *Builder { - return builder.With(GreenB) -} - -// YellowB is a syntax for YellowB. -func (builder *Builder) YellowB() *Builder { - return builder.With(YellowB) -} - -// BlueB is a syntax for BlueB. -func (builder *Builder) BlueB() *Builder { - return builder.With(BlueB) -} - -// MagentaB is a syntax for MagentaB. -func (builder *Builder) MagentaB() *Builder { - return builder.With(MagentaB) -} - -// CyanB is a syntax for CyanB. -func (builder *Builder) CyanB() *Builder { - return builder.With(CyanB) -} - -// WhiteB is a syntax for WhiteB. -func (builder *Builder) WhiteB() *Builder { - return builder.With(WhiteB) -} - -// DefaultB is a syntax for DefaultB. -func (builder *Builder) DefaultB() *Builder { - return builder.With(DefaultB) -} - -// Frame is a syntax for Frame. -func (builder *Builder) Frame() *Builder { - return builder.With(Frame) -} - -// Encircle is a syntax for Encircle. -func (builder *Builder) Encircle() *Builder { - return builder.With(Encircle) -} - -// Overline is a syntax for Overline. -func (builder *Builder) Overline() *Builder { - return builder.With(Overline) -} - -// LightBlackF is a syntax for LightBlueF. -func (builder *Builder) LightBlackF() *Builder { - return builder.With(LightBlackF) -} - -// LightRedF is a syntax for LightRedF. -func (builder *Builder) LightRedF() *Builder { - return builder.With(LightRedF) -} - -// LightGreenF is a syntax for LightGreenF. -func (builder *Builder) LightGreenF() *Builder { - return builder.With(LightGreenF) -} - -// LightYellowF is a syntax for LightYellowF. -func (builder *Builder) LightYellowF() *Builder { - return builder.With(LightYellowF) -} - -// LightBlueF is a syntax for LightBlueF. -func (builder *Builder) LightBlueF() *Builder { - return builder.With(LightBlueF) -} - -// LightMagentaF is a syntax for LightMagentaF. -func (builder *Builder) LightMagentaF() *Builder { - return builder.With(LightMagentaF) -} - -// LightCyanF is a syntax for LightCyanF. -func (builder *Builder) LightCyanF() *Builder { - return builder.With(LightCyanF) -} - -// LightWhiteF is a syntax for LightWhiteF. -func (builder *Builder) LightWhiteF() *Builder { - return builder.With(LightWhiteF) -} - -// LightBlackB is a syntax for LightBlackB. -func (builder *Builder) LightBlackB() *Builder { - return builder.With(LightBlackB) -} - -// LightRedB is a syntax for LightRedB. -func (builder *Builder) LightRedB() *Builder { - return builder.With(LightRedB) -} - -// LightGreenB is a syntax for LightGreenB. -func (builder *Builder) LightGreenB() *Builder { - return builder.With(LightGreenB) -} - -// LightYellowB is a syntax for LightYellowB. -func (builder *Builder) LightYellowB() *Builder { - return builder.With(LightYellowB) -} - -// LightBlueB is a syntax for LightBlueB. -func (builder *Builder) LightBlueB() *Builder { - return builder.With(LightBlueB) -} - -// LightMagentaB is a syntax for LightMagentaB. -func (builder *Builder) LightMagentaB() *Builder { - return builder.With(LightMagentaB) -} - -// LightCyanB is a syntax for LightCyanB. -func (builder *Builder) LightCyanB() *Builder { - return builder.With(LightCyanB) -} - -// LightWhiteB is a syntax for LightWhiteB. -func (builder *Builder) LightWhiteB() *Builder { - return builder.With(LightWhiteB) -} - -// Color3BitF is a syntax for Color3BitF. -func (builder *Builder) Color3BitF(c RGB3Bit) *Builder { - return builder.With(Color3BitF(c)) -} - -// Color3BitB is a syntax for Color3BitB. -func (builder *Builder) Color3BitB(c RGB3Bit) *Builder { - return builder.With(Color3BitB(c)) -} - -// Color8BitF is a syntax for Color8BitF. -func (builder *Builder) Color8BitF(c RGB8Bit) *Builder { - return builder.With(Color8BitF(c)) -} - -// Color8BitB is a syntax for Color8BitB. -func (builder *Builder) Color8BitB(c RGB8Bit) *Builder { - return builder.With(Color8BitB(c)) -} - -// FullColorF is a syntax for FullColorF. -func (builder *Builder) FullColorF(r, g, b uint8) *Builder { - return builder.With(FullColorF(r, g, b)) -} - -// FullColorB is a syntax for FullColorB. -func (builder *Builder) FullColorB(r, g, b uint8) *Builder { - return builder.With(FullColorB(r, g, b)) -} - -// RGB3BitF is a syntax for Color3BitF with NewRGB3Bit. -func (builder *Builder) RGB3BitF(r, g, b uint8) *Builder { - return builder.Color3BitF(NewRGB3Bit(r, g, b)) -} - -// RGB3BitB is a syntax for Color3BitB with NewRGB3Bit. -func (builder *Builder) RGB3BitB(r, g, b uint8) *Builder { - return builder.Color3BitB(NewRGB3Bit(r, g, b)) -} - -// RGB8BitF is a syntax for Color8BitF with NewRGB8Bit. -func (builder *Builder) RGB8BitF(r, g, b uint8) *Builder { - return builder.Color8BitF(NewRGB8Bit(r, g, b)) -} - -// RGB8BitB is a syntax for Color8BitB with NewRGB8Bit. -func (builder *Builder) RGB8BitB(r, g, b uint8) *Builder { - return builder.Color8BitB(NewRGB8Bit(r, g, b)) -} - -func init() { - EmptyBuilder = &Builder{empty} -} diff --git a/vendor/github.com/morikuni/aec/sample.gif b/vendor/github.com/morikuni/aec/sample.gif deleted file mode 100644 index c6c613bb706..00000000000 Binary files a/vendor/github.com/morikuni/aec/sample.gif and /dev/null differ diff --git a/vendor/github.com/morikuni/aec/sgr.go b/vendor/github.com/morikuni/aec/sgr.go deleted file mode 100644 index 0ba3464e6db..00000000000 --- a/vendor/github.com/morikuni/aec/sgr.go +++ /dev/null @@ -1,202 +0,0 @@ -package aec - -import ( - "fmt" -) - -// RGB3Bit is a 3bit RGB color. -type RGB3Bit uint8 - -// RGB8Bit is a 8bit RGB color. -type RGB8Bit uint8 - -func newSGR(n uint) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dm", n)) -} - -// NewRGB3Bit create a RGB3Bit from given RGB. -func NewRGB3Bit(r, g, b uint8) RGB3Bit { - return RGB3Bit((r >> 7) | ((g >> 6) & 0x2) | ((b >> 5) & 0x4)) -} - -// NewRGB8Bit create a RGB8Bit from given RGB. -func NewRGB8Bit(r, g, b uint8) RGB8Bit { - return RGB8Bit(16 + 36*(r/43) + 6*(g/43) + b/43) -} - -// Color3BitF set the foreground color of text. -func Color3BitF(c RGB3Bit) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dm", c+30)) -} - -// Color3BitB set the background color of text. -func Color3BitB(c RGB3Bit) ANSI { - return newAnsi(fmt.Sprintf(esc+"%dm", c+40)) -} - -// Color8BitF set the foreground color of text. -func Color8BitF(c RGB8Bit) ANSI { - return newAnsi(fmt.Sprintf(esc+"38;5;%dm", c)) -} - -// Color8BitB set the background color of text. -func Color8BitB(c RGB8Bit) ANSI { - return newAnsi(fmt.Sprintf(esc+"48;5;%dm", c)) -} - -// FullColorF set the foreground color of text. -func FullColorF(r, g, b uint8) ANSI { - return newAnsi(fmt.Sprintf(esc+"38;2;%d;%d;%dm", r, g, b)) -} - -// FullColorB set the foreground color of text. -func FullColorB(r, g, b uint8) ANSI { - return newAnsi(fmt.Sprintf(esc+"48;2;%d;%d;%dm", r, g, b)) -} - -// Style -var ( - // Bold set the text style to bold or increased intensity. - Bold ANSI - - // Faint set the text style to faint. - Faint ANSI - - // Italic set the text style to italic. - Italic ANSI - - // Underline set the text style to underline. - Underline ANSI - - // BlinkSlow set the text style to slow blink. - BlinkSlow ANSI - - // BlinkRapid set the text style to rapid blink. - BlinkRapid ANSI - - // Inverse swap the foreground color and background color. - Inverse ANSI - - // Conceal set the text style to conceal. - Conceal ANSI - - // CrossOut set the text style to crossed out. - CrossOut ANSI - - // Frame set the text style to framed. - Frame ANSI - - // Encircle set the text style to encircled. - Encircle ANSI - - // Overline set the text style to overlined. - Overline ANSI -) - -// Foreground color of text. -var ( - // DefaultF is the default color of foreground. - DefaultF ANSI - - // Normal color - BlackF ANSI - RedF ANSI - GreenF ANSI - YellowF ANSI - BlueF ANSI - MagentaF ANSI - CyanF ANSI - WhiteF ANSI - - // Light color - LightBlackF ANSI - LightRedF ANSI - LightGreenF ANSI - LightYellowF ANSI - LightBlueF ANSI - LightMagentaF ANSI - LightCyanF ANSI - LightWhiteF ANSI -) - -// Background color of text. -var ( - // DefaultB is the default color of background. - DefaultB ANSI - - // Normal color - BlackB ANSI - RedB ANSI - GreenB ANSI - YellowB ANSI - BlueB ANSI - MagentaB ANSI - CyanB ANSI - WhiteB ANSI - - // Light color - LightBlackB ANSI - LightRedB ANSI - LightGreenB ANSI - LightYellowB ANSI - LightBlueB ANSI - LightMagentaB ANSI - LightCyanB ANSI - LightWhiteB ANSI -) - -func init() { - Bold = newSGR(1) - Faint = newSGR(2) - Italic = newSGR(3) - Underline = newSGR(4) - BlinkSlow = newSGR(5) - BlinkRapid = newSGR(6) - Inverse = newSGR(7) - Conceal = newSGR(8) - CrossOut = newSGR(9) - - BlackF = newSGR(30) - RedF = newSGR(31) - GreenF = newSGR(32) - YellowF = newSGR(33) - BlueF = newSGR(34) - MagentaF = newSGR(35) - CyanF = newSGR(36) - WhiteF = newSGR(37) - - DefaultF = newSGR(39) - - BlackB = newSGR(40) - RedB = newSGR(41) - GreenB = newSGR(42) - YellowB = newSGR(43) - BlueB = newSGR(44) - MagentaB = newSGR(45) - CyanB = newSGR(46) - WhiteB = newSGR(47) - - DefaultB = newSGR(49) - - Frame = newSGR(51) - Encircle = newSGR(52) - Overline = newSGR(53) - - LightBlackF = newSGR(90) - LightRedF = newSGR(91) - LightGreenF = newSGR(92) - LightYellowF = newSGR(93) - LightBlueF = newSGR(94) - LightMagentaF = newSGR(95) - LightCyanF = newSGR(96) - LightWhiteF = newSGR(97) - - LightBlackB = newSGR(100) - LightRedB = newSGR(101) - LightGreenB = newSGR(102) - LightYellowB = newSGR(103) - LightBlueB = newSGR(104) - LightMagentaB = newSGR(105) - LightCyanB = newSGR(106) - LightWhiteB = newSGR(107) -} diff --git a/vendor/github.com/opencontainers/runc/internal/linux/linux.go b/vendor/github.com/opencontainers/runc/internal/linux/linux.go index 88fe5e0dfdf..13713159328 100644 --- a/vendor/github.com/opencontainers/runc/internal/linux/linux.go +++ b/vendor/github.com/opencontainers/runc/internal/linux/linux.go @@ -16,7 +16,7 @@ func Dup3(oldfd, newfd, flags int) error { } // Exec wraps [unix.Exec]. -func Exec(cmd string, args []string, env []string) error { +func Exec(cmd string, args, env []string) error { err := retryOnEINTR(func() error { return unix.Exec(cmd, args, env) }) @@ -66,6 +66,22 @@ func Recvfrom(fd int, p []byte, flags int) (n int, from unix.Sockaddr, err error return n, from, err } +// SchedSetaffinity wraps sched_setaffinity syscall without unix.CPUSet size limitation. +func SchedSetaffinity(pid int, buf []byte) error { + err := retryOnEINTR(func() error { + _, _, errno := unix.Syscall( + unix.SYS_SCHED_SETAFFINITY, + uintptr(pid), + uintptr(len(buf)), + uintptr((unsafe.Pointer)(&buf[0]))) + if errno != 0 { + return errno + } + return nil + }) + return os.NewSyscallError("sched_setaffinity", err) +} + // Sendmsg wraps [unix.Sendmsg]. func Sendmsg(fd int, p, oob []byte, to unix.Sockaddr, flags int) error { err := retryOnEINTR(func() error { @@ -75,13 +91,9 @@ func Sendmsg(fd int, p, oob []byte, to unix.Sockaddr, flags int) error { } // SetMempolicy wraps set_mempolicy. -func SetMempolicy(mode uint, mask *unix.CPUSet) error { +func SetMempolicy(mode int, mask *unix.CPUSet) error { err := retryOnEINTR(func() error { - _, _, errno := unix.Syscall(unix.SYS_SET_MEMPOLICY, uintptr(mode), uintptr(unsafe.Pointer(mask)), unsafe.Sizeof(*mask)*8) - if errno != 0 { - return errno - } - return nil + return unix.SetMemPolicy(mode, mask) }) return os.NewSyscallError("set_mempolicy", err) } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go index c533eb1c67a..409e58e963d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go @@ -98,7 +98,7 @@ func GetDevices(path string) ([]*Device, error) { if errors.Is(err, ErrNotADevice) { continue } - if os.IsNotExist(err) { + if errors.Is(err, os.ErrNotExist) { continue } return nil, err diff --git a/vendor/github.com/sigstore/sigstore/pkg/cryptoutils/publickey.go b/vendor/github.com/sigstore/sigstore/pkg/cryptoutils/publickey.go index 63e789a8d2d..1182d0ca35f 100644 --- a/vendor/github.com/sigstore/sigstore/pkg/cryptoutils/publickey.go +++ b/vendor/github.com/sigstore/sigstore/pkg/cryptoutils/publickey.go @@ -19,6 +19,7 @@ import ( "crypto" "crypto/ecdsa" "crypto/ed25519" + "crypto/elliptic" "crypto/rsa" "crypto/sha1" // nolint:gosec "crypto/x509" @@ -28,6 +29,7 @@ import ( "encoding/pem" "errors" "fmt" + "slices" ) const ( @@ -130,3 +132,27 @@ func genErrMsg(first, second crypto.PublicKey, keyType string) string { } return fmt.Sprintf("%s (%s, %s)", msg, hex.EncodeToString(firstSKID), hex.EncodeToString(secondSKID)) } + +// ValidatePubKey validates the parameters of an RSA, ECDSA, or ED25519 public key. +// +// Deprecated: Prefer goodkey.ValidatePubKey. This function has been +// updated to verify only the size of the key for RSA or the curve +// for ECDSA. +func ValidatePubKey(pub crypto.PublicKey) error { + switch pk := pub.(type) { + case *rsa.PublicKey: + if !slices.Contains([]int{2048, 3072, 4096}, pk.Size()*8) { + return fmt.Errorf("rsa key size %d is not supported supported, modulus size must be 2048, 3072, or 4096", pk.Size()*8) + } + return nil + case *ecdsa.PublicKey: + if !slices.Contains([]elliptic.Curve{elliptic.P256(), elliptic.P384(), elliptic.P521()}, pk.Curve) { + return fmt.Errorf("ecdsa curve %T is not supported, must be NIST P-256, P-384 or P-521", pk.Curve) + } + return nil + case ed25519.PublicKey: + // Nothing to validate for Ed25519 + return nil + } + return fmt.Errorf("unsupported public key type: %T", pub) +} diff --git a/vendor/github.com/sigstore/sigstore/pkg/signature/signer.go b/vendor/github.com/sigstore/sigstore/pkg/signature/signer.go index 1122989ff65..50f432798d3 100644 --- a/vendor/github.com/sigstore/sigstore/pkg/signature/signer.go +++ b/vendor/github.com/sigstore/sigstore/pkg/signature/signer.go @@ -31,9 +31,6 @@ import ( "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/signature/options" - - // these ensure we have the implementations loaded - _ "golang.org/x/crypto/sha3" ) // Signer creates digital signatures over a message using a specified key pair diff --git a/vendor/go.podman.io/common/libnetwork/cni/README.md b/vendor/go.podman.io/common/libnetwork/cni/README.md deleted file mode 100644 index 6f57feff51b..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/README.md +++ /dev/null @@ -1,10 +0,0 @@ -This package abstracts CNI from libpod. -It implements the `ContainerNetwork` interface defined in [libpod/network/types/network.go](../types/network.go) for the CNI backend. - - -## Testing -Run the tests with: -``` -go test -v -mod=vendor -cover ./libpod/network/cni/ -``` -Run the tests as root to also test setup/teardown. This will execute CNI and therefore the cni plugins have to be installed. diff --git a/vendor/go.podman.io/common/libnetwork/cni/cni_conversion.go b/vendor/go.podman.io/common/libnetwork/cni/cni_conversion.go deleted file mode 100644 index c89a867453a..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/cni_conversion.go +++ /dev/null @@ -1,461 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "os" - "path/filepath" - "slices" - "strconv" - "strings" - "time" - - "github.com/containernetworking/cni/libcni" - "github.com/sirupsen/logrus" - internalutil "go.podman.io/common/libnetwork/internal/util" - "go.podman.io/common/libnetwork/types" - "go.podman.io/common/libnetwork/util" - "golang.org/x/sys/unix" -) - -func createNetworkFromCNIConfigList(conf *libcni.NetworkConfigList, confPath string) (*types.Network, error) { - network := types.Network{ - Name: conf.Name, - ID: getNetworkIDFromName(conf.Name), - Labels: map[string]string{}, - Options: map[string]string{}, - IPAMOptions: map[string]string{}, - } - - cniJSON := make(map[string]any) - err := json.Unmarshal(conf.Bytes, &cniJSON) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal network config %s: %w", conf.Name, err) - } - if args, ok := cniJSON["args"]; ok { - if key, ok := args.(map[string]any); ok { - // read network labels and options from the conf file - network.Labels = getNetworkArgsFromConfList(key, podmanLabelKey) - network.Options = getNetworkArgsFromConfList(key, podmanOptionsKey) - } - } - - t, err := fileTime(confPath) - if err != nil { - return nil, err - } - network.Created = t - - firstPlugin := conf.Plugins[0] - network.Driver = firstPlugin.Network.Type - - switch firstPlugin.Network.Type { - case types.BridgeNetworkDriver: - var bridge hostLocalBridge - err := json.Unmarshal(firstPlugin.Bytes, &bridge) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal the bridge plugin config in %s: %w", confPath, err) - } - network.NetworkInterface = bridge.BrName - - // if isGateway is false we have an internal network - if !bridge.IsGW { - network.Internal = true - } - - // set network options - if bridge.MTU != 0 { - network.Options[types.MTUOption] = strconv.Itoa(bridge.MTU) - } - if bridge.Vlan != 0 { - network.Options[types.VLANOption] = strconv.Itoa(bridge.Vlan) - } - - err = convertIPAMConfToNetwork(&network, &bridge.IPAM, confPath) - if err != nil { - return nil, err - } - - case types.MacVLANNetworkDriver, types.IPVLANNetworkDriver: - var vlan VLANConfig - err := json.Unmarshal(firstPlugin.Bytes, &vlan) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal the macvlan plugin config in %s: %w", confPath, err) - } - network.NetworkInterface = vlan.Master - - // set network options - if vlan.MTU != 0 { - network.Options[types.MTUOption] = strconv.Itoa(vlan.MTU) - } - - if vlan.Mode != "" { - network.Options[types.ModeOption] = vlan.Mode - } - - err = convertIPAMConfToNetwork(&network, &vlan.IPAM, confPath) - if err != nil { - return nil, err - } - - default: - // A warning would be good but users would get this warning every time so keep this at info level. - logrus.Infof("Unsupported CNI config type %s in %s, this network can still be used but inspect or list cannot show all information", - firstPlugin.Network.Type, confPath) - } - - // check if the dnsname plugin is configured - network.DNSEnabled = findPluginByName(conf.Plugins, "dnsname") != nil - - // now get isolation mode from firewall plugin - firewall := findPluginByName(conf.Plugins, "firewall") - if firewall != nil { - var firewallConf firewallConfig - err := json.Unmarshal(firewall.Bytes, &firewallConf) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal the firewall plugin config in %s: %w", confPath, err) - } - if firewallConf.IngressPolicy == ingressPolicySameBridge { - network.Options[types.IsolateOption] = "true" - } - } - - return &network, nil -} - -func findPluginByName(plugins []*libcni.NetworkConfig, name string) *libcni.NetworkConfig { - for i := range plugins { - if plugins[i].Network.Type == name { - return plugins[i] - } - } - return nil -} - -// convertIPAMConfToNetwork converts A cni IPAMConfig to libpod network subnets. -// It returns an array of subnets and an extra bool if dhcp is configured. -func convertIPAMConfToNetwork(network *types.Network, ipam *ipamConfig, confPath string) error { - switch ipam.PluginType { - case "": - network.IPAMOptions[types.Driver] = types.NoneIPAMDriver - case types.DHCPIPAMDriver: - network.IPAMOptions[types.Driver] = types.DHCPIPAMDriver - case types.HostLocalIPAMDriver: - network.IPAMOptions[types.Driver] = types.HostLocalIPAMDriver - for _, r := range ipam.Ranges { - for _, ipam := range r { - s := types.Subnet{} - - // Do not use types.ParseCIDR() because we want the ip to be - // the network address and not a random ip in the sub. - _, sub, err := net.ParseCIDR(ipam.Subnet) - if err != nil { - return err - } - s.Subnet = types.IPNet{IPNet: *sub} - - // gateway - var gateway net.IP - if ipam.Gateway != "" { - gateway = net.ParseIP(ipam.Gateway) - if gateway == nil { - return fmt.Errorf("failed to parse gateway ip %s", ipam.Gateway) - } - // convert to 4 byte if ipv4 - util.NormalizeIP(&gateway) - } else if !network.Internal { - // only add a gateway address if the network is not internal - gateway, err = util.FirstIPInSubnet(sub) - if err != nil { - return fmt.Errorf("failed to get first ip in subnet %s", sub.String()) - } - } - s.Gateway = gateway - - var rangeStart net.IP - var rangeEnd net.IP - if ipam.RangeStart != "" { - rangeStart = net.ParseIP(ipam.RangeStart) - if rangeStart == nil { - return fmt.Errorf("failed to parse range start ip %s", ipam.RangeStart) - } - } - if ipam.RangeEnd != "" { - rangeEnd = net.ParseIP(ipam.RangeEnd) - if rangeEnd == nil { - return fmt.Errorf("failed to parse range end ip %s", ipam.RangeEnd) - } - } - if rangeStart != nil || rangeEnd != nil { - s.LeaseRange = &types.LeaseRange{} - s.LeaseRange.StartIP = rangeStart - s.LeaseRange.EndIP = rangeEnd - } - if util.IsIPv6(s.Subnet.IP) { - network.IPv6Enabled = true - } - network.Subnets = append(network.Subnets, s) - } - } - default: - // This is not an error. While we only support certain ipam drivers, we - // cannot make it fail for unsupported ones. CNI is still able to use them, - // just our translation logic cannot convert this into a Network. - // For the same reason this is not warning, it would just be annoying for - // everyone using a unknown ipam driver. - logrus.Infof("unsupported ipam plugin %q in %s", ipam.PluginType, confPath) - network.IPAMOptions[types.Driver] = ipam.PluginType - } - return nil -} - -// getNetworkArgsFromConfList returns the map of args in a conflist, argType should be labels or options. -func getNetworkArgsFromConfList(args map[string]any, argType string) map[string]string { - if args, ok := args[argType]; ok { - if labels, ok := args.(map[string]any); ok { - result := make(map[string]string, len(labels)) - for k, v := range labels { - if v, ok := v.(string); ok { - result[k] = v - } - } - return result - } - } - return map[string]string{} -} - -// createCNIConfigListFromNetwork will create a cni config file from the given network. -// It returns the cni config and the path to the file where the config was written. -// Set writeToDisk to false to only add this network into memory. -func (n *cniNetwork) createCNIConfigListFromNetwork(network *types.Network, writeToDisk bool) (*libcni.NetworkConfigList, string, error) { - var ( - routes []ipamRoute - ipamRanges [][]ipamLocalHostRangeConf - ipamConf *ipamConfig - err error - ) - - ipamDriver := network.IPAMOptions[types.Driver] - switch ipamDriver { - case types.HostLocalIPAMDriver: - defIpv4Route := false - defIpv6Route := false - for _, subnet := range network.Subnets { - ipam := newIPAMLocalHostRange(subnet.Subnet, subnet.LeaseRange, subnet.Gateway) - ipamRanges = append(ipamRanges, []ipamLocalHostRangeConf{*ipam}) - - // only add default route for not internal networks - if !network.Internal { - ipv6 := util.IsIPv6(subnet.Subnet.IP) - if !ipv6 && defIpv4Route { - continue - } - if ipv6 && defIpv6Route { - continue - } - - if ipv6 { - defIpv6Route = true - } else { - defIpv4Route = true - } - route, err := newIPAMDefaultRoute(ipv6) - if err != nil { - return nil, "", err - } - routes = append(routes, route) - } - } - conf := newIPAMHostLocalConf(routes, ipamRanges) - ipamConf = &conf - case types.DHCPIPAMDriver: - ipamConf = &ipamConfig{PluginType: "dhcp"} - - case types.NoneIPAMDriver: - // do nothing - default: - return nil, "", fmt.Errorf("unsupported ipam driver %q", ipamDriver) - } - - opts, err := parseOptions(network.Options, network.Driver) - if err != nil { - return nil, "", err - } - - isGateway := true - ipMasq := true - if network.Internal { - isGateway = false - ipMasq = false - } - // create CNI plugin configuration - // explicitly use CNI version 0.4.0 here, to use v1.0.0 at least containernetwork-plugins-1.0.1 has to be installed - // the dnsname plugin also needs to be updated for 1.0.0 - // TODO change to 1.0.0 when most distros support it - ncList := newNcList(network.Name, "0.4.0", network.Labels, network.Options) - var plugins []any - - switch network.Driver { - case types.BridgeNetworkDriver: - bridge := newHostLocalBridge(network.NetworkInterface, isGateway, ipMasq, opts.mtu, opts.vlan, ipamConf) - plugins = append(plugins, bridge, newPortMapPlugin(), newFirewallPlugin(opts.isolate), newTuningPlugin()) - // if we find the dnsname plugin we add configuration for it - if hasDNSNamePlugin(n.cniPluginDirs) && network.DNSEnabled { - // Note: in the future we might like to allow for dynamic domain names - plugins = append(plugins, newDNSNamePlugin(defaultPodmanDomainName)) - } - - case types.MacVLANNetworkDriver: - plugins = append(plugins, newVLANPlugin(types.MacVLANNetworkDriver, network.NetworkInterface, opts.vlanPluginMode, opts.mtu, ipamConf)) - - case types.IPVLANNetworkDriver: - plugins = append(plugins, newVLANPlugin(types.IPVLANNetworkDriver, network.NetworkInterface, opts.vlanPluginMode, opts.mtu, ipamConf)) - - default: - return nil, "", fmt.Errorf("driver %q is not supported by cni", network.Driver) - } - ncList["plugins"] = plugins - b, err := json.MarshalIndent(ncList, "", " ") - if err != nil { - return nil, "", err - } - cniPathName := "" - if writeToDisk { - if err := os.MkdirAll(n.cniConfigDir, 0o755); err != nil { - return nil, "", err - } - cniPathName = filepath.Join(n.cniConfigDir, network.Name+".conflist") - err = os.WriteFile(cniPathName, b, 0o644) - if err != nil { - return nil, "", err - } - t, err := fileTime(cniPathName) - if err != nil { - return nil, "", err - } - network.Created = t - } else { - network.Created = time.Now() - } - config, err := libcni.ConfListFromBytes(b) - if err != nil { - return nil, "", err - } - return config, cniPathName, nil -} - -func convertSpecgenPortsToCNIPorts(ports []types.PortMapping) ([]cniPortMapEntry, error) { - cniPorts := make([]cniPortMapEntry, 0, len(ports)) - for _, port := range ports { - if port.Protocol == "" { - return nil, errors.New("port protocol should not be empty") - } - for protocol := range strings.SplitSeq(port.Protocol, ",") { - if !slices.Contains([]string{"tcp", "udp", "sctp"}, protocol) { - return nil, fmt.Errorf("unknown port protocol %s", protocol) - } - cniPort := cniPortMapEntry{ - HostPort: int(port.HostPort), - ContainerPort: int(port.ContainerPort), - HostIP: port.HostIP, - Protocol: protocol, - } - cniPorts = append(cniPorts, cniPort) - for i := 1; i < int(port.Range); i++ { - cniPort := cniPortMapEntry{ - HostPort: int(port.HostPort) + i, - ContainerPort: int(port.ContainerPort) + i, - HostIP: port.HostIP, - Protocol: protocol, - } - cniPorts = append(cniPorts, cniPort) - } - } - } - return cniPorts, nil -} - -func removeMachinePlugin(conf *libcni.NetworkConfigList) *libcni.NetworkConfigList { - plugins := make([]*libcni.NetworkConfig, 0, len(conf.Plugins)) - for _, net := range conf.Plugins { - if net.Network.Type != "podman-machine" { - plugins = append(plugins, net) - } - } - conf.Plugins = plugins - return conf -} - -type options struct { - vlan int - mtu int - vlanPluginMode string - isolate bool -} - -func parseOptions(networkOptions map[string]string, networkDriver string) (*options, error) { - opt := &options{} - var err error - for k, v := range networkOptions { - switch k { - case types.MTUOption: - opt.mtu, err = internalutil.ParseMTU(v) - if err != nil { - return nil, err - } - - case types.VLANOption: - opt.vlan, err = internalutil.ParseVlan(v) - if err != nil { - return nil, err - } - - case types.ModeOption: - switch networkDriver { - case types.MacVLANNetworkDriver: - if !slices.Contains(types.ValidMacVLANModes, v) { - return nil, fmt.Errorf("unknown macvlan mode %q", v) - } - case types.IPVLANNetworkDriver: - if !slices.Contains(types.ValidIPVLANModes, v) { - return nil, fmt.Errorf("unknown ipvlan mode %q", v) - } - default: - return nil, fmt.Errorf("cannot set option \"mode\" with driver %q", networkDriver) - } - opt.vlanPluginMode = v - - case types.IsolateOption: - if networkDriver != types.BridgeNetworkDriver { - return nil, errors.New("isolate option is only supported with the bridge driver") - } - opt.isolate, err = strconv.ParseBool(v) - if err != nil { - return nil, fmt.Errorf("failed to parse isolate option: %w", err) - } - - default: - return nil, fmt.Errorf("unsupported network option %s", k) - } - } - return opt, nil -} - -func fileTime(file string) (time.Time, error) { - var st unix.Stat_t - for { - err := unix.Stat(file, &st) - if err == nil { - break - } - if err != unix.EINTR { //nolint:errorlint // unix errors are bare - return time.Time{}, &os.PathError{Path: file, Op: "stat", Err: err} - } - } - return time.Unix(int64(st.Ctim.Sec), int64(st.Ctim.Nsec)), nil //nolint:unconvert // On some platforms Sec and Nsec are int32. -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/cni_exec.go b/vendor/go.podman.io/common/libnetwork/cni/cni_exec.go deleted file mode 100644 index e4c47f5d73a..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/cni_exec.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2016 CNI authors -// Copyright 2021 Podman authors -// -// This code has been originally copied from github.com/containernetworking/cni -// but has been changed to better fit the Podman use case. -// -// 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 -// -// https://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. - -//go:build (linux || freebsd) && cni - -package cni - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/containernetworking/cni/pkg/invoke" - "github.com/containernetworking/cni/pkg/version" - "go.podman.io/storage/pkg/unshare" -) - -type cniExec struct { - version.PluginDecoder -} - -type cniPluginError struct { - plugin string - Code uint `json:"code"` - Msg string `json:"msg"` - Details string `json:"details,omitempty"` -} - -// Error returns a nicely formatted error message for the cni plugin errors. -func (e *cniPluginError) Error() string { - err := fmt.Sprintf("cni plugin %s failed", e.plugin) - if e.Msg != "" { - err = fmt.Sprintf("%s: %s", err, e.Msg) - } else if e.Code > 0 { - err = fmt.Sprintf("%s with error code %d", err, e.Code) - } - if e.Details != "" { - err = fmt.Sprintf("%s: %s", err, e.Details) - } - return err -} - -// ExecPlugin execute the cni plugin. Returns the stdout of the plugin or an error. -func (e *cniExec) ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error) { - stdout := &bytes.Buffer{} - stderr := &bytes.Buffer{} - c := exec.CommandContext(ctx, pluginPath) - c.Env = environ - c.Stdin = bytes.NewBuffer(stdinData) - c.Stdout = stdout - c.Stderr = stderr - - // The dnsname plugin tries to use XDG_RUNTIME_DIR to store files. - // podman run will have XDG_RUNTIME_DIR set and thus the cni plugin can use - // it. The problem is that XDG_RUNTIME_DIR is unset for the conmon process - // for rootful users. This causes issues since the cleanup process is spawned - // by conmon and thus not have XDG_RUNTIME_DIR set to same value as podman run. - // Because of it dnsname will not find the config files and cannot correctly cleanup. - // To fix this we should also unset XDG_RUNTIME_DIR for the cni plugins as rootful. - if !unshare.IsRootless() { - c.Env = append(c.Env, "XDG_RUNTIME_DIR=") - } - - // The CNI plugins need access to iptables in $PATH. As it turns out debian doesn't put - // /usr/sbin in $PATH for rootless users. This will break rootless networking completely. - // We might break existing users and we cannot expect everyone to change their $PATH so - // let's add /usr/sbin to $PATH ourselves. - path := os.Getenv("PATH") - if !strings.Contains(path, "/usr/sbin") { - path += ":/usr/sbin" - c.Env = append(c.Env, "PATH="+path) - } - - err := c.Run() - if err != nil { - return nil, annotatePluginError(err, pluginPath, stdout.Bytes(), stderr.Bytes()) - } - return stdout.Bytes(), nil -} - -// annotatePluginError parses the common cni plugin error json. -func annotatePluginError(err error, plugin string, stdout, stderr []byte) error { - pluginName := filepath.Base(plugin) - emsg := cniPluginError{ - plugin: pluginName, - } - if len(stdout) == 0 { - if len(stderr) == 0 { - emsg.Msg = err.Error() - } else { - emsg.Msg = string(stderr) - } - } else if perr := json.Unmarshal(stdout, &emsg); perr != nil { - emsg.Msg = fmt.Sprintf("failed to unmarshal error message %q: %v", string(stdout), perr) - } - return &emsg -} - -// FindInPath finds the plugin in the given paths. -func (e *cniExec) FindInPath(plugin string, paths []string) (string, error) { - return invoke.FindInPath(plugin, paths) -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/cni_types.go b/vendor/go.podman.io/common/libnetwork/cni/cni_types.go deleted file mode 100644 index e85a11b4934..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/cni_types.go +++ /dev/null @@ -1,286 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "net" - "path/filepath" - - "go.podman.io/common/libnetwork/types" - "go.podman.io/storage/pkg/fileutils" -) - -const ( - defaultIPv4Route = "0.0.0.0/0" - defaultIPv6Route = "::/0" - // defaultPodmanDomainName is used for the dnsname plugin to define - // a localized domain name for a created network. - defaultPodmanDomainName = "dns.podman" - - // cniDeviceName is the default name for a new bridge, it should be suffixed with an integer. - cniDeviceName = "cni-podman" - - // podmanLabelKey key used to store the podman network label in a cni config. - podmanLabelKey = "podman_labels" - - // podmanOptionsKey key used to store the podman network options in a cni config. - podmanOptionsKey = "podman_options" - - // ingressPolicySameBridge is used to only allow connection on the same bridge network. - ingressPolicySameBridge = "same-bridge" -) - -// cniPortMapEntry struct is used by the portmap plugin -// https://github.com/containernetworking/plugins/blob/649e0181fe7b3a61e708f3e4249a798f57f25cc5/plugins/meta/portmap/main.go#L43-L50 -type cniPortMapEntry struct { - HostPort int `json:"hostPort"` - ContainerPort int `json:"containerPort"` - Protocol string `json:"protocol"` - HostIP string `json:"hostIP,omitempty"` -} - -// hostLocalBridge describes a configuration for a bridge plugin -// https://github.com/containernetworking/plugins/tree/master/plugins/main/bridge#network-configuration-reference -type hostLocalBridge struct { - PluginType string `json:"type"` - BrName string `json:"bridge,omitempty"` - IsGW bool `json:"isGateway"` - IsDefaultGW bool `json:"isDefaultGateway,omitempty"` - ForceAddress bool `json:"forceAddress,omitempty"` - IPMasq bool `json:"ipMasq,omitempty"` - MTU int `json:"mtu,omitempty"` - HairpinMode bool `json:"hairpinMode,omitempty"` - PromiscMode bool `json:"promiscMode,omitempty"` - Vlan int `json:"vlan,omitempty"` - IPAM ipamConfig `json:"ipam"` - Capabilities map[string]bool `json:"capabilities,omitempty"` -} - -// ipamConfig describes an IPAM configuration -// https://github.com/containernetworking/plugins/tree/master/plugins/ipam/host-local#network-configuration-reference -type ipamConfig struct { - PluginType string `json:"type"` - Routes []ipamRoute `json:"routes,omitempty"` - ResolveConf string `json:"resolveConf,omitempty"` - DataDir string `json:"dataDir,omitempty"` - Ranges [][]ipamLocalHostRangeConf `json:"ranges,omitempty"` -} - -// ipamLocalHostRangeConf describes the new style IPAM ranges. -type ipamLocalHostRangeConf struct { - Subnet string `json:"subnet"` - RangeStart string `json:"rangeStart,omitempty"` - RangeEnd string `json:"rangeEnd,omitempty"` - Gateway string `json:"gateway,omitempty"` -} - -// ipamRoute describes a route in an ipam config. -type ipamRoute struct { - Dest string `json:"dst"` -} - -// portMapConfig describes the default portmapping config. -type portMapConfig struct { - PluginType string `json:"type"` - Capabilities map[string]bool `json:"capabilities"` -} - -// VLANConfig describes the macvlan config. -type VLANConfig struct { - PluginType string `json:"type"` - Master string `json:"master"` - IPAM ipamConfig `json:"ipam"` - MTU int `json:"mtu,omitempty"` - Mode string `json:"mode,omitempty"` - Capabilities map[string]bool `json:"capabilities,omitempty"` -} - -// firewallConfig describes the firewall plugin. -type firewallConfig struct { - PluginType string `json:"type"` - Backend string `json:"backend"` - IngressPolicy string `json:"ingressPolicy,omitempty"` -} - -// tuningConfig describes the tuning plugin. -type tuningConfig struct { - PluginType string `json:"type"` -} - -// dnsNameConfig describes the dns container name resolution plugin config. -type dnsNameConfig struct { - PluginType string `json:"type"` - DomainName string `json:"domainName"` - Capabilities map[string]bool `json:"capabilities"` -} - -// ncList describes a generic map. -type ncList map[string]any - -// newNcList creates a generic map of values with string -// keys and adds in version and network name. -func newNcList(name, version string, labels, options map[string]string) ncList { - n := ncList{} - n["cniVersion"] = version - n["name"] = name - args := map[string]map[string]string{} - if len(labels) > 0 { - args[podmanLabelKey] = labels - } - if len(options) > 0 { - args[podmanOptionsKey] = options - } - if len(args) > 0 { - n["args"] = args - } - return n -} - -// newHostLocalBridge creates a new LocalBridge for host-local. -func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu, vlan int, ipamConf *ipamConfig) *hostLocalBridge { - bridge := hostLocalBridge{ - PluginType: "bridge", - BrName: name, - IsGW: isGateWay, - IPMasq: ipMasq, - MTU: mtu, - HairpinMode: true, - Vlan: vlan, - } - if ipamConf != nil { - bridge.IPAM = *ipamConf - // if we use host-local set the ips cap to ensure we can set static ips via runtime config - if ipamConf.PluginType == types.HostLocalIPAMDriver { - bridge.Capabilities = map[string]bool{"ips": true} - } - } - return &bridge -} - -// newIPAMHostLocalConf creates a new IPAMHostLocal configuration. -func newIPAMHostLocalConf(routes []ipamRoute, ipamRanges [][]ipamLocalHostRangeConf) ipamConfig { - ipamConf := ipamConfig{ - PluginType: "host-local", - Routes: routes, - } - - ipamConf.Ranges = ipamRanges - return ipamConf -} - -// newIPAMLocalHostRange create a new IPAM range. -func newIPAMLocalHostRange(subnet types.IPNet, leaseRange *types.LeaseRange, gw net.IP) *ipamLocalHostRangeConf { - hostRange := &ipamLocalHostRangeConf{ - Subnet: subnet.String(), - } - - // a user provided a range, we add it here - if leaseRange != nil { - if leaseRange.StartIP != nil { - hostRange.RangeStart = leaseRange.StartIP.String() - } - if leaseRange.EndIP != nil { - hostRange.RangeEnd = leaseRange.EndIP.String() - } - } - - if gw != nil { - hostRange.Gateway = gw.String() - } - return hostRange -} - -// newIPAMRoute creates a new IPAM route configuration -// nolint:interfacer -func newIPAMRoute(r *net.IPNet) ipamRoute { - return ipamRoute{Dest: r.String()} -} - -// newIPAMDefaultRoute creates a new IPAMDefault route of -// 0.0.0.0/0 for IPv4 or ::/0 for IPv6. -func newIPAMDefaultRoute(isIPv6 bool) (ipamRoute, error) { - route := defaultIPv4Route - if isIPv6 { - route = defaultIPv6Route - } - _, n, err := net.ParseCIDR(route) - if err != nil { - return ipamRoute{}, err - } - return newIPAMRoute(n), nil -} - -// newPortMapPlugin creates a predefined, default portmapping -// configuration. -func newPortMapPlugin() portMapConfig { - return portMapConfig{ - PluginType: "portmap", - Capabilities: map[string]bool{"portMappings": true}, - } -} - -// newFirewallPlugin creates a generic firewall plugin. -func newFirewallPlugin(isolate bool) firewallConfig { - fw := firewallConfig{ - PluginType: "firewall", - } - if isolate { - fw.IngressPolicy = ingressPolicySameBridge - } - return fw -} - -// newTuningPlugin creates a generic tuning section. -func newTuningPlugin() tuningConfig { - return tuningConfig{ - PluginType: "tuning", - } -} - -// newDNSNamePlugin creates the dnsname config with a given -// domainname. -func newDNSNamePlugin(domainName string) dnsNameConfig { - return dnsNameConfig{ - PluginType: "dnsname", - DomainName: domainName, - Capabilities: map[string]bool{"aliases": true}, - } -} - -// hasDNSNamePlugin looks to see if the dnsname cni plugin is present. -func hasDNSNamePlugin(paths []string) bool { - for _, p := range paths { - if err := fileutils.Exists(filepath.Join(p, "dnsname")); err == nil { - return true - } - } - return false -} - -// newVLANPlugin creates a macvlanconfig with a given device name. -func newVLANPlugin(pluginType, device, mode string, mtu int, ipam *ipamConfig) VLANConfig { - m := VLANConfig{ - PluginType: pluginType, - } - if ipam != nil { - m.IPAM = *ipam - } - if mtu > 0 { - m.MTU = mtu - } - if len(mode) > 0 { - m.Mode = mode - } - // CNI is supposed to use the default route if a - // parent device is not provided - if len(device) > 0 { - m.Master = device - } - caps := make(map[string]bool) - caps["ips"] = true - // if we use host-local set the ips cap to ensure we can set static ips via runtime config - if m.IPAM.PluginType == types.HostLocalIPAMDriver { - m.Capabilities = caps - } - return m -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/config.go b/vendor/go.podman.io/common/libnetwork/cni/config.go deleted file mode 100644 index a8060bd7237..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/config.go +++ /dev/null @@ -1,246 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "errors" - "fmt" - "net" - "os" - "slices" - - "github.com/sirupsen/logrus" - internalutil "go.podman.io/common/libnetwork/internal/util" - "go.podman.io/common/libnetwork/types" -) - -func (n *cniNetwork) NetworkUpdate(_ string, _ types.NetworkUpdateOptions) error { - return fmt.Errorf("NetworkUpdate is not supported for backend CNI: %w", types.ErrInvalidArg) -} - -// NetworkCreate will take a partial filled Network and fill the -// missing fields. It creates the Network and returns the full Network. -func (n *cniNetwork) NetworkCreate(net types.Network, options *types.NetworkCreateOptions) (types.Network, error) { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return types.Network{}, err - } - network, err := n.networkCreate(&net, false) - if err != nil { - if options != nil && options.IgnoreIfExists && errors.Is(err, types.ErrNetworkExists) { - if network, ok := n.networks[net.Name]; ok { - return *network.libpodNet, nil - } - } - return types.Network{}, err - } - // add the new network to the map - n.networks[network.libpodNet.Name] = network - return *network.libpodNet, nil -} - -// networkCreate will fill out the given network struct and return the new network entry. -// If defaultNet is true it will not validate against used subnets and it will not write the cni config to disk. -func (n *cniNetwork) networkCreate(newNetwork *types.Network, defaultNet bool) (*network, error) { - if len(newNetwork.NetworkDNSServers) > 0 { - return nil, fmt.Errorf("NetworkDNSServers cannot be configured for backend CNI: %w", types.ErrInvalidArg) - } - // if no driver is set use the default one - if newNetwork.Driver == "" { - newNetwork.Driver = types.DefaultNetworkDriver - } - - // FIXME: Should we use a different type for network create without the ID field? - // the caller is not allowed to set a specific ID - if newNetwork.ID != "" { - return nil, fmt.Errorf("ID can not be set for network create: %w", types.ErrInvalidArg) - } - - err := internalutil.CommonNetworkCreate(n, newNetwork) - if err != nil { - return nil, err - } - - err = validateIPAMDriver(newNetwork) - if err != nil { - return nil, err - } - - // Only get the used networks for validation if we do not create the default network. - // The default network should not be validated against used subnets, we have to ensure - // that this network can always be created even when a subnet is already used on the host. - // This could happen if you run a container on this net, then the cni interface will be - // created on the host and "block" this subnet from being used again. - // Therefore the next podman command tries to create the default net again and it would - // fail because it thinks the network is used on the host. - var usedNetworks []*net.IPNet - if !defaultNet && newNetwork.Driver == types.BridgeNetworkDriver { - usedNetworks, err = internalutil.GetUsedSubnets(n) - if err != nil { - return nil, err - } - } - - switch newNetwork.Driver { - case types.BridgeNetworkDriver: - internalutil.MapDockerBridgeDriverOptions(newNetwork) - err = internalutil.CreateBridge(n, newNetwork, usedNetworks, n.defaultsubnetPools, true) - if err != nil { - return nil, err - } - case types.MacVLANNetworkDriver, types.IPVLANNetworkDriver: - err = createIPMACVLAN(newNetwork) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("unsupported driver %s: %w", newNetwork.Driver, types.ErrInvalidArg) - } - - err = internalutil.ValidateSubnets(newNetwork, !newNetwork.Internal, usedNetworks) - if err != nil { - return nil, err - } - - // generate the network ID - newNetwork.ID = getNetworkIDFromName(newNetwork.Name) - - // when we do not have ipam we must disable dns - internalutil.IpamNoneDisableDNS(newNetwork) - - // FIXME: Should this be a hard error? - if newNetwork.DNSEnabled && newNetwork.Internal && hasDNSNamePlugin(n.cniPluginDirs) { - logrus.Warnf("dnsname and internal networks are incompatible. dnsname plugin not configured for network %s", newNetwork.Name) - newNetwork.DNSEnabled = false - } - - cniConf, path, err := n.createCNIConfigListFromNetwork(newNetwork, !defaultNet) - if err != nil { - return nil, err - } - return &network{cniNet: cniConf, libpodNet: newNetwork, filename: path}, nil -} - -// NetworkRemove will remove the Network with the given name or ID. -// It does not ensure that the network is unused. -func (n *cniNetwork) NetworkRemove(nameOrID string) error { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return err - } - - network, err := n.getNetwork(nameOrID) - if err != nil { - return err - } - - // Removing the default network is not allowed. - if network.libpodNet.Name == n.defaultNetwork { - return fmt.Errorf("default network %s cannot be removed", n.defaultNetwork) - } - - // Remove the bridge network interface on the host. - if network.libpodNet.Driver == types.BridgeNetworkDriver { - deleteLink(network.libpodNet.NetworkInterface) - } - - file := network.filename - delete(n.networks, network.libpodNet.Name) - - // make sure to not error for ErrNotExist - if err := os.Remove(file); err != nil && !errors.Is(err, os.ErrNotExist) { - return err - } - return nil -} - -// NetworkList will return all known Networks. Optionally you can -// supply a list of filter functions. Only if a network matches all -// functions it is returned. -func (n *cniNetwork) NetworkList(filters ...types.FilterFunc) ([]types.Network, error) { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return nil, err - } - - networks := make([]types.Network, 0, len(n.networks)) -outer: - for _, net := range n.networks { - for _, filter := range filters { - // All filters have to match, if one does not match we can skip to the next network. - if !filter(*net.libpodNet) { - continue outer - } - } - networks = append(networks, *net.libpodNet) - } - return networks, nil -} - -// NetworkInspect will return the Network with the given name or ID. -func (n *cniNetwork) NetworkInspect(nameOrID string) (types.Network, error) { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return types.Network{}, err - } - - network, err := n.getNetwork(nameOrID) - if err != nil { - return types.Network{}, err - } - return *network.libpodNet, nil -} - -func createIPMACVLAN(network *types.Network) error { - if network.NetworkInterface != "" { - interfaceNames, err := internalutil.GetLiveNetworkNames() - if err != nil { - return err - } - if !slices.Contains(interfaceNames, network.NetworkInterface) { - return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface) - } - } - - switch network.IPAMOptions[types.Driver] { - // set default - case "": - if len(network.Subnets) == 0 { - // if no subnets and no driver choose dhcp - network.IPAMOptions[types.Driver] = types.DHCPIPAMDriver - } else { - network.IPAMOptions[types.Driver] = types.HostLocalIPAMDriver - } - case types.HostLocalIPAMDriver: - if len(network.Subnets) == 0 { - return errors.New("host-local ipam driver set but no subnets are given") - } - } - - if network.IPAMOptions[types.Driver] == types.DHCPIPAMDriver && network.Internal { - return errors.New("internal is not supported with macvlan and dhcp ipam driver") - } - return nil -} - -func validateIPAMDriver(n *types.Network) error { - ipamDriver := n.IPAMOptions[types.Driver] - switch ipamDriver { - case "", types.HostLocalIPAMDriver: - case types.DHCPIPAMDriver, types.NoneIPAMDriver: - if len(n.Subnets) > 0 { - return fmt.Errorf("%s ipam driver is set but subnets are given", ipamDriver) - } - default: - return fmt.Errorf("unsupported ipam driver %q", ipamDriver) - } - return nil -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/config_freebsd.go b/vendor/go.podman.io/common/libnetwork/cni/config_freebsd.go deleted file mode 100644 index ddee6d2e01e..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/config_freebsd.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "os/exec" - - "github.com/sirupsen/logrus" -) - -func deleteLink(name string) { - if output, err := exec.Command("ifconfig", name, "destroy").CombinedOutput(); err != nil { - // only log the error, it is not fatal - logrus.Infof("Failed to remove network interface %s: %v: %s", name, err, output) - } -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/config_linux.go b/vendor/go.podman.io/common/libnetwork/cni/config_linux.go deleted file mode 100644 index efc920614c0..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/config_linux.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "github.com/sirupsen/logrus" - "github.com/vishvananda/netlink" -) - -func deleteLink(name string) { - link, err := netlink.LinkByName(name) - if err == nil { - err = netlink.LinkDel(link) - // only log the error, it is not fatal - if err != nil { - logrus.Infof("Failed to remove network interface %s: %v", name, err) - } - } -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/network.go b/vendor/go.podman.io/common/libnetwork/cni/network.go deleted file mode 100644 index 33220a2827b..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/network.go +++ /dev/null @@ -1,359 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "strings" - "time" - - "github.com/containernetworking/cni/libcni" - "github.com/sirupsen/logrus" - "go.podman.io/common/libnetwork/internal/rootlessnetns" - "go.podman.io/common/libnetwork/types" - "go.podman.io/common/pkg/config" - "go.podman.io/common/pkg/version" - "go.podman.io/storage/pkg/fileutils" - "go.podman.io/storage/pkg/lockfile" - "go.podman.io/storage/pkg/unshare" -) - -const defaultRootLockPath = "/run/lock/podman-cni.lock" - -type cniNetwork struct { - // cniConfigDir is directory where the cni config files are stored. - cniConfigDir string - // cniPluginDirs is a list of directories where cni should look for the plugins. - cniPluginDirs []string - - cniConf *libcni.CNIConfig - - // defaultNetwork is the name for the default network. - defaultNetwork string - // defaultSubnet is the default subnet for the default network. - defaultSubnet types.IPNet - - // defaultsubnetPools contains the subnets which must be used to allocate a free subnet by network create - defaultsubnetPools []config.SubnetPool - - // isMachine describes whenever podman runs in a podman machine environment. - isMachine bool - - // lock is a internal lock for critical operations - lock *lockfile.LockFile - - // modTime is the timestamp when the config dir was modified - modTime time.Time - - // networks is a map with loaded networks, the key is the network name - networks map[string]*network - - // rootlessNetns is used for the rootless network setup/teardown - rootlessNetns *rootlessnetns.Netns -} - -type network struct { - // filename is the full path to the cni config file on disk - filename string - libpodNet *types.Network - cniNet *libcni.NetworkConfigList -} - -type InitConfig struct { - // CNIConfigDir is directory where the cni config files are stored. - CNIConfigDir string - // RunDir is a directory where temporary files can be stored. - RunDir string - - // IsMachine describes whenever podman runs in a podman machine environment. - IsMachine bool - - // Config containers.conf options - Config *config.Config -} - -// NewCNINetworkInterface creates the ContainerNetwork interface for the CNI backend. -// Note: The networks are not loaded from disk until a method is called. -func NewCNINetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) { - var netns *rootlessnetns.Netns - var err error - // Do not use unshare.IsRootless() here. We only care if we are running re-exec in the userns, - // IsRootless() also returns true if we are root in a userns which is not what we care about and - // causes issues as this slower more complicated rootless-netns logic should not be used as root. - val, ok := os.LookupEnv(unshare.UsernsEnvName) - useRootlessNetns := ok && val == "done" - if useRootlessNetns { - netns, err = rootlessnetns.New(conf.RunDir, rootlessnetns.CNI, conf.Config) - if err != nil { - return nil, err - } - } - - // root needs to use a globally unique lock because there is only one host netns - lockPath := defaultRootLockPath - if useRootlessNetns { - lockPath = filepath.Join(conf.CNIConfigDir, "cni.lock") - } - - lock, err := lockfile.GetLockFile(lockPath) - if err != nil { - return nil, err - } - - defaultNetworkName := conf.Config.Network.DefaultNetwork - if defaultNetworkName == "" { - defaultNetworkName = types.DefaultNetworkName - } - - defaultSubnet := conf.Config.Network.DefaultSubnet - if defaultSubnet == "" { - defaultSubnet = types.DefaultSubnet - } - defaultNet, err := types.ParseCIDR(defaultSubnet) - if err != nil { - return nil, fmt.Errorf("failed to parse default subnet: %w", err) - } - - defaultSubnetPools := conf.Config.Network.DefaultSubnetPools - if defaultSubnetPools == nil { - defaultSubnetPools = config.DefaultSubnetPools - } - - cni := libcni.NewCNIConfig(conf.Config.Network.CNIPluginDirs.Values, &cniExec{}) - n := &cniNetwork{ - cniConfigDir: conf.CNIConfigDir, - cniPluginDirs: conf.Config.Network.CNIPluginDirs.Get(), - cniConf: cni, - defaultNetwork: defaultNetworkName, - defaultSubnet: defaultNet, - defaultsubnetPools: defaultSubnetPools, - isMachine: conf.IsMachine, - lock: lock, - rootlessNetns: netns, - } - - return n, nil -} - -// Drivers will return the list of supported network drivers -// for this interface. -func (n *cniNetwork) Drivers() []string { - return []string{types.BridgeNetworkDriver, types.MacVLANNetworkDriver, types.IPVLANNetworkDriver} -} - -// DefaultNetworkName will return the default cni network name. -func (n *cniNetwork) DefaultNetworkName() string { - return n.defaultNetwork -} - -func (n *cniNetwork) loadNetworks() error { - // check the mod time of the config dir - var modTime time.Time - f, err := os.Stat(n.cniConfigDir) - // ignore error if the file does not exists - if err != nil && !errors.Is(err, os.ErrNotExist) { - return err - } - if err == nil { - modTime = f.ModTime() - } - - // skip loading networks if they are already loaded and - // if the config dir was not modified since the last call - if n.networks != nil && modTime.Equal(n.modTime) { - return nil - } - // make sure the remove all networks before we reload them - n.networks = nil - n.modTime = modTime - - // FIXME: do we have to support other file types as well, e.g. .conf? - files, err := libcni.ConfFiles(n.cniConfigDir, []string{".conflist"}) - if err != nil { - return err - } - networks := make(map[string]*network, len(files)) - for _, file := range files { - conf, err := libcni.ConfListFromFile(file) - if err != nil { - // do not log ENOENT errors - if !errors.Is(err, os.ErrNotExist) { - logrus.Warnf("Error loading CNI config file %s: %v", file, err) - } - continue - } - - if !types.NameRegex.MatchString(conf.Name) { - logrus.Warnf("CNI config list %s has invalid name, skipping: %v", file, types.ErrInvalidName) - continue - } - - // podman < v4.0 used the podman-machine cni plugin for podman machine port forwarding - // since this is now build into podman we no longer use the plugin - // old configs may still contain it so we just remove it here - if n.isMachine { - conf = removeMachinePlugin(conf) - } - - if _, err := n.cniConf.ValidateNetworkList(context.Background(), conf); err != nil { - logrus.Warnf("Error validating CNI config file %s: %v", file, err) - continue - } - - if val, ok := networks[conf.Name]; ok { - logrus.Warnf("CNI config list %s has the same network name as %s, skipping", file, val.filename) - continue - } - - net, err := createNetworkFromCNIConfigList(conf, file) - if err != nil { - // ignore ENOENT as the config has been removed in the meantime so we can just ignore this case - if !errors.Is(err, fs.ErrNotExist) { - logrus.Errorf("CNI config list %s could not be converted to a libpod config, skipping: %v", file, err) - } - continue - } - logrus.Debugf("Successfully loaded network %s: %v", net.Name, net) - networkInfo := network{ - filename: file, - cniNet: conf, - libpodNet: net, - } - networks[net.Name] = &networkInfo - } - - // create the default network in memory if it did not exists on disk - if networks[n.defaultNetwork] == nil { - networkInfo, err := n.createDefaultNetwork() - if err != nil { - return fmt.Errorf("failed to create default network %s: %w", n.defaultNetwork, err) - } - networks[n.defaultNetwork] = networkInfo - } - - logrus.Debugf("Successfully loaded %d networks", len(networks)) - n.networks = networks - return nil -} - -func (n *cniNetwork) createDefaultNetwork() (*network, error) { - net := types.Network{ - Name: n.defaultNetwork, - NetworkInterface: "cni-podman0", - Driver: types.BridgeNetworkDriver, - Subnets: []types.Subnet{ - {Subnet: n.defaultSubnet}, - }, - } - return n.networkCreate(&net, true) -} - -// getNetwork will lookup a network by name or ID. It returns an -// error when no network was found or when more than one network -// with the given (partial) ID exists. -// getNetwork will read from the networks map, therefore the caller -// must ensure that n.lock is locked before using it. -func (n *cniNetwork) getNetwork(nameOrID string) (*network, error) { - // fast path check the map key, this will only work for names - if val, ok := n.networks[nameOrID]; ok { - return val, nil - } - // If there was no match we might got a full or partial ID. - var net *network - for _, val := range n.networks { - // This should not happen because we already looked up the map by name but check anyway. - if val.libpodNet.Name == nameOrID { - return val, nil - } - - if strings.HasPrefix(val.libpodNet.ID, nameOrID) { - if net != nil { - return nil, fmt.Errorf("more than one result for network ID %s", nameOrID) - } - net = val - } - } - if net != nil { - return net, nil - } - return nil, fmt.Errorf("unable to find network with name or ID %s: %w", nameOrID, types.ErrNoSuchNetwork) -} - -// getNetworkIDFromName creates a network ID from the name. It is just the -// sha256 hash so it is not safe but it should be safe enough for our use case. -func getNetworkIDFromName(name string) string { - hash := sha256.Sum256([]byte(name)) - return hex.EncodeToString(hash[:]) -} - -// Implement the NetUtil interface for easy code sharing with other network interfaces. - -// ForEach call the given function for each network. -func (n *cniNetwork) ForEach(run func(types.Network)) { - for _, val := range n.networks { - run(*val.libpodNet) - } -} - -// Len return the number of networks. -func (n *cniNetwork) Len() int { - return len(n.networks) -} - -// DefaultInterfaceName return the default cni bridge name, must be suffixed with a number. -func (n *cniNetwork) DefaultInterfaceName() string { - return cniDeviceName -} - -// NetworkInfo return the network information about binary path, -// package version and program version. -func (n *cniNetwork) NetworkInfo() types.NetworkInfo { - path := "" - packageVersion := "" - for _, p := range n.cniPluginDirs { - ver := version.Package(p) - if ver != version.UnknownPackage { - path = p - packageVersion = ver - break - } - } - - info := types.NetworkInfo{ - Backend: types.CNI, - Package: packageVersion, - Path: path, - DefaultNetwork: n.defaultNetwork, - } - - dnsPath := filepath.Join(path, "dnsname") - dnsPackage := version.Package(dnsPath) - dnsProgram, err := version.ProgramDnsname(dnsPath) - if err != nil { - logrus.Infof("Failed to get the dnsname plugin version: %v", err) - } - if err := fileutils.Exists(dnsPath); err == nil { - info.DNS = types.DNSNetworkInfo{ - Path: dnsPath, - Package: dnsPackage, - Version: dnsProgram, - } - } - - return info -} - -func (n *cniNetwork) Network(nameOrID string) (*types.Network, error) { - network, err := n.getNetwork(nameOrID) - if err != nil { - return nil, err - } - return network.libpodNet, err -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/run.go b/vendor/go.podman.io/common/libnetwork/cni/run.go deleted file mode 100644 index 7877891a9a2..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/run.go +++ /dev/null @@ -1,302 +0,0 @@ -//go:build (linux || freebsd) && cni - -package cni - -import ( - "context" - "fmt" - "net" - "os" - "strings" - - "github.com/containernetworking/cni/libcni" - cnitypes "github.com/containernetworking/cni/pkg/types" - types040 "github.com/containernetworking/cni/pkg/types/040" - "github.com/hashicorp/go-multierror" - "github.com/sirupsen/logrus" - "go.podman.io/common/libnetwork/internal/util" - "go.podman.io/common/libnetwork/types" -) - -// Setup will setup the container network namespace. It returns -// a map of StatusBlocks, the key is the network name. -func (n *cniNetwork) Setup(namespacePath string, options types.SetupOptions) (map[string]types.StatusBlock, error) { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return nil, err - } - - err = util.ValidateSetupOptions(n, namespacePath, options) - if err != nil { - return nil, err - } - - err = setupLoopback(namespacePath) - if err != nil { - return nil, fmt.Errorf("failed to set the loopback adapter up: %w", err) - } - - results := make(map[string]types.StatusBlock, len(options.Networks)) - - setup := func() error { - var retErr error - teardownOpts := options - teardownOpts.Networks = map[string]types.PerNetworkOptions{} - // make sure to teardown the already connected networks on error - defer func() { - if retErr != nil { - if len(teardownOpts.Networks) > 0 { - err := n.teardown(namespacePath, types.TeardownOptions(teardownOpts)) - if err != nil { - logrus.Warn(err) - } - } - } - }() - - ports, err := convertSpecgenPortsToCNIPorts(options.PortMappings) - if err != nil { - return err - } - - for name, netOpts := range options.Networks { - network := n.networks[name] - rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, &netOpts) - - // If we have more than one static ip we need parse the ips via runtime config, - // make sure to add the ips capability to the first plugin otherwise it doesn't get the ips - if len(netOpts.StaticIPs) > 0 && !network.cniNet.Plugins[0].Network.Capabilities["ips"] { - caps := map[string]any{ - "capabilities": map[string]bool{"ips": true}, - } - network.cniNet.Plugins[0], retErr = libcni.InjectConf(network.cniNet.Plugins[0], caps) - if retErr != nil { - return retErr - } - } - - var res cnitypes.Result - res, retErr = n.cniConf.AddNetworkList(context.Background(), network.cniNet, rt) - // Add this network to teardown opts since it is now connected. - // Also add this if an errors was returned since we want to call teardown on this regardless. - teardownOpts.Networks[name] = netOpts - if retErr != nil { - return retErr - } - - logrus.Debugf("cni result for container %s network %s: %v", options.ContainerID, name, res) - var status types.StatusBlock - status, retErr = CNIResultToStatus(res) - if retErr != nil { - return retErr - } - results[name] = status - } - return nil - } - - if n.rootlessNetns != nil { - err = n.rootlessNetns.Setup(len(options.Networks), setup) - } else { - err = setup() - } - return results, err -} - -// CNIResultToStatus convert the cni result to status block -// nolint:golint,revive -func CNIResultToStatus(res cnitypes.Result) (types.StatusBlock, error) { - result := types.StatusBlock{} - cniResult, err := types040.GetResult(res) - if err != nil { - return result, err - } - nameservers := make([]net.IP, 0, len(cniResult.DNS.Nameservers)) - for _, nameserver := range cniResult.DNS.Nameservers { - ip := net.ParseIP(nameserver) - if ip == nil { - return result, fmt.Errorf("failed to parse cni nameserver ip %s", nameserver) - } - nameservers = append(nameservers, ip) - } - result.DNSServerIPs = nameservers - result.DNSSearchDomains = cniResult.DNS.Search - - interfaces := make(map[string]types.NetInterface) - for intIndex, netInterface := range cniResult.Interfaces { - // we are only interested about interfaces in the container namespace - if netInterface.Sandbox == "" { - continue - } - - mac, err := net.ParseMAC(netInterface.Mac) - if err != nil { - return result, err - } - subnets := make([]types.NetAddress, 0, len(cniResult.IPs)) - for _, ip := range cniResult.IPs { - if ip.Interface == nil { - // we do no expect ips without an interface - continue - } - if len(cniResult.Interfaces) <= *ip.Interface { - return result, fmt.Errorf("invalid cni result, interface index %d out of range", *ip.Interface) - } - - // when we have a ip for this interface add it to the subnets - if *ip.Interface == intIndex { - subnets = append(subnets, types.NetAddress{ - IPNet: types.IPNet{IPNet: ip.Address}, - Gateway: ip.Gateway, - }) - } - } - interfaces[netInterface.Name] = types.NetInterface{ - MacAddress: types.HardwareAddr(mac), - Subnets: subnets, - } - } - result.Interfaces = interfaces - return result, nil -} - -func getRuntimeConfig(netns, conName, conID, networkName string, ports []cniPortMapEntry, opts *types.PerNetworkOptions) *libcni.RuntimeConf { - rt := &libcni.RuntimeConf{ - ContainerID: conID, - NetNS: netns, - IfName: opts.InterfaceName, - Args: [][2]string{ - {"IgnoreUnknown", "1"}, - // Do not set the K8S env vars, see https://github.com/containers/podman/issues/12083. - // Only K8S_POD_NAME is used by dnsname to get the container name. - {"K8S_POD_NAME", conName}, - }, - CapabilityArgs: map[string]any{}, - } - - // Propagate environment CNI_ARGS - for kvpairs := range strings.SplitSeq(os.Getenv("CNI_ARGS"), ";") { - if key, val, ok := strings.Cut(kvpairs, "="); ok { - rt.Args = append(rt.Args, [2]string{key, val}) - } - } - - // Add mac address to cni args - if len(opts.StaticMAC) > 0 { - rt.Args = append(rt.Args, [2]string{"MAC", opts.StaticMAC.String()}) - } - - if len(opts.StaticIPs) == 1 { - // Add a single IP to the args field. CNI plugins < 1.0.0 - // do not support multiple ips via capability args. - rt.Args = append(rt.Args, [2]string{"IP", opts.StaticIPs[0].String()}) - } else if len(opts.StaticIPs) > 1 { - // Set the static ips in the capability args - // to support more than one static ip per network. - rt.CapabilityArgs["ips"] = opts.StaticIPs - } - - // Set network aliases for the dnsname plugin. - if len(opts.Aliases) > 0 { - rt.CapabilityArgs["aliases"] = map[string][]string{ - networkName: opts.Aliases, - } - } - - // Set PortMappings in Capabilities - if len(ports) > 0 { - rt.CapabilityArgs["portMappings"] = ports - } - - return rt -} - -// Teardown will teardown the container network namespace. -func (n *cniNetwork) Teardown(namespacePath string, options types.TeardownOptions) error { - n.lock.Lock() - defer n.lock.Unlock() - err := n.loadNetworks() - if err != nil { - return err - } - return n.teardown(namespacePath, options) -} - -func (n *cniNetwork) teardown(namespacePath string, options types.TeardownOptions) error { - // Note: An empty namespacePath is allowed because some plugins - // still need teardown, for example ipam should remove used ip allocations. - - ports, err := convertSpecgenPortsToCNIPorts(options.PortMappings) - if err != nil { - return err - } - - var multiErr *multierror.Error - teardown := func() error { - for name, netOpts := range options.Networks { - rt := getRuntimeConfig(namespacePath, options.ContainerName, options.ContainerID, name, ports, &netOpts) - - cniConfList, newRt, err := getCachedNetworkConfig(n.cniConf, name, rt) - if err == nil { - rt = newRt - } else { - logrus.Warnf("Failed to load cached network config: %v, falling back to loading network %s from disk", err, name) - network := n.networks[name] - if network == nil { - multiErr = multierror.Append(multiErr, fmt.Errorf("network %s: %w", name, types.ErrNoSuchNetwork)) - continue - } - cniConfList = network.cniNet - } - - err = n.cniConf.DelNetworkList(context.Background(), cniConfList, rt) - if err != nil { - multiErr = multierror.Append(multiErr, err) - } - } - return nil - } - - if n.rootlessNetns != nil { - err = n.rootlessNetns.Teardown(len(options.Networks), teardown) - } else { - err = teardown() - } - multiErr = multierror.Append(multiErr, err) - - return multiErr.ErrorOrNil() -} - -func getCachedNetworkConfig(cniConf *libcni.CNIConfig, name string, rt *libcni.RuntimeConf) (*libcni.NetworkConfigList, *libcni.RuntimeConf, error) { - cniConfList := &libcni.NetworkConfigList{ - Name: name, - } - confBytes, rt, err := cniConf.GetNetworkListCachedConfig(cniConfList, rt) - if err != nil { - return nil, nil, err - } else if confBytes == nil { - return nil, nil, fmt.Errorf("network %s not found in CNI cache", name) - } - - cniConfList, err = libcni.ConfListFromBytes(confBytes) - if err != nil { - return nil, nil, err - } - return cniConfList, rt, nil -} - -func (n *cniNetwork) RunInRootlessNetns(toRun func() error) error { - if n.rootlessNetns == nil { - return types.ErrNotRootlessNetns - } - return n.rootlessNetns.Run(n.lock, toRun) -} - -func (n *cniNetwork) RootlessNetnsInfo() (*types.RootlessNetnsInfo, error) { - if n.rootlessNetns == nil { - return nil, types.ErrNotRootlessNetns - } - return n.rootlessNetns.Info(), nil -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/run_freebsd.go b/vendor/go.podman.io/common/libnetwork/cni/run_freebsd.go deleted file mode 100644 index cca00aa83fc..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/run_freebsd.go +++ /dev/null @@ -1,19 +0,0 @@ -package cni - -import ( - "os/exec" -) - -// FreeBSD vnet adds the lo0 interface automatically - we just need to -// add the default address. Note: this will also add ::1 as a side -// effect. -func setupLoopback(namespacePath string) error { - // Try to run the command using ifconfig's -j flag (supported in 13.3 and later) - if err := exec.Command("ifconfig", "-j", namespacePath, "lo0", "inet", "127.0.0.1").Run(); err == nil { - return nil - } - - // Fall back to using the jexec wrapper to run the ifconfig command - // inside the jail. - return exec.Command("jexec", namespacePath, "ifconfig", "lo0", "inet", "127.0.0.1").Run() -} diff --git a/vendor/go.podman.io/common/libnetwork/cni/run_linux.go b/vendor/go.podman.io/common/libnetwork/cni/run_linux.go deleted file mode 100644 index 735e4960e7d..00000000000 --- a/vendor/go.podman.io/common/libnetwork/cni/run_linux.go +++ /dev/null @@ -1,17 +0,0 @@ -package cni - -import ( - "github.com/containernetworking/plugins/pkg/ns" - "github.com/vishvananda/netlink" -) - -func setupLoopback(namespacePath string) error { - // set the loopback adapter up in the container netns - return ns.WithNetNSPath(namespacePath, func(_ ns.NetNS) error { - link, err := netlink.LinkByName("lo") - if err == nil { - err = netlink.LinkSetUp(link) - } - return err - }) -} diff --git a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns.go b/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns.go deleted file mode 100644 index edc29f66fe3..00000000000 --- a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns.go +++ /dev/null @@ -1,8 +0,0 @@ -package rootlessnetns - -type NetworkBackend int - -const ( - Netavark NetworkBackend = iota - CNI -) diff --git a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_freebsd.go b/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_freebsd.go index 03322dc52b4..f1ae4bb00c5 100644 --- a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_freebsd.go +++ b/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_freebsd.go @@ -12,7 +12,7 @@ var ErrNotSupported = errors.New("rootless netns only supported on linux") type Netns struct{} -func New(dir string, backend NetworkBackend, conf *config.Config) (*Netns, error) { +func New(dir string, conf *config.Config) (*Netns, error) { return nil, ErrNotSupported } diff --git a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_linux.go b/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_linux.go index 05b3b16dd67..049df8dc357 100644 --- a/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_linux.go +++ b/vendor/go.podman.io/common/libnetwork/internal/rootlessnetns/netns_linux.go @@ -11,7 +11,6 @@ import ( "strconv" "strings" - "github.com/containernetworking/plugins/pkg/ns" "github.com/hashicorp/go-multierror" "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/selinux/go-selinux/label" @@ -41,9 +40,6 @@ const ( // rootlessNetNsConnPidFile is the name of the rootless netns slirp4netns/pasta pid file. rootlessNetNsConnPidFile = "rootless-netns-conn.pid" - // persistentCNIDir is the directory where the CNI files are stored. - persistentCNIDir = "/var/lib/cni" - tmpfs = "tmpfs" none = "none" resolvConfName = "resolv.conf" @@ -52,8 +48,6 @@ const ( type Netns struct { // dir used for the rootless netns dir string - // backend used for the network setup/teardown - backend NetworkBackend // config contains containers.conf options. config *config.Config @@ -88,15 +82,14 @@ func wrapError(msg string, err error) *rootlessNetnsError { } } -func New(dir string, backend NetworkBackend, conf *config.Config) (*Netns, error) { +func New(dir string, conf *config.Config) (*Netns, error) { netnsDir := filepath.Join(dir, rootlessNetnsDir) if err := os.MkdirAll(netnsDir, 0o700); err != nil { return nil, wrapError("", err) } return &Netns{ - dir: netnsDir, - backend: backend, - config: conf, + dir: netnsDir, + config: conf, }, nil } @@ -107,9 +100,9 @@ func (n *Netns) getPath(path string) string { // getOrCreateNetns returns the rootless netns, if it created a new one the // returned bool is set to true. -func (n *Netns) getOrCreateNetns() (ns.NetNS, bool, error) { +func (n *Netns) getOrCreateNetns() (netns.NetNS, bool, error) { nsPath := n.getPath(rootlessNetnsDir) - nsRef, err := ns.GetNS(nsPath) + nsRef, err := netns.GetNS(nsPath) if err == nil { pidPath := n.getPath(rootlessNetNsConnPidFile) pid, err := readPidFile(pidPath) @@ -140,7 +133,7 @@ func (n *Netns) getOrCreateNetns() (ns.NetNS, bool, error) { // the file and mounting it. Or if the file is not on tmpfs (deleted on boot) // you might run into it as well: https://github.com/containers/podman/issues/25144 // We have to do this because NewNSAtPath fails with EEXIST otherwise - if errors.As(err, &ns.NSPathNotNSErr{}) { + if errors.As(err, &netns.NSPathNotNSErr{}) { // We don't care if this fails, NewNSAtPath() should return the real error. _ = os.Remove(nsPath) } @@ -349,16 +342,15 @@ func (n *Netns) setupMounts() error { // we have to set up all mounts correctly. // The order of the mounts is IMPORTANT. - // The idea of the extra mount ns is to make /run and /var/lib/cni writeable - // for the cni plugins but not affecting the podman user namespace. + // The idea of the extra mount ns is to make /run writeable + // for the network plugins but not affecting the podman user namespace. // Because the plugins also need access to XDG_RUNTIME_DIR/netns some special setup is needed. // The following bind mounts are needed // 1. XDG_RUNTIME_DIR -> XDG_RUNTIME_DIR/rootless-netns/XDG_RUNTIME_DIR // 2. /run/systemd -> XDG_RUNTIME_DIR/rootless-netns/run/systemd (only if it exists) // 3. XDG_RUNTIME_DIR/rootless-netns/resolv.conf -> /etc/resolv.conf or XDG_RUNTIME_DIR/rootless-netns/run/symlink/target - // 4. XDG_RUNTIME_DIR/rootless-netns/var/lib/cni -> /var/lib/cni (if /var/lib/cni does not exist, use the parent dir) - // 5. XDG_RUNTIME_DIR/rootless-netns/run -> /run + // 4. XDG_RUNTIME_DIR/rootless-netns/run -> /run // Create a new mount namespace, // this must happen inside the netns thread. @@ -385,7 +377,7 @@ func (n *Netns) setupMounts() error { } newXDGRuntimeDir := n.getPath(xdgRuntimeDir) // 1. Mount the netns into the new run to keep them accessible. - // Otherwise cni setup will fail because it cannot access the netns files. + // Otherwise network setup will fail because it cannot access the netns files. err = mountAndMkdirDest(xdgRuntimeDir, newXDGRuntimeDir, none, unix.MS_BIND|unix.MS_REC) if err != nil { return err @@ -501,14 +493,7 @@ func (n *Netns) setupMounts() error { return wrapError(fmt.Sprintf("mount resolv.conf to %q", resolvePath), err) } - // 4. CNI plugins need access to /var/lib/cni - if n.backend == CNI { - if err := n.mountCNIVarDir(); err != nil { - return err - } - } - - // 5. Mount the new prepared run dir to /run, it has to be recursive to keep the other bind mounts. + // 4. Mount the new prepared run dir to /run, it has to be recursive to keep the other bind mounts. runDir := n.getPath("run") err = os.MkdirAll(runDir, 0o700) if err != nil { @@ -530,36 +515,6 @@ func (n *Netns) setupMounts() error { return nil } -func (n *Netns) mountCNIVarDir() error { - varDir := "" - varTarget := persistentCNIDir - // we can only mount to a target dir which exists, check /var/lib/cni recursively - // while we could always use /var there are cases where a user might store the cni - // configs under /var/custom and this would break - for { - if err := fileutils.Exists(varTarget); err == nil { - varDir = n.getPath(varTarget) - break - } - varTarget = filepath.Dir(varTarget) - if varTarget == "/" { - break - } - } - if varDir == "" { - return errors.New("failed to stat /var directory") - } - if err := os.MkdirAll(varDir, 0o700); err != nil { - return wrapError("create var dir", err) - } - // make sure to mount var first - err := unix.Mount(varDir, varTarget, none, unix.MS_BIND, "") - if err != nil { - return wrapError(fmt.Sprintf("mount %q to %q", varDir, varTarget), err) - } - return nil -} - func (n *Netns) runInner(toRun func() error, cleanup bool) (err error) { nsRef, newNs, err := n.getOrCreateNetns() if err != nil { @@ -577,7 +532,7 @@ func (n *Netns) runInner(toRun func() error, cleanup bool) (err error) { }() } - return nsRef.Do(func(_ ns.NetNS) error { + return nsRef.Do(func(_ netns.NetNS) error { if err := n.setupMounts(); err != nil { return err } diff --git a/vendor/go.podman.io/common/libnetwork/netavark/config.go b/vendor/go.podman.io/common/libnetwork/netavark/config.go index 7dcbe7bb3c7..f8631d2895d 100644 --- a/vendor/go.podman.io/common/libnetwork/netavark/config.go +++ b/vendor/go.podman.io/common/libnetwork/netavark/config.go @@ -153,7 +153,7 @@ func (n *netavarkNetwork) networkCreate(newNetwork *types.Network, defaultNet bo // Only get the used networks for validation if we do not create the default network. // The default network should not be validated against used subnets, we have to ensure // that this network can always be created even when a subnet is already used on the host. - // This could happen if you run a container on this net, then the cni interface will be + // This could happen if you run a container on this net, then the network interface will be // created on the host and "block" this subnet from being used again. // Therefore the next podman command tries to create the default net again and it would // fail because it thinks the network is used on the host. diff --git a/vendor/go.podman.io/common/libnetwork/netavark/network.go b/vendor/go.podman.io/common/libnetwork/netavark/network.go index 9dbe3b452da..3a35b2af82c 100644 --- a/vendor/go.podman.io/common/libnetwork/netavark/network.go +++ b/vendor/go.podman.io/common/libnetwork/netavark/network.go @@ -104,7 +104,7 @@ func NewNetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) { val, ok := os.LookupEnv(unshare.UsernsEnvName) useRootlessNetns := ok && val == "done" if useRootlessNetns { - netns, err = rootlessnetns.New(conf.NetworkRunDir, rootlessnetns.Netavark, conf.Config) + netns, err = rootlessnetns.New(conf.NetworkRunDir, conf.Config) if err != nil { return nil, err } @@ -354,7 +354,7 @@ func (n *netavarkNetwork) Len() int { return len(n.networks) } -// DefaultInterfaceName return the default cni bridge name, must be suffixed with a number. +// DefaultInterfaceName return the default bridge name, must be suffixed with a number. func (n *netavarkNetwork) DefaultInterfaceName() string { return defaultBridgeName } diff --git a/vendor/go.podman.io/common/libnetwork/network/interface.go b/vendor/go.podman.io/common/libnetwork/network/interface.go index 82955b6edfb..4a08e85339f 100644 --- a/vendor/go.podman.io/common/libnetwork/network/interface.go +++ b/vendor/go.podman.io/common/libnetwork/network/interface.go @@ -3,51 +3,41 @@ package network import ( - "errors" "fmt" - "os" "path/filepath" - "github.com/sirupsen/logrus" "go.podman.io/common/libnetwork/netavark" "go.podman.io/common/libnetwork/types" "go.podman.io/common/pkg/config" "go.podman.io/storage" - "go.podman.io/storage/pkg/ioutils" "go.podman.io/storage/pkg/unshare" ) const ( - // defaultNetworkBackendFileName is the file name for sentinel file to store the backend. - defaultNetworkBackendFileName = "defaultNetworkBackend" - // netavarkBinary is the name of the netavark binary. netavarkBinary = "netavark" // aardvarkBinary is the name of the aardvark binary. aardvarkBinary = "aardvark-dns" ) -// NetworkBackend returns the network backend name and interface -// It returns either the CNI or netavark backend depending on what is set in the config. -// If the backend is set to "" we will automatically assign the backend on the following conditions: -// 1. read ${graphroot}/defaultNetworkBackend -// 2. find netavark binary (if not installed use CNI) -// 3. check containers, images and CNI networks and if there are some we have an existing install and should continue to use CNI +// NetworkBackend returns the network backend name and interface. +// It returns the netavark backend. If no backend is set in the config, +// it defaults to netavark. Any other backend value is an error. // // revive does not like the name because the package is already called network // //nolint:revive func NetworkBackend(store storage.Store, conf *config.Config, syslog bool) (types.NetworkBackend, types.ContainerNetwork, error) { backend := types.NetworkBackend(conf.Network.NetworkBackend) - if backend == "" { - var err error - backend, err = defaultNetworkBackend(store, conf) - if err != nil { - return "", nil, fmt.Errorf("failed to get default network backend: %w", err) - } + if backend != "" && backend != types.Netavark { + return "", nil, fmt.Errorf("unsupported network backend %q, only netavark is supported", backend) } - return backendFromType(backend, store, conf, syslog) + netInt, err := netavarkBackendFromConf(store, conf, syslog) + if err != nil { + return "", nil, err + } + return types.Netavark, netInt, nil } func netavarkBackendFromConf(store storage.Store, conf *config.Config, syslog bool) (types.ContainerNetwork, error) { @@ -83,60 +73,6 @@ func netavarkBackendFromConf(store storage.Store, conf *config.Config, syslog bo return netInt, err } -func defaultNetworkBackend(store storage.Store, conf *config.Config) (backend types.NetworkBackend, err error) { - err = nil - - file := filepath.Join(store.GraphRoot(), defaultNetworkBackendFileName) - - writeBackendToFile := func(backendT types.NetworkBackend) { - // only write when there is no error - if err == nil { - if err := ioutils.AtomicWriteFile(file, []byte(backendT), 0o644); err != nil { - logrus.Errorf("could not write network backend to file: %v", err) - } - } - } - - // read defaultNetworkBackend file - b, err := os.ReadFile(file) - if err == nil { - val := string(b) - - // if the network backend has been already set previously, - // handle the values depending on whether CNI is supported and - // whether the network backend is explicitly configured - if val == string(types.Netavark) { - // netavark is always good - return types.Netavark, nil - } else if val == string(types.CNI) { - if cniSupported { - return types.CNI, nil - } - // the user has *not* configured a network - // backend explicitly but used CNI in the past - // => we upgrade them in this case to netavark only - writeBackendToFile(types.Netavark) - logrus.Info("Migrating network backend to netavark as no backend has been configured previously") - return types.Netavark, nil - } - return "", fmt.Errorf("unknown network backend value %q in %q", val, file) - } - - // fail for all errors except ENOENT - if !errors.Is(err, os.ErrNotExist) { - return "", fmt.Errorf("could not read network backend value: %w", err) - } - - backend, err = networkBackendFromStore(store, conf) - if err != nil { - return "", err - } - // cache the network backend to make sure always the same one will be used - writeBackendToFile(backend) - - return backend, nil -} - // getDefaultNetavarkConfigDir return the netavark config dir. For rootful it will // use "/etc/containers/networks" and for rootless "$graphroot/networks". We cannot // use the graphroot for rootful since the network namespace is shared for all diff --git a/vendor/go.podman.io/common/libnetwork/network/interface_cni.go b/vendor/go.podman.io/common/libnetwork/network/interface_cni.go deleted file mode 100644 index a46ff251826..00000000000 --- a/vendor/go.podman.io/common/libnetwork/network/interface_cni.go +++ /dev/null @@ -1,119 +0,0 @@ -//go:build (linux || freebsd) && cni - -package network - -import ( - "errors" - "fmt" - "os" - "path/filepath" - - "go.podman.io/common/libnetwork/cni" - "go.podman.io/common/libnetwork/types" - "go.podman.io/common/pkg/config" - "go.podman.io/common/pkg/machine" - "go.podman.io/storage" - "go.podman.io/storage/pkg/homedir" - "go.podman.io/storage/pkg/unshare" -) - -const ( - // cniConfigDirRootless is the directory in XDG_CONFIG_HOME for cni plugins. - cniConfigDirRootless = "cni/net.d/" - - cniSupported = true -) - -func getCniInterface(conf *config.Config) (types.ContainerNetwork, error) { - confDir := conf.Network.NetworkConfigDir - if confDir == "" { - var err error - confDir, err = getDefaultCNIConfigDir() - if err != nil { - return nil, err - } - } - return cni.NewCNINetworkInterface(&cni.InitConfig{ - Config: conf, - CNIConfigDir: confDir, - RunDir: conf.Engine.TmpDir, - IsMachine: machine.IsGvProxyBased(), - }) -} - -func getDefaultCNIConfigDir() (string, error) { - if !unshare.IsRootless() { - return cniConfigDir, nil - } - - configHome, err := homedir.GetConfigHome() - if err != nil { - return "", err - } - - return filepath.Join(configHome, cniConfigDirRootless), nil -} - -func networkBackendFromStore(store storage.Store, conf *config.Config) (backend types.NetworkBackend, err error) { - _, err = conf.FindHelperBinary("netavark", false) - if err != nil { - // if we cannot find netavark use CNI - return types.CNI, nil - } - - // If there are any containers then return CNI - cons, err := store.Containers() - if err != nil { - return "", err - } - if len(cons) != 0 { - return types.CNI, nil - } - - // If there are any non ReadOnly images then return CNI - imgs, err := store.Images() - if err != nil { - return "", err - } - for _, i := range imgs { - if !i.ReadOnly { - return types.CNI, nil - } - } - - // If there are CNI Networks then return CNI - cniInterface, err := getCniInterface(conf) - if err == nil { - nets, err := cniInterface.NetworkList() - // there is always a default network so check > 1 - if err != nil && !errors.Is(err, os.ErrNotExist) { - return "", err - } - - if len(nets) > 1 { - // we do not have a fresh system so use CNI - return types.CNI, nil - } - } - return types.Netavark, nil -} - -func backendFromType(backend types.NetworkBackend, store storage.Store, conf *config.Config, syslog bool) (types.NetworkBackend, types.ContainerNetwork, error) { - switch backend { - case types.Netavark: - netInt, err := netavarkBackendFromConf(store, conf, syslog) - if err != nil { - return "", nil, err - } - return types.Netavark, netInt, err - case types.CNI: - netInt, err := getCniInterface(conf) - if err != nil { - return "", nil, err - } - return types.CNI, netInt, err - - default: - return "", nil, fmt.Errorf("unsupported network backend %q, check network_backend in containers.conf", backend) - } -} diff --git a/vendor/go.podman.io/common/libnetwork/network/interface_cni_unsupported.go b/vendor/go.podman.io/common/libnetwork/network/interface_cni_unsupported.go deleted file mode 100644 index 5d94fb8cadc..00000000000 --- a/vendor/go.podman.io/common/libnetwork/network/interface_cni_unsupported.go +++ /dev/null @@ -1,30 +0,0 @@ -//go:build (linux || freebsd) && !cni - -package network - -import ( - "fmt" - - "go.podman.io/common/libnetwork/types" - "go.podman.io/common/pkg/config" - "go.podman.io/storage" -) - -const ( - cniSupported = false -) - -func networkBackendFromStore(_store storage.Store, _conf *config.Config) (backend types.NetworkBackend, err error) { - return types.Netavark, nil -} - -func backendFromType(backend types.NetworkBackend, store storage.Store, conf *config.Config, syslog bool) (types.NetworkBackend, types.ContainerNetwork, error) { - if backend != types.Netavark { - return "", nil, fmt.Errorf("cni support is not enabled in this build, only netavark. Got unsupported network backend %q", backend) - } - cn, err := netavarkBackendFromConf(store, conf, syslog) - if err != nil { - return "", nil, err - } - return types.Netavark, cn, err -} diff --git a/vendor/go.podman.io/common/libnetwork/network/interface_freebsd.go b/vendor/go.podman.io/common/libnetwork/network/interface_freebsd.go index 4d60b25c7c5..42fa78bc713 100644 --- a/vendor/go.podman.io/common/libnetwork/network/interface_freebsd.go +++ b/vendor/go.podman.io/common/libnetwork/network/interface_freebsd.go @@ -1,8 +1,6 @@ package network const ( - // cniConfigDir is the directory where cni configuration is found - cniConfigDir = "/usr/local/etc/cni/net.d/" // netavarkConfigDir is the config directory for the rootful network files netavarkConfigDir = "/usr/local/etc/containers/networks" // netavarkRunDir is the run directory for the rootful temporary network files such as the ipam db diff --git a/vendor/go.podman.io/common/libnetwork/network/interface_linux.go b/vendor/go.podman.io/common/libnetwork/network/interface_linux.go index 7a5db69a58d..f89acfd1026 100644 --- a/vendor/go.podman.io/common/libnetwork/network/interface_linux.go +++ b/vendor/go.podman.io/common/libnetwork/network/interface_linux.go @@ -1,8 +1,6 @@ package network const ( - // cniConfigDir is the directory where cni configuration is found. - cniConfigDir = "/etc/cni/net.d/" // netavarkConfigDir is the config directory for the rootful network files. netavarkConfigDir = "/etc/containers/networks" // netavarkRunDir is the run directory for the rootful temporary network files such as the ipam db. diff --git a/vendor/go.podman.io/common/libnetwork/pasta/pasta_linux.go b/vendor/go.podman.io/common/libnetwork/pasta/pasta_linux.go index a72e7adfdec..91bbb165344 100644 --- a/vendor/go.podman.io/common/libnetwork/pasta/pasta_linux.go +++ b/vendor/go.podman.io/common/libnetwork/pasta/pasta_linux.go @@ -18,11 +18,11 @@ import ( "slices" "strings" - "github.com/containernetworking/plugins/pkg/ns" "github.com/sirupsen/logrus" "go.podman.io/common/libnetwork/types" "go.podman.io/common/libnetwork/util" "go.podman.io/common/pkg/config" + "go.podman.io/common/pkg/netns" ) const ( @@ -104,7 +104,7 @@ func Setup(opts *SetupOptions) (*SetupResult, error) { var ipv4, ipv6 bool result := &SetupResult{} - err = ns.WithNetNSPath(opts.Netns, func(_ ns.NetNS) error { + err = netns.WithNetNSPath(opts.Netns, func(_ netns.NetNS) error { addrs, err := net.InterfaceAddrs() if err != nil { return err diff --git a/vendor/go.podman.io/common/libnetwork/slirp4netns/slirp4netns.go b/vendor/go.podman.io/common/libnetwork/slirp4netns/slirp4netns.go index 397f55f505c..74126c608ca 100644 --- a/vendor/go.podman.io/common/libnetwork/slirp4netns/slirp4netns.go +++ b/vendor/go.podman.io/common/libnetwork/slirp4netns/slirp4netns.go @@ -18,10 +18,10 @@ import ( "syscall" "time" - "github.com/containernetworking/plugins/pkg/ns" "github.com/sirupsen/logrus" "go.podman.io/common/libnetwork/types" "go.podman.io/common/pkg/config" + "go.podman.io/common/pkg/netns" "go.podman.io/common/pkg/rootlessport" "go.podman.io/common/pkg/servicereaper" "go.podman.io/common/pkg/util" @@ -334,7 +334,7 @@ func Setup(opts *SetupOptions) (*SetupResult, error) { netnsReadyWg.Add(1) go func() { - err := ns.WithNetNSPath(opts.Netns, func(_ ns.NetNS) error { + err := netns.WithNetNSPath(opts.Netns, func(_ netns.NetNS) error { // Duplicate Address Detection slows the ipv6 setup down for 1-2 seconds. // Since slirp4netns is run in its own namespace and not directly routed // we can skip this to make the ipv6 address immediately available. diff --git a/vendor/go.podman.io/common/libnetwork/types/const.go b/vendor/go.podman.io/common/libnetwork/types/const.go index d8730dcdf04..c027d933b4b 100644 --- a/vendor/go.podman.io/common/libnetwork/types/const.go +++ b/vendor/go.podman.io/common/libnetwork/types/const.go @@ -19,9 +19,9 @@ const ( // NoneIPAMDriver do not provide ipam management. NoneIPAMDriver = "none" - // DefaultSubnet is the name that will be used for the default CNI network. + // DefaultNetworkName is the name that will be used for the default network. DefaultNetworkName = "podman" - // DefaultSubnet is the subnet that will be used for the default CNI network. + // DefaultSubnet is the subnet that will be used for the default network. DefaultSubnet = "10.88.0.0/16" BridgeModeManaged = "managed" @@ -52,7 +52,6 @@ const ( type NetworkBackend string const ( - CNI NetworkBackend = "cni" Netavark NetworkBackend = "netavark" ) diff --git a/vendor/go.podman.io/common/pkg/config/config.go b/vendor/go.podman.io/common/pkg/config/config.go index b434e011dea..445acdfbfe9 100644 --- a/vendor/go.podman.io/common/pkg/config/config.go +++ b/vendor/go.podman.io/common/pkg/config/config.go @@ -47,7 +47,7 @@ type Config struct { Engine EngineConfig `toml:"engine"` // Machine specifies configurations of podman machine VMs Machine MachineConfig `toml:"machine"` - // Network section defines the configuration of CNI Plugins + // Network section defines the configuration of network plugins Network NetworkConfig `toml:"network"` // Secret section defines configurations for the secret management Secrets SecretConfig `toml:"secrets"` @@ -590,9 +590,6 @@ type NetworkConfig struct { // networking. NetworkBackend string `toml:"network_backend,omitempty"` - // CNIPluginDirs is where CNI plugin binaries are stored. - CNIPluginDirs attributedstring.Slice `toml:"cni_plugin_dirs,omitempty"` - // NetavarkPluginDirs is a list of directories which contain netavark plugins. NetavarkPluginDirs attributedstring.Slice `toml:"netavark_plugin_dirs,omitempty"` diff --git a/vendor/go.podman.io/common/pkg/config/containers.conf b/vendor/go.podman.io/common/pkg/config/containers.conf index c2249c3740c..f07c9dbf31e 100644 --- a/vendor/go.podman.io/common/pkg/config/containers.conf +++ b/vendor/go.podman.io/common/pkg/config/containers.conf @@ -354,25 +354,10 @@ default_sysctls = [ [network] # Network backend determines what network driver will be used to set up and tear down container networks. -# Valid values are "cni" and "netavark". -# The default value is empty which means that it will automatically choose CNI or netavark. If there are -# already containers/images or CNI networks preset it will choose CNI. -# -# Before changing this value all containers must be stopped otherwise it is likely that -# firewall rules and network interfaces might leak on the host. A reboot will fix this. +# The only supported value is "netavark". # #network_backend = "" -# Path to directory where CNI plugin binaries are located. -# -#cni_plugin_dirs = [ -# "/usr/local/libexec/cni", -# "/usr/libexec/cni", -# "/usr/local/lib/cni", -# "/usr/lib/cni", -# "/opt/cni/bin", -#] - # List of directories that will be searched for netavark plugins. # #netavark_plugin_dirs = [ @@ -426,12 +411,10 @@ default_sysctls = [ #default_rootless_network_cmd = "pasta" # Path to the directory where network configuration files are located. -# For the CNI backend the default is "/etc/cni/net.d" as root -# and "$HOME/.config/cni/net.d" as rootless. -# For the netavark backend "/etc/containers/networks" is used as root +# The default is "/etc/containers/networks" as root # and "$graphroot/networks" as rootless. # -#network_config_dir = "/etc/cni/net.d/" +#network_config_dir = "/etc/containers/networks" # Port to use for dns forwarding daemon with netavark in rootful bridge # mode and dns enabled. diff --git a/vendor/go.podman.io/common/pkg/config/containers.conf-freebsd b/vendor/go.podman.io/common/pkg/config/containers.conf-freebsd index d76235a24d8..620bd0ca4f1 100644 --- a/vendor/go.podman.io/common/pkg/config/containers.conf-freebsd +++ b/vendor/go.podman.io/common/pkg/config/containers.conf-freebsd @@ -271,25 +271,10 @@ default_sysctls = [ [network] # Network backend determines what network driver will be used to set up and tear down container networks. -# Valid values are "cni" and "netavark". -# The default value is empty which means that it will automatically choose CNI or netavark. If there are -# already containers/images or CNI networks preset it will choose CNI. -# -# Before changing this value all containers must be stopped otherwise it is likely that -# iptables rules and network interfaces might leak on the host. A reboot will fix this. +# The only supported value is "netavark". # #network_backend = "" -# Path to directory where CNI plugin binaries are located. -# -#cni_plugin_dirs = [ -# "/usr/local/libexec/cni", -# "/usr/libexec/cni", -# "/usr/local/lib/cni", -# "/usr/lib/cni", -# "/opt/cni/bin", -#] - # List of directories that will be searched for netavark plugins. # #netavark_plugin_dirs = [ @@ -328,12 +313,10 @@ default_sysctls = [ #] # Path to the directory where network configuration files are located. -# For the CNI backend the default is "/etc/cni/net.d" as root -# and "$HOME/.config/cni/net.d" as rootless. -# For the netavark backend "/etc/containers/networks" is used as root +# The default is "/usr/local/etc/containers/networks" as root # and "$graphroot/networks" as rootless. # -#network_config_dir = "/usr/local/etc/cni/net.d/" +#network_config_dir = "/usr/local/etc/containers/networks" # The default host IPs to bind published container ports to when no host IP # is explicitly specified in the -p flag (e.g., -p 8000:8000). If empty, the default diff --git a/vendor/go.podman.io/common/pkg/config/default.go b/vendor/go.podman.io/common/pkg/config/default.go index ee4dd63791b..f7c425546f8 100644 --- a/vendor/go.podman.io/common/pkg/config/default.go +++ b/vendor/go.podman.io/common/pkg/config/default.go @@ -117,14 +117,6 @@ var ( "CAP_SYS_CHROOT", } - // Search these locations in which CNIPlugins can be installed. - DefaultCNIPluginDirs = []string{ - "/usr/local/libexec/cni", - "/usr/libexec/cni", - "/usr/local/lib/cni", - "/usr/lib/cni", - "/opt/cni/bin", - } DefaultNetavarkPluginDirs = []string{ "/usr/local/libexec/netavark", "/usr/libexec/netavark", @@ -272,7 +264,6 @@ func defaultConfig() (*Config, error) { DefaultSubnetPools: DefaultSubnetPools, DefaultRootlessNetworkCmd: "pasta", DNSBindPort: 0, - CNIPluginDirs: attributedstring.NewSlice(DefaultCNIPluginDirs), NetavarkPluginDirs: attributedstring.NewSlice(DefaultNetavarkPluginDirs), }, Engine: *defaultEngineConfig, diff --git a/vendor/go.podman.io/common/pkg/netns/netns_linux.go b/vendor/go.podman.io/common/pkg/netns/netns_linux.go index 4283ffd8d7b..c2ee879d628 100644 --- a/vendor/go.podman.io/common/pkg/netns/netns_linux.go +++ b/vendor/go.podman.io/common/pkg/netns/netns_linux.go @@ -1,4 +1,4 @@ -// Copyright 2018 CNI authors +// Copyright 2015-2018 CNI authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,9 +29,9 @@ import ( "runtime" "strings" "sync" + "syscall" "time" - "github.com/containernetworking/plugins/pkg/ns" "github.com/sirupsen/logrus" "go.podman.io/storage/pkg/homedir" "go.podman.io/storage/pkg/unshare" @@ -43,6 +43,209 @@ const threadNsPath = "/proc/thread-self/ns/net" var errNoFreeName = errors.New("failed to find free netns path name") +// NetNS defines a network namespace. +type NetNS interface { + // Do executes the passed closure in this object's network namespace, + // attempting to restore the original namespace before returning. + // However, since each OS thread can have a different network namespace, + // and Go's thread scheduling is highly variable, callers cannot + // guarantee any specific namespace is set unless operations that + // require that namespace are wrapped with Do(). Also, no code called + // from Do() should call runtime.UnlockOSThread(), or the risk + // of executing code in an incorrect namespace will be greater. See + // https://github.com/golang/go/wiki/LockOSThread for further details. + Do(toRun func(NetNS) error) error + + // Set sets the current network namespace to this object's network namespace. + // Note that since Go's thread scheduling is highly variable, callers + // cannot guarantee the requested namespace will be the current namespace + // after this function is called; to ensure this wrap operations that + // require the namespace with Do() instead. + Set() error + + // Path returns the filesystem path representing this object's network namespace. + Path() string + + // Fd returns a file descriptor representing this object's network namespace. + Fd() uintptr + + // Close cleans up this instance of the network namespace; if this instance + // is the last user the namespace will be destroyed. + Close() error +} + +type netNS struct { + file *os.File + closed bool +} + +// netNS implements the NetNS interface. +var _ NetNS = &netNS{} + +const ( + // https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h + nsfsMagic = unix.NSFS_MAGIC + procfsMagic = unix.PROC_SUPER_MAGIC +) + +// NSPathNotExistErr is returned when the netns path does not exist. +type NSPathNotExistErr struct{ msg string } + +func (e NSPathNotExistErr) Error() string { return e.msg } + +// NSPathNotNSErr is returned when the path exists but is not a network namespace. +type NSPathNotNSErr struct{ msg string } + +func (e NSPathNotNSErr) Error() string { return e.msg } + +// IsNSorErr checks whether the given path is a network namespace. +func IsNSorErr(nspath string) error { + stat := syscall.Statfs_t{} + if err := syscall.Statfs(nspath, &stat); err != nil { + if os.IsNotExist(err) { + err = NSPathNotExistErr{msg: fmt.Sprintf("failed to Statfs %q: %v", nspath, err)} + } else { + err = fmt.Errorf("failed to Statfs %q: %v", nspath, err) + } + return err + } + + switch stat.Type { + case procfsMagic, nsfsMagic: + return nil + default: + return NSPathNotNSErr{msg: fmt.Sprintf("unknown FS magic on %q: %x", nspath, stat.Type)} + } +} + +// GetNS returns an object representing the namespace referred to by @path. +func GetNS(nspath string) (NetNS, error) { + err := IsNSorErr(nspath) + if err != nil { + return nil, err + } + + fd, err := os.Open(nspath) + if err != nil { + return nil, err + } + + return &netNS{file: fd}, nil +} + +// GetCurrentNS returns an object representing the current OS thread's network namespace. +func GetCurrentNS() (NetNS, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + return GetNS(threadNsPath) +} + +// WithNetNSPath executes the passed closure under the given network +// namespace, restoring the original namespace afterwards. +func WithNetNSPath(nspath string, toRun func(NetNS) error) error { + ns, err := GetNS(nspath) + if err != nil { + return err + } + defer ns.Close() + return ns.Do(toRun) +} + +func (ns *netNS) Path() string { + return ns.file.Name() +} + +func (ns *netNS) Fd() uintptr { + return ns.file.Fd() +} + +func (ns *netNS) errorIfClosed() error { + if ns.closed { + return fmt.Errorf("%q has already been closed", ns.file.Name()) + } + return nil +} + +func (ns *netNS) Close() error { + if err := ns.errorIfClosed(); err != nil { + return err + } + + if err := ns.file.Close(); err != nil { + return fmt.Errorf("failed to close %q: %v", ns.file.Name(), err) + } + ns.closed = true + + return nil +} + +func (ns *netNS) Set() error { + if err := ns.errorIfClosed(); err != nil { + return err + } + + if err := unix.Setns(int(ns.Fd()), unix.CLONE_NEWNET); err != nil { + return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err) + } + + return nil +} + +func (ns *netNS) Do(toRun func(NetNS) error) error { + if err := ns.errorIfClosed(); err != nil { + return err + } + + containedCall := func(hostNS NetNS) error { + threadNS, err := GetNS(threadNsPath) + if err != nil { + return fmt.Errorf("failed to open current netns: %v", err) + } + defer threadNS.Close() + + // switch to target namespace + if err = ns.Set(); err != nil { + return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err) + } + defer func() { + err := threadNS.Set() // switch back + if err == nil { + // Unlock the current thread only when we successfully switched back + // to the original namespace; otherwise leave the thread locked which + // will force the runtime to scrap the current thread, that is maybe + // not as optimal but at least always safe to do. + runtime.UnlockOSThread() + } + }() + + return toRun(hostNS) + } + + // save a handle to current network namespace + hostNS, err := GetCurrentNS() + if err != nil { + return fmt.Errorf("failed to open current namespace: %v", err) + } + defer hostNS.Close() + + var wg sync.WaitGroup + wg.Add(1) + + // Start the callback in a new green thread so that if we later fail + // to switch the namespace back to the original one, we can safely + // leave the thread locked to die without a risk of the current thread + // left lingering with incorrect namespace. + var innerError error + go func() { + defer wg.Done() + runtime.LockOSThread() + innerError = containedCall(hostNS) + }() + wg.Wait() + + return innerError +} + // GetNSRunDir returns the dir of where to create the netNS. When running // rootless, it needs to be at a location writable by user. func GetNSRunDir() (string, error) { @@ -56,13 +259,15 @@ func GetNSRunDir() (string, error) { return "/run/netns", nil } -func NewNSAtPath(nsPath string) (ns.NetNS, error) { +// NewNSAtPath creates a new persistent (bind-mounted) network namespace +// at the given path and returns an object representing that namespace. +func NewNSAtPath(nsPath string) (NetNS, error) { return newNSPath(nsPath) } // NewNS creates a new persistent (bind-mounted) network namespace and returns // an object representing that namespace, without switching to it. -func NewNS() (ns.NetNS, error) { +func NewNS() (NetNS, error) { nsRunDir, err := GetNSRunDir() if err != nil { return nil, err @@ -208,7 +413,7 @@ func createNetnsFile(path string) error { return mountPointFd.Close() } -func newNSPath(nsPath string) (ns.NetNS, error) { +func newNSPath(nsPath string) (NetNS, error) { // create an empty file to use as at the mount point err := createNetnsFile(nsPath) if err != nil { @@ -253,7 +458,7 @@ func newNSPath(nsPath string) (ns.NetNS, error) { return nil, fmt.Errorf("failed to create namespace: %v", err) } - return ns.GetNS(nsPath) + return GetNS(nsPath) } // UnmountNS unmounts the given netns path. diff --git a/vendor/golang.org/x/crypto/sha3/hashes.go b/vendor/golang.org/x/crypto/sha3/hashes.go deleted file mode 100644 index a51269d91aa..00000000000 --- a/vendor/golang.org/x/crypto/sha3/hashes.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sha3 implements the SHA-3 hash algorithms and the SHAKE extendable -// output functions defined in FIPS 202. -// -// Most of this package is a wrapper around the crypto/sha3 package in the -// standard library. The only exception is the legacy Keccak hash functions. -package sha3 - -import ( - "crypto/sha3" - "hash" -) - -// New224 creates a new SHA3-224 hash. -// Its generic security strength is 224 bits against preimage attacks, -// and 112 bits against collision attacks. -// -// It is a wrapper for the [sha3.New224] function in the standard library. -// -//go:fix inline -func New224() hash.Hash { - return sha3.New224() -} - -// New256 creates a new SHA3-256 hash. -// Its generic security strength is 256 bits against preimage attacks, -// and 128 bits against collision attacks. -// -// It is a wrapper for the [sha3.New256] function in the standard library. -// -//go:fix inline -func New256() hash.Hash { - return sha3.New256() -} - -// New384 creates a new SHA3-384 hash. -// Its generic security strength is 384 bits against preimage attacks, -// and 192 bits against collision attacks. -// -// It is a wrapper for the [sha3.New384] function in the standard library. -// -//go:fix inline -func New384() hash.Hash { - return sha3.New384() -} - -// New512 creates a new SHA3-512 hash. -// Its generic security strength is 512 bits against preimage attacks, -// and 256 bits against collision attacks. -// -// It is a wrapper for the [sha3.New512] function in the standard library. -// -//go:fix inline -func New512() hash.Hash { - return sha3.New512() -} - -// Sum224 returns the SHA3-224 digest of the data. -// -// It is a wrapper for the [sha3.Sum224] function in the standard library. -// -//go:fix inline -func Sum224(data []byte) [28]byte { - return sha3.Sum224(data) -} - -// Sum256 returns the SHA3-256 digest of the data. -// -// It is a wrapper for the [sha3.Sum256] function in the standard library. -// -//go:fix inline -func Sum256(data []byte) [32]byte { - return sha3.Sum256(data) -} - -// Sum384 returns the SHA3-384 digest of the data. -// -// It is a wrapper for the [sha3.Sum384] function in the standard library. -// -//go:fix inline -func Sum384(data []byte) [48]byte { - return sha3.Sum384(data) -} - -// Sum512 returns the SHA3-512 digest of the data. -// -// It is a wrapper for the [sha3.Sum512] function in the standard library. -// -//go:fix inline -func Sum512(data []byte) [64]byte { - return sha3.Sum512(data) -} diff --git a/vendor/golang.org/x/crypto/sha3/legacy_hash.go b/vendor/golang.org/x/crypto/sha3/legacy_hash.go deleted file mode 100644 index b8784536e01..00000000000 --- a/vendor/golang.org/x/crypto/sha3/legacy_hash.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sha3 - -// This implementation is only used for NewLegacyKeccak256 and -// NewLegacyKeccak512, which are not implemented by crypto/sha3. -// All other functions in this package are wrappers around crypto/sha3. - -import ( - "crypto/subtle" - "encoding/binary" - "errors" - "hash" - "unsafe" - - "golang.org/x/sys/cpu" -) - -const ( - dsbyteKeccak = 0b00000001 - - // rateK[c] is the rate in bytes for Keccak[c] where c is the capacity in - // bits. Given the sponge size is 1600 bits, the rate is 1600 - c bits. - rateK256 = (1600 - 256) / 8 - rateK512 = (1600 - 512) / 8 - rateK1024 = (1600 - 1024) / 8 -) - -// NewLegacyKeccak256 creates a new Keccak-256 hash. -// -// Only use this function if you require compatibility with an existing cryptosystem -// that uses non-standard padding. All other users should use New256 instead. -func NewLegacyKeccak256() hash.Hash { - return &state{rate: rateK512, outputLen: 32, dsbyte: dsbyteKeccak} -} - -// NewLegacyKeccak512 creates a new Keccak-512 hash. -// -// Only use this function if you require compatibility with an existing cryptosystem -// that uses non-standard padding. All other users should use New512 instead. -func NewLegacyKeccak512() hash.Hash { - return &state{rate: rateK1024, outputLen: 64, dsbyte: dsbyteKeccak} -} - -// spongeDirection indicates the direction bytes are flowing through the sponge. -type spongeDirection int - -const ( - // spongeAbsorbing indicates that the sponge is absorbing input. - spongeAbsorbing spongeDirection = iota - // spongeSqueezing indicates that the sponge is being squeezed. - spongeSqueezing -) - -type state struct { - a [1600 / 8]byte // main state of the hash - - // a[n:rate] is the buffer. If absorbing, it's the remaining space to XOR - // into before running the permutation. If squeezing, it's the remaining - // output to produce before running the permutation. - n, rate int - - // dsbyte contains the "domain separation" bits and the first bit of - // the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the - // SHA-3 and SHAKE functions by appending bitstrings to the message. - // Using a little-endian bit-ordering convention, these are "01" for SHA-3 - // and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the - // padding rule from section 5.1 is applied to pad the message to a multiple - // of the rate, which involves adding a "1" bit, zero or more "0" bits, and - // a final "1" bit. We merge the first "1" bit from the padding into dsbyte, - // giving 00000110b (0x06) and 00011111b (0x1f). - // [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf - // "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and - // Extendable-Output Functions (May 2014)" - dsbyte byte - - outputLen int // the default output size in bytes - state spongeDirection // whether the sponge is absorbing or squeezing -} - -// BlockSize returns the rate of sponge underlying this hash function. -func (d *state) BlockSize() int { return d.rate } - -// Size returns the output size of the hash function in bytes. -func (d *state) Size() int { return d.outputLen } - -// Reset clears the internal state by zeroing the sponge state and -// the buffer indexes, and setting Sponge.state to absorbing. -func (d *state) Reset() { - // Zero the permutation's state. - for i := range d.a { - d.a[i] = 0 - } - d.state = spongeAbsorbing - d.n = 0 -} - -func (d *state) clone() *state { - ret := *d - return &ret -} - -// permute applies the KeccakF-1600 permutation. -func (d *state) permute() { - var a *[25]uint64 - if cpu.IsBigEndian { - a = new([25]uint64) - for i := range a { - a[i] = binary.LittleEndian.Uint64(d.a[i*8:]) - } - } else { - a = (*[25]uint64)(unsafe.Pointer(&d.a)) - } - - keccakF1600(a) - d.n = 0 - - if cpu.IsBigEndian { - for i := range a { - binary.LittleEndian.PutUint64(d.a[i*8:], a[i]) - } - } -} - -// pads appends the domain separation bits in dsbyte, applies -// the multi-bitrate 10..1 padding rule, and permutes the state. -func (d *state) padAndPermute() { - // Pad with this instance's domain-separator bits. We know that there's - // at least one byte of space in the sponge because, if it were full, - // permute would have been called to empty it. dsbyte also contains the - // first one bit for the padding. See the comment in the state struct. - d.a[d.n] ^= d.dsbyte - // This adds the final one bit for the padding. Because of the way that - // bits are numbered from the LSB upwards, the final bit is the MSB of - // the last byte. - d.a[d.rate-1] ^= 0x80 - // Apply the permutation - d.permute() - d.state = spongeSqueezing -} - -// Write absorbs more data into the hash's state. It panics if any -// output has already been read. -func (d *state) Write(p []byte) (n int, err error) { - if d.state != spongeAbsorbing { - panic("sha3: Write after Read") - } - - n = len(p) - - for len(p) > 0 { - x := subtle.XORBytes(d.a[d.n:d.rate], d.a[d.n:d.rate], p) - d.n += x - p = p[x:] - - // If the sponge is full, apply the permutation. - if d.n == d.rate { - d.permute() - } - } - - return -} - -// Read squeezes an arbitrary number of bytes from the sponge. -func (d *state) Read(out []byte) (n int, err error) { - // If we're still absorbing, pad and apply the permutation. - if d.state == spongeAbsorbing { - d.padAndPermute() - } - - n = len(out) - - // Now, do the squeezing. - for len(out) > 0 { - // Apply the permutation if we've squeezed the sponge dry. - if d.n == d.rate { - d.permute() - } - - x := copy(out, d.a[d.n:d.rate]) - d.n += x - out = out[x:] - } - - return -} - -// Sum applies padding to the hash state and then squeezes out the desired -// number of output bytes. It panics if any output has already been read. -func (d *state) Sum(in []byte) []byte { - if d.state != spongeAbsorbing { - panic("sha3: Sum after Read") - } - - // Make a copy of the original hash so that caller can keep writing - // and summing. - dup := d.clone() - hash := make([]byte, dup.outputLen, 64) // explicit cap to allow stack allocation - dup.Read(hash) - return append(in, hash...) -} - -const ( - magicKeccak = "sha\x0b" - // magic || rate || main state || n || sponge direction - marshaledSize = len(magicKeccak) + 1 + 200 + 1 + 1 -) - -func (d *state) MarshalBinary() ([]byte, error) { - return d.AppendBinary(make([]byte, 0, marshaledSize)) -} - -func (d *state) AppendBinary(b []byte) ([]byte, error) { - switch d.dsbyte { - case dsbyteKeccak: - b = append(b, magicKeccak...) - default: - panic("unknown dsbyte") - } - // rate is at most 168, and n is at most rate. - b = append(b, byte(d.rate)) - b = append(b, d.a[:]...) - b = append(b, byte(d.n), byte(d.state)) - return b, nil -} - -func (d *state) UnmarshalBinary(b []byte) error { - if len(b) != marshaledSize { - return errors.New("sha3: invalid hash state") - } - - magic := string(b[:len(magicKeccak)]) - b = b[len(magicKeccak):] - switch { - case magic == magicKeccak && d.dsbyte == dsbyteKeccak: - default: - return errors.New("sha3: invalid hash state identifier") - } - - rate := int(b[0]) - b = b[1:] - if rate != d.rate { - return errors.New("sha3: invalid hash state function") - } - - copy(d.a[:], b) - b = b[len(d.a):] - - n, state := int(b[0]), spongeDirection(b[1]) - if n > d.rate { - return errors.New("sha3: invalid hash state") - } - d.n = n - if state != spongeAbsorbing && state != spongeSqueezing { - return errors.New("sha3: invalid hash state") - } - d.state = state - - return nil -} diff --git a/vendor/golang.org/x/crypto/sha3/legacy_keccakf.go b/vendor/golang.org/x/crypto/sha3/legacy_keccakf.go deleted file mode 100644 index 101588c16cc..00000000000 --- a/vendor/golang.org/x/crypto/sha3/legacy_keccakf.go +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sha3 - -// This implementation is only used for NewLegacyKeccak256 and -// NewLegacyKeccak512, which are not implemented by crypto/sha3. -// All other functions in this package are wrappers around crypto/sha3. - -import "math/bits" - -// rc stores the round constants for use in the ι step. -var rc = [24]uint64{ - 0x0000000000000001, - 0x0000000000008082, - 0x800000000000808A, - 0x8000000080008000, - 0x000000000000808B, - 0x0000000080000001, - 0x8000000080008081, - 0x8000000000008009, - 0x000000000000008A, - 0x0000000000000088, - 0x0000000080008009, - 0x000000008000000A, - 0x000000008000808B, - 0x800000000000008B, - 0x8000000000008089, - 0x8000000000008003, - 0x8000000000008002, - 0x8000000000000080, - 0x000000000000800A, - 0x800000008000000A, - 0x8000000080008081, - 0x8000000000008080, - 0x0000000080000001, - 0x8000000080008008, -} - -// keccakF1600 applies the Keccak permutation to a 1600b-wide -// state represented as a slice of 25 uint64s. -func keccakF1600(a *[25]uint64) { - // Implementation translated from Keccak-inplace.c - // in the keccak reference code. - var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64 - - for i := 0; i < 24; i += 4 { - // Combines the 5 steps in each round into 2 steps. - // Unrolls 4 rounds per loop and spreads some steps across rounds. - - // Round 1 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[6] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[12] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[18] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[24] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i] - a[6] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[16] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[22] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[3] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[10] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[1] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[7] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[19] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[20] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[11] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[23] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[4] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[5] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[2] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[8] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[14] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[15] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - // Round 2 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[16] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[7] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[23] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[14] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+1] - a[16] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[11] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[2] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[18] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[20] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[6] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[22] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[4] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[15] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[1] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[8] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[24] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[10] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[12] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[3] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[19] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[5] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - // Round 3 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[11] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[22] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[8] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[19] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+2] - a[11] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[1] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[12] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[23] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[15] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[16] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[2] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[24] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[5] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[6] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[3] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[14] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[20] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[7] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[18] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[4] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[10] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - // Round 4 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[1] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[2] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[3] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[4] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+3] - a[1] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[6] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[7] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[8] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[5] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[11] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[12] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[14] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[10] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[16] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[18] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[19] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[15] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[22] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[23] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[24] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[20] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - } -} diff --git a/vendor/golang.org/x/crypto/sha3/shake.go b/vendor/golang.org/x/crypto/sha3/shake.go deleted file mode 100644 index 6f3f70c2656..00000000000 --- a/vendor/golang.org/x/crypto/sha3/shake.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sha3 - -import ( - "crypto/sha3" - "hash" - "io" -) - -// ShakeHash defines the interface to hash functions that support -// arbitrary-length output. When used as a plain [hash.Hash], it -// produces minimum-length outputs that provide full-strength generic -// security. -type ShakeHash interface { - hash.Hash - - // Read reads more output from the hash; reading affects the hash's - // state. (ShakeHash.Read is thus very different from Hash.Sum.) - // It never returns an error, but subsequent calls to Write or Sum - // will panic. - io.Reader - - // Clone returns a copy of the ShakeHash in its current state. - Clone() ShakeHash -} - -// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash. -// Its generic security strength is 128 bits against all attacks if at -// least 32 bytes of its output are used. -func NewShake128() ShakeHash { - return &shakeWrapper{sha3.NewSHAKE128(), 32, false, sha3.NewSHAKE128} -} - -// NewShake256 creates a new SHAKE256 variable-output-length ShakeHash. -// Its generic security strength is 256 bits against all attacks if -// at least 64 bytes of its output are used. -func NewShake256() ShakeHash { - return &shakeWrapper{sha3.NewSHAKE256(), 64, false, sha3.NewSHAKE256} -} - -// NewCShake128 creates a new instance of cSHAKE128 variable-output-length ShakeHash, -// a customizable variant of SHAKE128. -// N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is -// desired. S is a customization byte string used for domain separation - two cSHAKE -// computations on same input with different S yield unrelated outputs. -// When N and S are both empty, this is equivalent to NewShake128. -func NewCShake128(N, S []byte) ShakeHash { - return &shakeWrapper{sha3.NewCSHAKE128(N, S), 32, false, func() *sha3.SHAKE { - return sha3.NewCSHAKE128(N, S) - }} -} - -// NewCShake256 creates a new instance of cSHAKE256 variable-output-length ShakeHash, -// a customizable variant of SHAKE256. -// N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is -// desired. S is a customization byte string used for domain separation - two cSHAKE -// computations on same input with different S yield unrelated outputs. -// When N and S are both empty, this is equivalent to NewShake256. -func NewCShake256(N, S []byte) ShakeHash { - return &shakeWrapper{sha3.NewCSHAKE256(N, S), 64, false, func() *sha3.SHAKE { - return sha3.NewCSHAKE256(N, S) - }} -} - -// ShakeSum128 writes an arbitrary-length digest of data into hash. -func ShakeSum128(hash, data []byte) { - h := NewShake128() - h.Write(data) - h.Read(hash) -} - -// ShakeSum256 writes an arbitrary-length digest of data into hash. -func ShakeSum256(hash, data []byte) { - h := NewShake256() - h.Write(data) - h.Read(hash) -} - -// shakeWrapper adds the Size, Sum, and Clone methods to a sha3.SHAKE -// to implement the ShakeHash interface. -type shakeWrapper struct { - *sha3.SHAKE - outputLen int - squeezing bool - newSHAKE func() *sha3.SHAKE -} - -func (w *shakeWrapper) Read(p []byte) (n int, err error) { - w.squeezing = true - return w.SHAKE.Read(p) -} - -func (w *shakeWrapper) Clone() ShakeHash { - s := w.newSHAKE() - b, err := w.MarshalBinary() - if err != nil { - panic(err) // unreachable - } - if err := s.UnmarshalBinary(b); err != nil { - panic(err) // unreachable - } - return &shakeWrapper{s, w.outputLen, w.squeezing, w.newSHAKE} -} - -func (w *shakeWrapper) Size() int { return w.outputLen } - -func (w *shakeWrapper) Sum(b []byte) []byte { - if w.squeezing { - panic("sha3: Sum after Read") - } - out := make([]byte, w.outputLen) - // Clone the state so that we don't affect future Write calls. - s := w.Clone() - s.Read(out) - return append(b, out...) -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 1fd840037dc..ddbe2c74276 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,4 @@ -# cyphar.com/go-pathrs v0.2.1 +# cyphar.com/go-pathrs v0.2.4 ## explicit; go 1.18 cyphar.com/go-pathrs cyphar.com/go-pathrs/internal/fdutils @@ -75,23 +75,11 @@ github.com/containerd/stargz-snapshotter/estargz/errorutil # github.com/containerd/typeurl/v2 v2.2.3 ## explicit; go 1.21 github.com/containerd/typeurl/v2 -# github.com/containernetworking/cni v1.3.0 -## explicit; go 1.21 -github.com/containernetworking/cni/libcni -github.com/containernetworking/cni/pkg/invoke -github.com/containernetworking/cni/pkg/types -github.com/containernetworking/cni/pkg/types/020 -github.com/containernetworking/cni/pkg/types/040 -github.com/containernetworking/cni/pkg/types/100 -github.com/containernetworking/cni/pkg/types/create -github.com/containernetworking/cni/pkg/types/internal -github.com/containernetworking/cni/pkg/utils -github.com/containernetworking/cni/pkg/version # github.com/containernetworking/plugins v1.9.0 ## explicit; go 1.24.2 github.com/containernetworking/plugins/pkg/ns -# github.com/containers/buildah v1.42.1-0.20260216192603-e473f9d26ec6 -## explicit; go 1.24.6 +# github.com/containers/buildah v1.42.1-0.20260216192603-e473f9d26ec6 => github.com/lsm5/buildah v0.0.0-20260317084505-caaea7f2d096 +## explicit; go 1.25.5 github.com/containers/buildah github.com/containers/buildah/bind github.com/containers/buildah/chroot @@ -175,7 +163,7 @@ github.com/containers/psgo/internal/process ## explicit; go 1.19 github.com/containers/winquit/pkg/winquit github.com/containers/winquit/pkg/winquit/win32 -# github.com/coreos/go-oidc/v3 v3.16.0 +# github.com/coreos/go-oidc/v3 v3.17.0 ## explicit; go 1.24.0 github.com/coreos/go-oidc/v3/oidc # github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f @@ -235,23 +223,6 @@ github.com/distribution/reference ## explicit github.com/docker/distribution/registry/api/errcode github.com/docker/distribution/registry/api/v2 -# github.com/docker/docker v28.5.2+incompatible -## explicit -github.com/docker/docker/api/types/blkiodev -github.com/docker/docker/api/types/common -github.com/docker/docker/api/types/container -github.com/docker/docker/api/types/filters -github.com/docker/docker/api/types/mount -github.com/docker/docker/api/types/network -github.com/docker/docker/api/types/registry -github.com/docker/docker/api/types/storage -github.com/docker/docker/api/types/strslice -github.com/docker/docker/api/types/swarm -github.com/docker/docker/api/types/swarm/runtime -github.com/docker/docker/api/types/versions -github.com/docker/docker/pkg/homedir -github.com/docker/docker/pkg/jsonmessage -github.com/docker/docker/pkg/stdcopy # github.com/docker/docker-credential-helpers v0.9.5 ## explicit; go 1.21 github.com/docker/docker-credential-helpers/client @@ -282,8 +253,8 @@ github.com/felixge/httpsnoop ## explicit; go 1.17 github.com/fsnotify/fsnotify github.com/fsnotify/fsnotify/internal -# github.com/fsouza/go-dockerclient v1.12.3 -## explicit; go 1.24.0 +# github.com/fsouza/go-dockerclient v1.13.0 +## explicit; go 1.25.0 github.com/fsouza/go-dockerclient # github.com/go-jose/go-jose/v4 v4.1.3 ## explicit; go 1.24.0 @@ -320,8 +291,8 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/go-containerregistry v0.20.6 -## explicit; go 1.24 +# github.com/google/go-containerregistry v0.20.7 +## explicit; go 1.24.0 github.com/google/go-containerregistry/pkg/name github.com/google/go-containerregistry/pkg/v1 github.com/google/go-containerregistry/pkg/v1/types @@ -428,8 +399,8 @@ github.com/miekg/pkcs11 # github.com/mistifyio/go-zfs/v4 v4.0.0 ## explicit; go 1.14 github.com/mistifyio/go-zfs/v4 -# github.com/moby/buildkit v0.26.3 -## explicit; go 1.24.3 +# github.com/moby/buildkit v0.28.0 +## explicit; go 1.25.5 github.com/moby/buildkit/frontend/dockerfile/command github.com/moby/buildkit/frontend/dockerfile/parser github.com/moby/buildkit/frontend/dockerfile/shell @@ -437,7 +408,7 @@ github.com/moby/buildkit/util/stack # github.com/moby/docker-image-spec v1.3.1 ## explicit; go 1.18 github.com/moby/docker-image-spec/specs-go/v1 -# github.com/moby/go-archive v0.1.0 +# github.com/moby/go-archive v0.2.0 ## explicit; go 1.23.0 github.com/moby/go-archive github.com/moby/go-archive/compression @@ -445,6 +416,7 @@ github.com/moby/go-archive/tarheader # github.com/moby/moby/api v1.54.0 ## explicit; go 1.24.0 github.com/moby/moby/api +github.com/moby/moby/api/pkg/stdcopy github.com/moby/moby/api/types github.com/moby/moby/api/types/blkiodev github.com/moby/moby/api/types/build @@ -467,7 +439,11 @@ github.com/moby/moby/api/types/volume github.com/moby/moby/client github.com/moby/moby/client/internal github.com/moby/moby/client/internal/timestamp +github.com/moby/moby/client/pkg/jsonmessage github.com/moby/moby/client/pkg/versions +# github.com/moby/moby/v2 v2.0.0-beta.6 +## explicit; go 1.25.0 +github.com/moby/moby/v2/pkg/homedir # github.com/moby/patternmatcher v0.6.0 ## explicit; go 1.19 github.com/moby/patternmatcher @@ -496,9 +472,6 @@ github.com/modern-go/concurrent # github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee ## explicit; go 1.12 github.com/modern-go/reflect2 -# github.com/morikuni/aec v1.0.0 -## explicit -github.com/morikuni/aec # github.com/nxadm/tail v1.4.11 ## explicit; go 1.13 github.com/nxadm/tail @@ -561,7 +534,7 @@ github.com/opencontainers/go-digest ## explicit; go 1.18 github.com/opencontainers/image-spec/specs-go github.com/opencontainers/image-spec/specs-go/v1 -# github.com/opencontainers/runc v1.4.0 +# github.com/opencontainers/runc v1.4.1 ## explicit; go 1.24.0 github.com/opencontainers/runc/internal/linux github.com/opencontainers/runc/internal/pathrs @@ -639,15 +612,15 @@ github.com/shirou/gopsutil/v4/internal/common github.com/shirou/gopsutil/v4/mem github.com/shirou/gopsutil/v4/net github.com/shirou/gopsutil/v4/process -# github.com/sigstore/fulcio v1.8.1 -## explicit; go 1.24.6 +# github.com/sigstore/fulcio v1.8.5 +## explicit; go 1.25.0 github.com/sigstore/fulcio/pkg/api github.com/sigstore/fulcio/pkg/certificate # github.com/sigstore/protobuf-specs v0.5.0 ## explicit; go 1.22.0 github.com/sigstore/protobuf-specs/gen/pb-go/common/v1 -# github.com/sigstore/sigstore v1.9.6-0.20251111174640-d8ab8afb1326 -## explicit; go 1.24.0 +# github.com/sigstore/sigstore v1.10.4 +## explicit; go 1.25.0 github.com/sigstore/sigstore/pkg/cryptoutils github.com/sigstore/sigstore/pkg/oauth github.com/sigstore/sigstore/pkg/oauthflow @@ -761,7 +734,7 @@ go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry go.opentelemetry.io/otel/trace/noop -# go.podman.io/common v0.67.1-0.20260313003550-7415b6a27ee6 +# go.podman.io/common v0.67.1-0.20260316162257-e70c309aabae ## explicit; go 1.25.0 go.podman.io/common/internal go.podman.io/common/internal/attributedstring @@ -770,7 +743,6 @@ go.podman.io/common/libimage/define go.podman.io/common/libimage/filter go.podman.io/common/libimage/manifests go.podman.io/common/libimage/platform -go.podman.io/common/libnetwork/cni go.podman.io/common/libnetwork/etchosts go.podman.io/common/libnetwork/internal/rootlessnetns go.podman.io/common/libnetwork/internal/util @@ -829,7 +801,7 @@ go.podman.io/common/pkg/umask go.podman.io/common/pkg/util go.podman.io/common/pkg/version go.podman.io/common/version -# go.podman.io/image/v5 v5.39.2-0.20260313003550-7415b6a27ee6 +# go.podman.io/image/v5 v5.39.2-0.20260316162257-e70c309aabae ## explicit; go 1.25.0 go.podman.io/image/v5/copy go.podman.io/image/v5/directory @@ -906,7 +878,7 @@ go.podman.io/image/v5/transports go.podman.io/image/v5/transports/alltransports go.podman.io/image/v5/types go.podman.io/image/v5/version -# go.podman.io/storage v1.62.1-0.20260313003550-7415b6a27ee6 +# go.podman.io/storage v1.62.1-0.20260316162257-e70c309aabae ## explicit; go 1.25.0 go.podman.io/storage go.podman.io/storage/drivers @@ -985,7 +957,6 @@ golang.org/x/crypto/pbkdf2 golang.org/x/crypto/ripemd160 golang.org/x/crypto/salsa20/salsa golang.org/x/crypto/scrypt -golang.org/x/crypto/sha3 golang.org/x/crypto/ssh golang.org/x/crypto/ssh/agent golang.org/x/crypto/ssh/internal/bcrypt_pbkdf @@ -1208,3 +1179,4 @@ tags.cncf.io/container-device-interface/pkg/parser # tags.cncf.io/container-device-interface/specs-go v1.1.0 ## explicit; go 1.19 tags.cncf.io/container-device-interface/specs-go +# github.com/containers/buildah => github.com/lsm5/buildah v0.0.0-20260317084505-caaea7f2d096