diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 50e557f92d4e..09e7da7089d8 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,6 +1,6 @@ { "ImportPath": "k8s.io/minikube", - "GoVersion": "go1.6", + "GoVersion": "go1.7", "GodepVersion": "v74", "Packages": [ "./..." @@ -11,6 +11,44 @@ "Comment": "null-5", "Rev": "'75cd24fc2f2c2a2088577d12123ddee5f54e0675'" }, + { + "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/compute", + "Comment": "v3.0.0-beta", + "Rev": "2cdbb8553a20830507e4178b4d0803794136dde7" + }, + { + "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/network", + "Comment": "v3.0.0-beta", + "Rev": "2cdbb8553a20830507e4178b4d0803794136dde7" + }, + { + "ImportPath": "github.com/Azure/go-ansiterm", + "Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" + }, + { + "ImportPath": "github.com/Azure/go-ansiterm/winterm", + "Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest", + "Comment": "v7.0.6-4-g2492d97", + "Rev": "2492d97b402e00797833c03ac5fa1c572c7bb29a" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/azure", + "Comment": "v7.0.6-4-g2492d97", + "Rev": "2492d97b402e00797833c03ac5fa1c572c7bb29a" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/date", + "Comment": "v7.0.6-4-g2492d97", + "Rev": "2492d97b402e00797833c03ac5fa1c572c7bb29a" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/to", + "Comment": "v7.0.6-4-g2492d97", + "Rev": "2492d97b402e00797833c03ac5fa1c572c7bb29a" + }, { "ImportPath": "github.com/BurntSushi/toml", "Comment": "v0.2.0-9-gf0aeabc", @@ -212,6 +250,71 @@ "Comment": "v1.1.0-65-gee4a088", "Rev": "ee4a0888a9abe7eefe5a0992ca4cb06864839873" }, + { + "ImportPath": "github.com/cloudflare/cfssl/auth", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/certdb", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/config", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/crypto/pkcs7", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/csr", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/errors", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/helpers", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/helpers/derhelpers", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/info", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/log", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/ocsp/config", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/signer", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, + { + "ImportPath": "github.com/cloudflare/cfssl/signer/local", + "Comment": "1.2.0", + "Rev": "db0d0650b6496bfe8061ec56a92edd32d8e75c30" + }, { "ImportPath": "github.com/coreos/etcd/alarm", "Comment": "v2.3.0-282-g8b320e7", @@ -557,8 +660,8 @@ }, { "ImportPath": "github.com/dgrijalva/jwt-go", - "Comment": "v2.2.0-23-g5ca8014", - "Rev": "5ca80149b9d3f8b863af0e2bb6742e608603bd99" + "Comment": "v3.0.0-4-g01aeca5", + "Rev": "01aeca54ebda6e0fbfafd0a524d234159c05ec20" }, { "ImportPath": "github.com/docker/distribution/digest", @@ -570,45 +673,50 @@ "Comment": "v2.4.0-rc.1-38-gcd27f17", "Rev": "cd27f179f2c10c5d300e6d09025b538c475b0d51" }, + { + "ImportPath": "github.com/docker/docker/pkg/jsonlog", + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" + }, { "ImportPath": "github.com/docker/docker/pkg/jsonmessage", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" + }, + { + "ImportPath": "github.com/docker/docker/pkg/longpath", + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { "ImportPath": "github.com/docker/docker/pkg/mount", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { "ImportPath": "github.com/docker/docker/pkg/stdcopy", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { "ImportPath": "github.com/docker/docker/pkg/symlink", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" - }, - { - "ImportPath": "github.com/docker/docker/pkg/term", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { - "ImportPath": "github.com/docker/docker/pkg/term/winconsole", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "ImportPath": "github.com/docker/docker/pkg/system", + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { - "ImportPath": "github.com/docker/docker/pkg/timeutils", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "ImportPath": "github.com/docker/docker/pkg/term", + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { - "ImportPath": "github.com/docker/docker/pkg/units", - "Comment": "v1.4.1-4831-g0f5c9d3", - "Rev": "0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d" + "ImportPath": "github.com/docker/docker/pkg/term/windows", + "Comment": "v1.11.2", + "Rev": "b9f10c951893f9a00865890a5232e85d770c1087" }, { "ImportPath": "github.com/docker/engine-api/client", @@ -859,18 +967,18 @@ }, { "ImportPath": "github.com/emicklei/go-restful", - "Comment": "v1.2-54-g7c47e25", - "Rev": "7c47e2558a0bbbaba9ecab06bc6681e73028a28a" + "Comment": "v1.2-66-gc4afa8e", + "Rev": "c4afa8e5421428d584b32d36d7b35f2c9ae5f823" }, { "ImportPath": "github.com/emicklei/go-restful/log", - "Comment": "v1.2-54-g7c47e25", - "Rev": "7c47e2558a0bbbaba9ecab06bc6681e73028a28a" + "Comment": "v1.2-66-gc4afa8e", + "Rev": "c4afa8e5421428d584b32d36d7b35f2c9ae5f823" }, { "ImportPath": "github.com/emicklei/go-restful/swagger", - "Comment": "v1.2-54-g7c47e25", - "Rev": "7c47e2558a0bbbaba9ecab06bc6681e73028a28a" + "Comment": "v1.2-66-gc4afa8e", + "Rev": "c4afa8e5421428d584b32d36d7b35f2c9ae5f823" }, { "ImportPath": "github.com/evanphx/json-patch", @@ -900,6 +1008,11 @@ "Comment": "v0.1-125-g82d16f7", "Rev": "82d16f734d6d871204a3feb1a73cb220cc92574c" }, + { + "ImportPath": "github.com/gogo/protobuf/sortkeys", + "Comment": "v0.1-125-g82d16f7", + "Rev": "82d16f734d6d871204a3feb1a73cb220cc92574c" + }, { "ImportPath": "github.com/golang/glog", "Rev": "44145f04b68cf362d9c4df2182967c2275eaefed" @@ -918,198 +1031,218 @@ }, { "ImportPath": "github.com/google/cadvisor/api", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/cache/memory", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/collector", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/common", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/docker", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/libcontainer", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/raw", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/rkt", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/container/systemd", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/devicemapper", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/events", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/fs", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/healthz", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/http", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/http/mux", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/info/v1", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/info/v2", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/machine", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/manager", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/manager/watcher", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/manager/watcher/raw", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/manager/watcher/rkt", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/metrics", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/pages", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/pages/static", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/storage", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/summary", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/cloudinfo", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/cpuload", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/cpuload/netlink", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/docker", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/oomparser", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/sysfs", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/sysinfo", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/utils/tail", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/validate", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" }, { "ImportPath": "github.com/google/cadvisor/version", - "Comment": "v0.23.7", - "Rev": "c2ea32971ae033041f0fb0f309b1dee94fd1d55f" + "Comment": "v0.23.2-63-ge47efa0", + "Rev": "e47efa0e8af65e9a2a2eb2ce955e156eac067852" + }, + { + "ImportPath": "github.com/google/certificate-transparency/go", + "Rev": "af98904302724c29aa6659ca372d41c9687de2b7" + }, + { + "ImportPath": "github.com/google/certificate-transparency/go/asn1", + "Rev": "af98904302724c29aa6659ca372d41c9687de2b7" + }, + { + "ImportPath": "github.com/google/certificate-transparency/go/client", + "Rev": "af98904302724c29aa6659ca372d41c9687de2b7" + }, + { + "ImportPath": "github.com/google/certificate-transparency/go/x509", + "Rev": "af98904302724c29aa6659ca372d41c9687de2b7" + }, + { + "ImportPath": "github.com/google/certificate-transparency/go/x509/pkix", + "Rev": "af98904302724c29aa6659ca372d41c9687de2b7" }, { "ImportPath": "github.com/google/gofuzz", @@ -1279,7 +1412,7 @@ }, { "ImportPath": "github.com/miekg/dns", - "Rev": "c2b278e70f35902fd68b54b69238cd10bb1b7451" + "Rev": "5d001d020961ae1c184f9f8152fdc73810481677" }, { "ImportPath": "github.com/mistifyio/go-zfs", @@ -1290,84 +1423,93 @@ "ImportPath": "github.com/mitchellh/mapstructure", "Rev": "740c764bc6149d3f1806231418adb9f52c11bcbf" }, + { + "ImportPath": "github.com/mreiferson/go-httpclient", + "Rev": "31f0106b4474f14bc441575c19d3a5fa21aa1f6c" + }, { "ImportPath": "github.com/mxk/go-flowrate/flowrate", "Rev": "cca7078d478f8520f85629ad7c68962d31ed7682" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/apparmor", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/cgroups", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/cgroups/fs", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/cgroups/systemd", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/configs", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/configs/validate", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/criurpc", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" + }, + { + "ImportPath": "github.com/opencontainers/runc/libcontainer/keys", + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/label", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/seccomp", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/selinux", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/stacktrace", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/system", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/user", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/utils", - "Comment": "v0.0.7", - "Rev": "7ca2aa4873aea7cb4265b1726acb24b90d8726c6" + "Comment": "v0.1.1", + "Rev": "baf6536d6259209c3edfa2b22237af82942d3dfa" }, { "ImportPath": "github.com/pborman/uuid", @@ -1377,10 +1519,6 @@ "ImportPath": "github.com/pkg/browser", "Rev": "9302be274faad99162b9d48ec97b24306872ebb0" }, - { - "ImportPath": "github.com/pmezard/go-difflib/difflib", - "Rev": "d8ed2627bdf02c080bf22230dbb337003b7aba2d" - }, { "ImportPath": "github.com/prometheus/client_golang/prometheus", "Comment": "0.7.0-39-g3b78d7a", @@ -1590,33 +1728,33 @@ }, { "ImportPath": "github.com/skynetservices/skydns/backends/etcd", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/skynetservices/skydns/cache", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/skynetservices/skydns/metrics", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/skynetservices/skydns/msg", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/skynetservices/skydns/server", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/skynetservices/skydns/singleflight", - "Comment": "2.5.3a-32-gf7b6fb7", - "Rev": "f7b6fb74bcfab300b4e7e0e27b1fe6c0ed555f78" + "Comment": "2.5.3a-41-g00ade30", + "Rev": "00ade3024f047d26130abf161900e0adb72a06f1" }, { "ImportPath": "github.com/spf13/cast", @@ -1642,20 +1780,6 @@ "ImportPath": "github.com/spf13/viper", "Rev": "c1ccc378a054ea8d4e38d8c67f6938d4760b53dd" }, - { - "ImportPath": "github.com/stretchr/objx", - "Rev": "1a9d0bb9f541897e62256577b352fdbc1fb4fd94" - }, - { - "ImportPath": "github.com/stretchr/testify/assert", - "Comment": "v1.0-88-ge3a8ff8", - "Rev": "e3a8ff8ce36581f87a15341206f205b1da467059" - }, - { - "ImportPath": "github.com/stretchr/testify/mock", - "Comment": "v1.0-88-ge3a8ff8", - "Rev": "e3a8ff8ce36581f87a15341206f205b1da467059" - }, { "ImportPath": "github.com/syndtr/gocapability/capability", "Rev": "2c00daeb6c3b45114c80ac44119e7b8801fdd852" @@ -1769,23 +1893,31 @@ }, { "ImportPath": "golang.org/x/crypto/bcrypt", - "Rev": "c84e1f8e3a7e322d497cd16c0e8a13c7e127baf3" + "Rev": "1f22c0103821b9390939b6776727195525381532" }, { "ImportPath": "golang.org/x/crypto/blowfish", - "Rev": "c84e1f8e3a7e322d497cd16c0e8a13c7e127baf3" + "Rev": "1f22c0103821b9390939b6776727195525381532" }, { "ImportPath": "golang.org/x/crypto/curve25519", - "Rev": "c84e1f8e3a7e322d497cd16c0e8a13c7e127baf3" + "Rev": "1f22c0103821b9390939b6776727195525381532" + }, + { + "ImportPath": "golang.org/x/crypto/pkcs12", + "Rev": "1f22c0103821b9390939b6776727195525381532" + }, + { + "ImportPath": "golang.org/x/crypto/pkcs12/internal/rc2", + "Rev": "1f22c0103821b9390939b6776727195525381532" }, { "ImportPath": "golang.org/x/crypto/ssh", - "Rev": "c84e1f8e3a7e322d497cd16c0e8a13c7e127baf3" + "Rev": "1f22c0103821b9390939b6776727195525381532" }, { "ImportPath": "golang.org/x/crypto/ssh/terminal", - "Rev": "c84e1f8e3a7e322d497cd16c0e8a13c7e127baf3" + "Rev": "1f22c0103821b9390939b6776727195525381532" }, { "ImportPath": "golang.org/x/exp/inotify", @@ -1793,43 +1925,47 @@ }, { "ImportPath": "golang.org/x/net/context", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/context/ctxhttp", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/html", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/html/atom", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/http2", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/http2/hpack", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/internal/timeseries", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" + }, + { + "ImportPath": "golang.org/x/net/lex/httplex", + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/proxy", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/trace", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/net/websocket", - "Rev": "62685c2d7ca23c807425dca88b11a3e2323dab41" + "Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0" }, { "ImportPath": "golang.org/x/oauth2", @@ -1964,2248 +2100,2338 @@ }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-apiserver/app", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-apiserver/app/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-controller-manager/app", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-controller-manager/app/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-proxy/app", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kube-proxy/app/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kubelet/app", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/cmd/kubelet/app/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/admission", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/annotations", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/endpoints", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/errors", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/errors/storage", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/meta", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/meta/metatypes", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/pod", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/resource", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/rest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/service", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/unversioned/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/v1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/api/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apimachinery", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apimachinery/registered", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/abac", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/abac/latest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/abac/v0", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/abac/v1beta1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/apps", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/apps/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/apps/v1alpha1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/apps/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authentication.k8s.io", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/authorization/v1beta1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling/v1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/autoscaling/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/batch", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/v1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/v2alpha1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/batch/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/certificates", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/certificates/install", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/apis/certificates/validation", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions/v1beta1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/extensions/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/policy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/policy/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/policy/v1alpha1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/policy/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/rbac", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/rbac/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/rbac/v1alpha1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apis/rbac/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apiserver", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apiserver/authenticator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/apiserver/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/authenticator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/authenticator/bearertoken", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/authorizer", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/authorizer/abac", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/authorizer/union", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/handlers", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/auth/user", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/capabilities", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/cache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/chaosclient", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/leaderelection", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/record", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/restclient", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/testing/core", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/transport", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/typed/discovery", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/typed/discovery/fake", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/typed/dynamic", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/auth", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/aws", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/azure", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/gce", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/mesos", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/controller/certificates", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/daemon", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/deployment", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/controller/deployment/util", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/endpoint", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/framework", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/framework/informers", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/garbagecollector", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" - }, - { - "ImportPath": "k8s.io/kubernetes/pkg/controller/gc", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/job", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/namespace", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/node", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/petset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/podautoscaler", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/controller/podgc", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/replicaset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/replication", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/resourcequota", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/route", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/service", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/serviceaccount", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/attachdetach", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/attachdetach/populator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/attachdetach/reconciler", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/controller/volume/persistentvolume", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/conversion", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/conversion/queryparams", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/credentialprovider", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/credentialprovider/aws", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/credentialprovider/gcp", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/fieldpath", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/fields", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/genericapiserver", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/genericapiserver/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/healthz", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/httplog", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/cadvisor", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/client", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/cm", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/config", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/container", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/custommetrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/dockertools", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/envvars", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubelet/events", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/eviction", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/kubelet/images", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/leaky", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/lifecycle", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network/cni", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network/exec", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network/hairpin", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network/hostport", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/network/kubenet", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/pleg", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/pod", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/prober", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/prober/results", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/qos", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" - }, - { - "ImportPath": "k8s.io/kubernetes/pkg/kubelet/qos/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/rkt", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/server", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/server/portforward", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/server/remotecommand", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/server/stats", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/status", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/types", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/util/cache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/util/format", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/util/ioutils", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/util/queue", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/volumemanager", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/volumemanager/cache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/volumemanager/populator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/labels", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/master", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/master/ports", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/probe", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/probe/exec", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/probe/http", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/probe/tcp", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/proxy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/proxy/config", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/proxy/iptables", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/proxy/userspace", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/quota", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/quota/evaluator/core", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/quota/generic", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/quota/install", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/cachesize", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/registry/certificates", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/registry/certificates/etcd", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrole", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrole/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrole/policybased", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrolebinding", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrolebinding/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/clusterrolebinding/policybased", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/componentstatus", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/configmap", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/configmap/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/controller", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/controller/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/daemonset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/daemonset/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/deployment", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/deployment/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/endpoint", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/endpoint/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/event", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/event/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/experimental/controller/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/generic", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/generic/registry", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/generic/rest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/ingress", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/ingress/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/job", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/job/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/limitrange", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/limitrange/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/namespace", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/namespace/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/networkpolicy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/networkpolicy/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/node", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/node/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/node/rest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/persistentvolume", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/persistentvolume/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/persistentvolumeclaim", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/petset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/petset/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/pod", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/pod/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/pod/rest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/poddisruptionbudget", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/poddisruptionbudget/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/podsecuritypolicy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/podtemplate", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/podtemplate/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/replicaset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/replicaset/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/resourcequota", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/resourcequota/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/role", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/role/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/role/policybased", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/rolebinding", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/rolebinding/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/rolebinding/policybased", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/secret", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/secret/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/allocator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/allocator/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/ipallocator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/ipallocator/controller", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/portallocator", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/service/portallocator/controller", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/serviceaccount", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/serviceaccount/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/registry/storageclass", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/registry/storageclass/etcd", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/thirdpartyresource", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/json", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/protobuf", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/recognizer", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/streaming", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/runtime/serializer/versioning", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy/group", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy/user", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/securitycontext", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/serviceaccount", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/ssh", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/etcd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/etcd/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/etcd/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/etcd3", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/storagebackend", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/storage/storagebackend/factory", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/types", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/ui", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/ui/data/swagger", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/bandwidth", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/cache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/certificates", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/chmod", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/chown", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/clock", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/config", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/configz", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/crypto", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/dbus", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" - }, - { - "ImportPath": "k8s.io/kubernetes/pkg/util/deployment", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/diff", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/env", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/errors", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/exec", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/flock", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/flowcontrol", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/flushwriter", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/framer", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/goroutinemap", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/hash", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/homedir", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/httpstream", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/httpstream/spdy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/integer", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/interrupt", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/intstr", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/io", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/iptables", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/json", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/keymutex", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/labels", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/limitwriter", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/mount", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/net", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/net/sets", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/node", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/oom", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/parsers", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/pod", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/procfs", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/proxy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/rand", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/replicaset", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/runtime", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/selinux", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/sets", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/slice", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/strategicpatch", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/strings", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/sysctl", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/system", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" + }, + { + "ImportPath": "k8s.io/kubernetes/pkg/util/term", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/validation/field", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/wait", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/workqueue", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/wsstream", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/util/yaml", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/version", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/aws_ebs", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/azure_file", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/cephfs", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/cinder", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/configmap", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/downwardapi", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/empty_dir", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/fc", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/flexvolume", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/flocker", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/gce_pd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/git_repo", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/glusterfs", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/host_path", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/iscsi", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/nfs", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/rbd", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/secret", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/util/operationexecutor", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/util/types", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/util/volumehelper", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/volume/vsphere_volume", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/watch", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/pkg/watch/versioned", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/cmd/kube-scheduler/app", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/admit", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/alwayspullimages", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/antiaffinity", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/deny", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/exec", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/initialresources", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/limitranger", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/namespace/exists", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/namespace/lifecycle", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/resourcequota", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/admission/serviceaccount", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/passwordfile", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/basicauth", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/oidc", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/webhook", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/client/auth", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/client/auth/gcp", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/client/auth/oidc", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/api", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/api/latest", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/api/v1", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/api/validation", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/factory", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/metrics", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { "ImportPath": "k8s.io/kubernetes/plugin/pkg/webhook", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { - "ImportPath": "k8s.io/kubernetes/third_party/forked/json", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "ImportPath": "k8s.io/kubernetes/third_party/forked/golang/expansion", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { - "ImportPath": "k8s.io/kubernetes/third_party/forked/reflect", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "ImportPath": "k8s.io/kubernetes/third_party/forked/golang/json", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { - "ImportPath": "k8s.io/kubernetes/third_party/golang/expansion", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "ImportPath": "k8s.io/kubernetes/third_party/forked/golang/netutil", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" }, { - "ImportPath": "k8s.io/kubernetes/third_party/golang/netutil", - "Comment": "v1.3.5", - "Rev": "b0deb2eb8f4037421077f77cb163dbb4c0a2a9f5" + "ImportPath": "k8s.io/kubernetes/third_party/forked/golang/reflect", + "Comment": "v1.4.0-alpha.2", + "Rev": "9fab05fe59fb4e02deb0f839ae2ae79954bbda4c" } ] } diff --git a/docs/minikube_start.md b/docs/minikube_start.md index c8f33fa69b8f..ea441e3c3e1d 100644 --- a/docs/minikube_start.md +++ b/docs/minikube_start.md @@ -21,7 +21,7 @@ minikube start --host-only-cidr="192.168.99.1/24": The CIDR to be used for the minikube VM (only supported with Virtualbox driver) --insecure-registry=[]: Insecure Docker registries to pass to the Docker daemon --iso-url="https://storage.googleapis.com/minikube/minikube-0.6.iso": Location of the minikube iso - --kubernetes-version="v1.3.5": The kubernetes version that the minikube VM will (ex: v1.2.3) + --kubernetes-version="v1.4.0-alpha.2": The kubernetes version that the minikube VM will (ex: v1.2.3) OR a URI which contains a localkube binary (ex: https://storage.googleapis.com/minikube/k8sReleases/v1.3.0/localkube-linux-amd64) --memory=1024: Amount of RAM allocated to the minikube VM --registry-mirror=[]: Registry mirrors to pass to the Docker daemon diff --git a/vendor/github.com/Azure/azure-sdk-for-go/LICENSE b/vendor/github.com/Azure/azure-sdk-for-go/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/LICENSE @@ -0,0 +1,202 @@ + + 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/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go new file mode 100644 index 000000000000..d60f15738c75 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go @@ -0,0 +1,352 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// AvailabilitySetsClient is the the Compute Management Client. +type AvailabilitySetsClient struct { + ManagementClient +} + +// NewAvailabilitySetsClient creates an instance of the AvailabilitySetsClient +// client. +func NewAvailabilitySetsClient(subscriptionID string) AvailabilitySetsClient { + return AvailabilitySetsClient{New(subscriptionID)} +} + +// CreateOrUpdate the operation to create or update the availability set. +// +// resourceGroupName is the name of the resource group. name is parameters +// supplied to the Create Availability Set operation. parameters is +// parameters supplied to the Create Availability Set operation. +func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client AvailabilitySetsClient) CreateOrUpdatePreparer(resourceGroupName string, name string, parameters AvailabilitySet) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{name}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilitySetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response) (result AvailabilitySet, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete the operation to delete the availability set. +// +// resourceGroupName is the name of the resource group. availabilitySetName is +// the name of the availability set. +func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, availabilitySetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client AvailabilitySetsClient) DeletePreparer(resourceGroupName string, availabilitySetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilitySetName": autorest.Encode("path", availabilitySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the operation to get the availability set. +// +// resourceGroupName is the name of the resource group. availabilitySetName is +// the name of the availability set. +func (client AvailabilitySetsClient) Get(resourceGroupName string, availabilitySetName string) (result AvailabilitySet, err error) { + req, err := client.GetPreparer(resourceGroupName, availabilitySetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client AvailabilitySetsClient) GetPreparer(resourceGroupName string, availabilitySetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilitySetName": autorest.Encode("path", availabilitySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilitySetsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result AvailabilitySet, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the operation to list the availability sets. +// +// resourceGroupName is the name of the resource group. +func (client AvailabilitySetsClient) List(resourceGroupName string) (result AvailabilitySetListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client AvailabilitySetsClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilitySetsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result AvailabilitySetListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAvailableSizes lists all available virtual machine sizes that can be +// used to create a new virtual machine in an existing availability set. +// +// resourceGroupName is the name of the resource group. availabilitySetName is +// the name of the availability set. +func (client AvailabilitySetsClient) ListAvailableSizes(resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, err error) { + req, err := client.ListAvailableSizesPreparer(resourceGroupName, availabilitySetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") + } + + resp, err := client.ListAvailableSizesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") + } + + result, err = client.ListAvailableSizesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure responding to request") + } + + return +} + +// ListAvailableSizesPreparer prepares the ListAvailableSizes request. +func (client AvailabilitySetsClient) ListAvailableSizesPreparer(resourceGroupName string, availabilitySetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilitySetName": autorest.Encode("path", availabilitySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilitySetsClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always +// closes the http.Response Body. +func (client AvailabilitySetsClient) ListAvailableSizesResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go new file mode 100644 index 000000000000..64ebfa410922 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go @@ -0,0 +1,53 @@ +// Package compute implements the Azure ARM Compute service API version +// 2016-03-30. +// +// The Compute Management Client. +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // APIVersion is the version of the Compute + APIVersion = "2016-03-30" + + // DefaultBaseURI is the default URI used for the service Compute + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Compute. +type ManagementClient struct { + autorest.Client + BaseURI string + APIVersion string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: DefaultBaseURI, + APIVersion: APIVersion, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go new file mode 100644 index 000000000000..3858f6e57815 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go @@ -0,0 +1,1180 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// CachingTypes enumerates the values for caching types. +type CachingTypes string + +const ( + // None specifies the none state for caching types. + None CachingTypes = "None" + // ReadOnly specifies the read only state for caching types. + ReadOnly CachingTypes = "ReadOnly" + // ReadWrite specifies the read write state for caching types. + ReadWrite CachingTypes = "ReadWrite" +) + +// ComponentNames enumerates the values for component names. +type ComponentNames string + +const ( + // MicrosoftWindowsShellSetup specifies the microsoft windows shell setup + // state for component names. + MicrosoftWindowsShellSetup ComponentNames = "Microsoft-Windows-Shell-Setup" +) + +// DiskCreateOptionTypes enumerates the values for disk create option types. +type DiskCreateOptionTypes string + +const ( + // Attach specifies the attach state for disk create option types. + Attach DiskCreateOptionTypes = "attach" + // Empty specifies the empty state for disk create option types. + Empty DiskCreateOptionTypes = "empty" + // FromImage specifies the from image state for disk create option types. + FromImage DiskCreateOptionTypes = "fromImage" +) + +// InstanceViewTypes enumerates the values for instance view types. +type InstanceViewTypes string + +const ( + // InstanceView specifies the instance view state for instance view types. + InstanceView InstanceViewTypes = "instanceView" +) + +// OperatingSystemTypes enumerates the values for operating system types. +type OperatingSystemTypes string + +const ( + // Linux specifies the linux state for operating system types. + Linux OperatingSystemTypes = "Linux" + // Windows specifies the windows state for operating system types. + Windows OperatingSystemTypes = "Windows" +) + +// PassNames enumerates the values for pass names. +type PassNames string + +const ( + // OobeSystem specifies the oobe system state for pass names. + OobeSystem PassNames = "oobeSystem" +) + +// ProtocolTypes enumerates the values for protocol types. +type ProtocolTypes string + +const ( + // HTTP specifies the http state for protocol types. + HTTP ProtocolTypes = "Http" + // HTTPS specifies the https state for protocol types. + HTTPS ProtocolTypes = "Https" +) + +// SettingNames enumerates the values for setting names. +type SettingNames string + +const ( + // AutoLogon specifies the auto logon state for setting names. + AutoLogon SettingNames = "AutoLogon" + // FirstLogonCommands specifies the first logon commands state for setting + // names. + FirstLogonCommands SettingNames = "FirstLogonCommands" +) + +// StatusLevelTypes enumerates the values for status level types. +type StatusLevelTypes string + +const ( + // Error specifies the error state for status level types. + Error StatusLevelTypes = "Error" + // Info specifies the info state for status level types. + Info StatusLevelTypes = "Info" + // Warning specifies the warning state for status level types. + Warning StatusLevelTypes = "Warning" +) + +// UpgradeMode enumerates the values for upgrade mode. +type UpgradeMode string + +const ( + // Automatic specifies the automatic state for upgrade mode. + Automatic UpgradeMode = "Automatic" + // Manual specifies the manual state for upgrade mode. + Manual UpgradeMode = "Manual" +) + +// VirtualMachineScaleSetSkuScaleType enumerates the values for virtual +// machine scale set sku scale type. +type VirtualMachineScaleSetSkuScaleType string + +const ( + // VirtualMachineScaleSetSkuScaleTypeAutomatic specifies the virtual + // machine scale set sku scale type automatic state for virtual machine + // scale set sku scale type. + VirtualMachineScaleSetSkuScaleTypeAutomatic VirtualMachineScaleSetSkuScaleType = "Automatic" + // VirtualMachineScaleSetSkuScaleTypeNone specifies the virtual machine + // scale set sku scale type none state for virtual machine scale set sku + // scale type. + VirtualMachineScaleSetSkuScaleTypeNone VirtualMachineScaleSetSkuScaleType = "None" +) + +// VirtualMachineSizeTypes enumerates the values for virtual machine size +// types. +type VirtualMachineSizeTypes string + +const ( + // BasicA0 specifies the basic a0 state for virtual machine size types. + BasicA0 VirtualMachineSizeTypes = "Basic_A0" + // BasicA1 specifies the basic a1 state for virtual machine size types. + BasicA1 VirtualMachineSizeTypes = "Basic_A1" + // BasicA2 specifies the basic a2 state for virtual machine size types. + BasicA2 VirtualMachineSizeTypes = "Basic_A2" + // BasicA3 specifies the basic a3 state for virtual machine size types. + BasicA3 VirtualMachineSizeTypes = "Basic_A3" + // BasicA4 specifies the basic a4 state for virtual machine size types. + BasicA4 VirtualMachineSizeTypes = "Basic_A4" + // StandardA0 specifies the standard a0 state for virtual machine size + // types. + StandardA0 VirtualMachineSizeTypes = "Standard_A0" + // StandardA1 specifies the standard a1 state for virtual machine size + // types. + StandardA1 VirtualMachineSizeTypes = "Standard_A1" + // StandardA10 specifies the standard a10 state for virtual machine size + // types. + StandardA10 VirtualMachineSizeTypes = "Standard_A10" + // StandardA11 specifies the standard a11 state for virtual machine size + // types. + StandardA11 VirtualMachineSizeTypes = "Standard_A11" + // StandardA2 specifies the standard a2 state for virtual machine size + // types. + StandardA2 VirtualMachineSizeTypes = "Standard_A2" + // StandardA3 specifies the standard a3 state for virtual machine size + // types. + StandardA3 VirtualMachineSizeTypes = "Standard_A3" + // StandardA4 specifies the standard a4 state for virtual machine size + // types. + StandardA4 VirtualMachineSizeTypes = "Standard_A4" + // StandardA5 specifies the standard a5 state for virtual machine size + // types. + StandardA5 VirtualMachineSizeTypes = "Standard_A5" + // StandardA6 specifies the standard a6 state for virtual machine size + // types. + StandardA6 VirtualMachineSizeTypes = "Standard_A6" + // StandardA7 specifies the standard a7 state for virtual machine size + // types. + StandardA7 VirtualMachineSizeTypes = "Standard_A7" + // StandardA8 specifies the standard a8 state for virtual machine size + // types. + StandardA8 VirtualMachineSizeTypes = "Standard_A8" + // StandardA9 specifies the standard a9 state for virtual machine size + // types. + StandardA9 VirtualMachineSizeTypes = "Standard_A9" + // StandardD1 specifies the standard d1 state for virtual machine size + // types. + StandardD1 VirtualMachineSizeTypes = "Standard_D1" + // StandardD11 specifies the standard d11 state for virtual machine size + // types. + StandardD11 VirtualMachineSizeTypes = "Standard_D11" + // StandardD11V2 specifies the standard d11v2 state for virtual machine + // size types. + StandardD11V2 VirtualMachineSizeTypes = "Standard_D11_v2" + // StandardD12 specifies the standard d12 state for virtual machine size + // types. + StandardD12 VirtualMachineSizeTypes = "Standard_D12" + // StandardD12V2 specifies the standard d12v2 state for virtual machine + // size types. + StandardD12V2 VirtualMachineSizeTypes = "Standard_D12_v2" + // StandardD13 specifies the standard d13 state for virtual machine size + // types. + StandardD13 VirtualMachineSizeTypes = "Standard_D13" + // StandardD13V2 specifies the standard d13v2 state for virtual machine + // size types. + StandardD13V2 VirtualMachineSizeTypes = "Standard_D13_v2" + // StandardD14 specifies the standard d14 state for virtual machine size + // types. + StandardD14 VirtualMachineSizeTypes = "Standard_D14" + // StandardD14V2 specifies the standard d14v2 state for virtual machine + // size types. + StandardD14V2 VirtualMachineSizeTypes = "Standard_D14_v2" + // StandardD15V2 specifies the standard d15v2 state for virtual machine + // size types. + StandardD15V2 VirtualMachineSizeTypes = "Standard_D15_v2" + // StandardD1V2 specifies the standard d1v2 state for virtual machine size + // types. + StandardD1V2 VirtualMachineSizeTypes = "Standard_D1_v2" + // StandardD2 specifies the standard d2 state for virtual machine size + // types. + StandardD2 VirtualMachineSizeTypes = "Standard_D2" + // StandardD2V2 specifies the standard d2v2 state for virtual machine size + // types. + StandardD2V2 VirtualMachineSizeTypes = "Standard_D2_v2" + // StandardD3 specifies the standard d3 state for virtual machine size + // types. + StandardD3 VirtualMachineSizeTypes = "Standard_D3" + // StandardD3V2 specifies the standard d3v2 state for virtual machine size + // types. + StandardD3V2 VirtualMachineSizeTypes = "Standard_D3_v2" + // StandardD4 specifies the standard d4 state for virtual machine size + // types. + StandardD4 VirtualMachineSizeTypes = "Standard_D4" + // StandardD4V2 specifies the standard d4v2 state for virtual machine size + // types. + StandardD4V2 VirtualMachineSizeTypes = "Standard_D4_v2" + // StandardD5V2 specifies the standard d5v2 state for virtual machine size + // types. + StandardD5V2 VirtualMachineSizeTypes = "Standard_D5_v2" + // StandardDS1 specifies the standard ds1 state for virtual machine size + // types. + StandardDS1 VirtualMachineSizeTypes = "Standard_DS1" + // StandardDS11 specifies the standard ds11 state for virtual machine size + // types. + StandardDS11 VirtualMachineSizeTypes = "Standard_DS11" + // StandardDS11V2 specifies the standard ds11v2 state for virtual machine + // size types. + StandardDS11V2 VirtualMachineSizeTypes = "Standard_DS11_v2" + // StandardDS12 specifies the standard ds12 state for virtual machine size + // types. + StandardDS12 VirtualMachineSizeTypes = "Standard_DS12" + // StandardDS12V2 specifies the standard ds12v2 state for virtual machine + // size types. + StandardDS12V2 VirtualMachineSizeTypes = "Standard_DS12_v2" + // StandardDS13 specifies the standard ds13 state for virtual machine size + // types. + StandardDS13 VirtualMachineSizeTypes = "Standard_DS13" + // StandardDS13V2 specifies the standard ds13v2 state for virtual machine + // size types. + StandardDS13V2 VirtualMachineSizeTypes = "Standard_DS13_v2" + // StandardDS14 specifies the standard ds14 state for virtual machine size + // types. + StandardDS14 VirtualMachineSizeTypes = "Standard_DS14" + // StandardDS14V2 specifies the standard ds14v2 state for virtual machine + // size types. + StandardDS14V2 VirtualMachineSizeTypes = "Standard_DS14_v2" + // StandardDS15V2 specifies the standard ds15v2 state for virtual machine + // size types. + StandardDS15V2 VirtualMachineSizeTypes = "Standard_DS15_v2" + // StandardDS1V2 specifies the standard ds1v2 state for virtual machine + // size types. + StandardDS1V2 VirtualMachineSizeTypes = "Standard_DS1_v2" + // StandardDS2 specifies the standard ds2 state for virtual machine size + // types. + StandardDS2 VirtualMachineSizeTypes = "Standard_DS2" + // StandardDS2V2 specifies the standard ds2v2 state for virtual machine + // size types. + StandardDS2V2 VirtualMachineSizeTypes = "Standard_DS2_v2" + // StandardDS3 specifies the standard ds3 state for virtual machine size + // types. + StandardDS3 VirtualMachineSizeTypes = "Standard_DS3" + // StandardDS3V2 specifies the standard ds3v2 state for virtual machine + // size types. + StandardDS3V2 VirtualMachineSizeTypes = "Standard_DS3_v2" + // StandardDS4 specifies the standard ds4 state for virtual machine size + // types. + StandardDS4 VirtualMachineSizeTypes = "Standard_DS4" + // StandardDS4V2 specifies the standard ds4v2 state for virtual machine + // size types. + StandardDS4V2 VirtualMachineSizeTypes = "Standard_DS4_v2" + // StandardDS5V2 specifies the standard ds5v2 state for virtual machine + // size types. + StandardDS5V2 VirtualMachineSizeTypes = "Standard_DS5_v2" + // StandardG1 specifies the standard g1 state for virtual machine size + // types. + StandardG1 VirtualMachineSizeTypes = "Standard_G1" + // StandardG2 specifies the standard g2 state for virtual machine size + // types. + StandardG2 VirtualMachineSizeTypes = "Standard_G2" + // StandardG3 specifies the standard g3 state for virtual machine size + // types. + StandardG3 VirtualMachineSizeTypes = "Standard_G3" + // StandardG4 specifies the standard g4 state for virtual machine size + // types. + StandardG4 VirtualMachineSizeTypes = "Standard_G4" + // StandardG5 specifies the standard g5 state for virtual machine size + // types. + StandardG5 VirtualMachineSizeTypes = "Standard_G5" + // StandardGS1 specifies the standard gs1 state for virtual machine size + // types. + StandardGS1 VirtualMachineSizeTypes = "Standard_GS1" + // StandardGS2 specifies the standard gs2 state for virtual machine size + // types. + StandardGS2 VirtualMachineSizeTypes = "Standard_GS2" + // StandardGS3 specifies the standard gs3 state for virtual machine size + // types. + StandardGS3 VirtualMachineSizeTypes = "Standard_GS3" + // StandardGS4 specifies the standard gs4 state for virtual machine size + // types. + StandardGS4 VirtualMachineSizeTypes = "Standard_GS4" + // StandardGS5 specifies the standard gs5 state for virtual machine size + // types. + StandardGS5 VirtualMachineSizeTypes = "Standard_GS5" +) + +// AdditionalUnattendContent is gets or sets additional XML formatted +// information that can be included in the Unattend.xml file, which is used +// by Windows Setup. Contents are defined by setting name, component name, +// and the pass in which the content is a applied. +type AdditionalUnattendContent struct { + PassName PassNames `json:"passName,omitempty"` + ComponentName ComponentNames `json:"componentName,omitempty"` + SettingName SettingNames `json:"settingName,omitempty"` + Content *string `json:"content,omitempty"` +} + +// APIEntityReference is the API entity reference. +type APIEntityReference struct { + ID *string `json:"id,omitempty"` +} + +// APIError is api error. +type APIError struct { + Details *[]APIErrorBase `json:"details,omitempty"` + Innererror *InnerError `json:"innererror,omitempty"` + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// APIErrorBase is api error base. +type APIErrorBase struct { + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// AvailabilitySet is create or update Availability Set parameters. +type AvailabilitySet struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *AvailabilitySetProperties `json:"properties,omitempty"` +} + +// AvailabilitySetListResult is the List Availability Set operation response. +type AvailabilitySetListResult struct { + autorest.Response `json:"-"` + Value *[]AvailabilitySet `json:"value,omitempty"` +} + +// AvailabilitySetProperties is the instance view of a resource. +type AvailabilitySetProperties struct { + PlatformUpdateDomainCount *int32 `json:"platformUpdateDomainCount,omitempty"` + PlatformFaultDomainCount *int32 `json:"platformFaultDomainCount,omitempty"` + VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// BootDiagnostics is describes Boot Diagnostics. +type BootDiagnostics struct { + Enabled *bool `json:"enabled,omitempty"` + StorageURI *string `json:"storageUri,omitempty"` +} + +// BootDiagnosticsInstanceView is the instance view of a virtual machine boot +// diagnostics. +type BootDiagnosticsInstanceView struct { + ConsoleScreenshotBlobURI *string `json:"consoleScreenshotBlobUri,omitempty"` + SerialConsoleLogBlobURI *string `json:"serialConsoleLogBlobUri,omitempty"` +} + +// DataDisk is describes a data disk. +type DataDisk struct { + Lun *int32 `json:"lun,omitempty"` + Name *string `json:"name,omitempty"` + Vhd *VirtualHardDisk `json:"vhd,omitempty"` + Image *VirtualHardDisk `json:"image,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` +} + +// DataDiskImage is contains the data disk images information. +type DataDiskImage struct { + Lun *int32 `json:"lun,omitempty"` +} + +// DiagnosticsProfile is describes a diagnostics profile. +type DiagnosticsProfile struct { + BootDiagnostics *BootDiagnostics `json:"bootDiagnostics,omitempty"` +} + +// DiskEncryptionSettings is describes a Encryption Settings for a Disk +type DiskEncryptionSettings struct { + DiskEncryptionKey *KeyVaultSecretReference `json:"diskEncryptionKey,omitempty"` + KeyEncryptionKey *KeyVaultKeyReference `json:"keyEncryptionKey,omitempty"` + Enabled *bool `json:"enabled,omitempty"` +} + +// DiskInstanceView is the instance view of the disk. +type DiskInstanceView struct { + Name *string `json:"name,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// HardwareProfile is describes a hardware profile. +type HardwareProfile struct { + VMSize VirtualMachineSizeTypes `json:"vmSize,omitempty"` +} + +// ImageReference is the image reference. +type ImageReference struct { + Publisher *string `json:"publisher,omitempty"` + Offer *string `json:"offer,omitempty"` + Sku *string `json:"sku,omitempty"` + Version *string `json:"version,omitempty"` +} + +// InnerError is inner error details. +type InnerError struct { + Exceptiontype *string `json:"exceptiontype,omitempty"` + Errordetail *string `json:"errordetail,omitempty"` +} + +// InstanceViewStatus is instance view status. +type InstanceViewStatus struct { + Code *string `json:"code,omitempty"` + Level StatusLevelTypes `json:"level,omitempty"` + DisplayStatus *string `json:"displayStatus,omitempty"` + Message *string `json:"message,omitempty"` + Time *date.Time `json:"time,omitempty"` +} + +// KeyVaultKeyReference is describes a reference to Key Vault Key +type KeyVaultKeyReference struct { + KeyURL *string `json:"keyUrl,omitempty"` + SourceVault *SubResource `json:"sourceVault,omitempty"` +} + +// KeyVaultSecretReference is describes a reference to Key Vault Secret +type KeyVaultSecretReference struct { + SecretURL *string `json:"secretUrl,omitempty"` + SourceVault *SubResource `json:"sourceVault,omitempty"` +} + +// LinuxConfiguration is describes Windows Configuration of the OS Profile. +type LinuxConfiguration struct { + DisablePasswordAuthentication *bool `json:"disablePasswordAuthentication,omitempty"` + SSH *SSHConfiguration `json:"ssh,omitempty"` +} + +// ListUsagesResult is the List Usages operation response. +type ListUsagesResult struct { + autorest.Response `json:"-"` + Value *[]Usage `json:"value,omitempty"` + NextLink *string `json:",omitempty"` +} + +// ListUsagesResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ListUsagesResult) ListUsagesResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ListVirtualMachineExtensionImage is +type ListVirtualMachineExtensionImage struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineExtensionImage `json:"value,omitempty"` +} + +// ListVirtualMachineImageResource is +type ListVirtualMachineImageResource struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineImageResource `json:"value,omitempty"` +} + +// LongRunningOperationProperties is compute-specific operation properties, +// including output +type LongRunningOperationProperties struct { + Output *map[string]interface{} `json:"output,omitempty"` +} + +// NetworkInterfaceReference is describes a network interface reference. +type NetworkInterfaceReference struct { + ID *string `json:"id,omitempty"` + Properties *NetworkInterfaceReferenceProperties `json:"properties,omitempty"` +} + +// NetworkInterfaceReferenceProperties is describes a network interface +// reference properties. +type NetworkInterfaceReferenceProperties struct { + Primary *bool `json:"primary,omitempty"` +} + +// NetworkProfile is describes a network profile. +type NetworkProfile struct { + NetworkInterfaces *[]NetworkInterfaceReference `json:"networkInterfaces,omitempty"` +} + +// OSDisk is describes an Operating System disk. +type OSDisk struct { + OsType OperatingSystemTypes `json:"osType,omitempty"` + EncryptionSettings *DiskEncryptionSettings `json:"encryptionSettings,omitempty"` + Name *string `json:"name,omitempty"` + Vhd *VirtualHardDisk `json:"vhd,omitempty"` + Image *VirtualHardDisk `json:"image,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` +} + +// OSDiskImage is contains the os disk image information. +type OSDiskImage struct { + OperatingSystem OperatingSystemTypes `json:"operatingSystem,omitempty"` +} + +// OSProfile is describes an OS profile. +type OSProfile struct { + ComputerName *string `json:"computerName,omitempty"` + AdminUsername *string `json:"adminUsername,omitempty"` + AdminPassword *string `json:"adminPassword,omitempty"` + CustomData *string `json:"customData,omitempty"` + WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` + LinuxConfiguration *LinuxConfiguration `json:"linuxConfiguration,omitempty"` + Secrets *[]VaultSecretGroup `json:"secrets,omitempty"` +} + +// Plan is plan for the resource. +type Plan struct { + Name *string `json:"name,omitempty"` + Publisher *string `json:"publisher,omitempty"` + Product *string `json:"product,omitempty"` + PromotionCode *string `json:"promotionCode,omitempty"` +} + +// PurchasePlan is used for establishing the purchase context of any 3rd Party +// artifact through MarketPlace. +type PurchasePlan struct { + Publisher *string `json:"publisher,omitempty"` + Name *string `json:"name,omitempty"` + Product *string `json:"product,omitempty"` +} + +// Resource is +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// Sku is describes a virtual machine scale set sku. +type Sku struct { + Name *string `json:"name,omitempty"` + Tier *string `json:"tier,omitempty"` + Capacity *int64 `json:"capacity,omitempty"` +} + +// SSHConfiguration is sSH configuration for Linux based VMs running on Azure +type SSHConfiguration struct { + PublicKeys *[]SSHPublicKey `json:"publicKeys,omitempty"` +} + +// SSHPublicKey is contains information about SSH certificate public key and +// the path on the Linux VM where the public key is placed. +type SSHPublicKey struct { + Path *string `json:"path,omitempty"` + KeyData *string `json:"keyData,omitempty"` +} + +// StorageProfile is describes a storage profile. +type StorageProfile struct { + ImageReference *ImageReference `json:"imageReference,omitempty"` + OsDisk *OSDisk `json:"osDisk,omitempty"` + DataDisks *[]DataDisk `json:"dataDisks,omitempty"` +} + +// SubResource is +type SubResource struct { + ID *string `json:"id,omitempty"` +} + +// UpgradePolicy is describes an upgrade policy - automatic or manual. +type UpgradePolicy struct { + Mode UpgradeMode `json:"mode,omitempty"` +} + +// Usage is describes Compute Resource Usage. +type Usage struct { + Unit *string `json:"unit,omitempty"` + CurrentValue *int32 `json:"currentValue,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Name *UsageName `json:"name,omitempty"` +} + +// UsageName is the Usage Names. +type UsageName struct { + Value *string `json:"value,omitempty"` + LocalizedValue *string `json:"localizedValue,omitempty"` +} + +// VaultCertificate is describes a single certificate reference in a Key +// Vault, and where the certificate should reside on the VM. +type VaultCertificate struct { + CertificateURL *string `json:"certificateUrl,omitempty"` + CertificateStore *string `json:"certificateStore,omitempty"` +} + +// VaultSecretGroup is describes a set of certificates which are all in the +// same Key Vault. +type VaultSecretGroup struct { + SourceVault *SubResource `json:"sourceVault,omitempty"` + VaultCertificates *[]VaultCertificate `json:"vaultCertificates,omitempty"` +} + +// VirtualHardDisk is describes the uri of a disk. +type VirtualHardDisk struct { + URI *string `json:"uri,omitempty"` +} + +// VirtualMachine is describes a Virtual Machine. +type VirtualMachine struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Plan *Plan `json:"plan,omitempty"` + Properties *VirtualMachineProperties `json:"properties,omitempty"` + Resources *[]VirtualMachineExtension `json:"resources,omitempty"` +} + +// VirtualMachineAgentInstanceView is the instance view of the VM Agent +// running on the virtual machine. +type VirtualMachineAgentInstanceView struct { + VMAgentVersion *string `json:"vmAgentVersion,omitempty"` + ExtensionHandlers *[]VirtualMachineExtensionHandlerInstanceView `json:"extensionHandlers,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// VirtualMachineCaptureParameters is capture Virtual Machine parameters. +type VirtualMachineCaptureParameters struct { + VhdPrefix *string `json:"vhdPrefix,omitempty"` + DestinationContainerName *string `json:"destinationContainerName,omitempty"` + OverwriteVhds *bool `json:"overwriteVhds,omitempty"` +} + +// VirtualMachineCaptureResult is resource Id. +type VirtualMachineCaptureResult struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *VirtualMachineCaptureResultProperties `json:"properties,omitempty"` +} + +// VirtualMachineCaptureResultProperties is compute-specific operation +// properties, including output +type VirtualMachineCaptureResultProperties struct { + Output *map[string]interface{} `json:"output,omitempty"` +} + +// VirtualMachineExtension is describes a Virtual Machine Extension. +type VirtualMachineExtension struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualMachineExtensionProperties `json:"properties,omitempty"` +} + +// VirtualMachineExtensionHandlerInstanceView is the instance view of a +// virtual machine extension handler. +type VirtualMachineExtensionHandlerInstanceView struct { + Type *string `json:"type,omitempty"` + TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` + Status *InstanceViewStatus `json:"status,omitempty"` +} + +// VirtualMachineExtensionImage is describes a Virtual Machine Extension Image. +type VirtualMachineExtensionImage struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualMachineExtensionImageProperties `json:"properties,omitempty"` +} + +// VirtualMachineExtensionImageProperties is describes the properties of a +// Virtual Machine Extension Image. +type VirtualMachineExtensionImageProperties struct { + OperatingSystem *string `json:"operatingSystem,omitempty"` + ComputeRole *string `json:"computeRole,omitempty"` + HandlerSchema *string `json:"handlerSchema,omitempty"` + VMScaleSetEnabled *bool `json:"vmScaleSetEnabled,omitempty"` + SupportsMultipleExtensions *bool `json:"supportsMultipleExtensions,omitempty"` +} + +// VirtualMachineExtensionInstanceView is the instance view of a virtual +// machine extension. +type VirtualMachineExtensionInstanceView struct { + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` + Substatuses *[]InstanceViewStatus `json:"substatuses,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// VirtualMachineExtensionProperties is describes the properties of a Virtual +// Machine Extension. +type VirtualMachineExtensionProperties struct { + ForceUpdateTag *string `json:"forceUpdateTag,omitempty"` + Publisher *string `json:"publisher,omitempty"` + Type *string `json:"type,omitempty"` + TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` + AutoUpgradeMinorVersion *bool `json:"autoUpgradeMinorVersion,omitempty"` + Settings *map[string]interface{} `json:"settings,omitempty"` + ProtectedSettings *map[string]interface{} `json:"protectedSettings,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + InstanceView *VirtualMachineExtensionInstanceView `json:"instanceView,omitempty"` +} + +// VirtualMachineImage is describes a Virtual Machine Image. +type VirtualMachineImage struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualMachineImageProperties `json:"properties,omitempty"` +} + +// VirtualMachineImageProperties is describes the properties of a Virtual +// Machine Image. +type VirtualMachineImageProperties struct { + Plan *PurchasePlan `json:"plan,omitempty"` + OsDiskImage *OSDiskImage `json:"osDiskImage,omitempty"` + DataDiskImages *[]DataDiskImage `json:"dataDiskImages,omitempty"` +} + +// VirtualMachineImageResource is virtual machine image resource information. +type VirtualMachineImageResource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// VirtualMachineInstanceView is the instance view of a virtual machine. +type VirtualMachineInstanceView struct { + PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` + PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` + RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` + VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` + Disks *[]DiskInstanceView `json:"disks,omitempty"` + Extensions *[]VirtualMachineExtensionInstanceView `json:"extensions,omitempty"` + BootDiagnostics *BootDiagnosticsInstanceView `json:"bootDiagnostics,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// VirtualMachineListResult is the List Virtual Machine operation response. +type VirtualMachineListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachine `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualMachineListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualMachineListResult) VirtualMachineListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualMachineProperties is describes the properties of a Virtual Machine. +type VirtualMachineProperties struct { + HardwareProfile *HardwareProfile `json:"hardwareProfile,omitempty"` + StorageProfile *StorageProfile `json:"storageProfile,omitempty"` + OsProfile *OSProfile `json:"osProfile,omitempty"` + NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` + DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` + AvailabilitySet *SubResource `json:"availabilitySet,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + InstanceView *VirtualMachineInstanceView `json:"instanceView,omitempty"` + LicenseType *string `json:"licenseType,omitempty"` + VMID *string `json:"vmId,omitempty"` +} + +// VirtualMachineScaleSet is describes a Virtual Machine Scale Set. +type VirtualMachineScaleSet struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Properties *VirtualMachineScaleSetProperties `json:"properties,omitempty"` +} + +// VirtualMachineScaleSetExtension is describes a Virtual Machine Scale Set +// Extension. +type VirtualMachineScaleSetExtension struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *VirtualMachineScaleSetExtensionProperties `json:"properties,omitempty"` +} + +// VirtualMachineScaleSetExtensionProfile is describes a virtual machine scale +// set extension profile. +type VirtualMachineScaleSetExtensionProfile struct { + Extensions *[]VirtualMachineScaleSetExtension `json:"extensions,omitempty"` +} + +// VirtualMachineScaleSetExtensionProperties is describes the properties of a +// Virtual Machine Scale Set Extension. +type VirtualMachineScaleSetExtensionProperties struct { + Publisher *string `json:"publisher,omitempty"` + Type *string `json:"type,omitempty"` + TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` + AutoUpgradeMinorVersion *bool `json:"autoUpgradeMinorVersion,omitempty"` + Settings *map[string]interface{} `json:"settings,omitempty"` + ProtectedSettings *map[string]interface{} `json:"protectedSettings,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VirtualMachineScaleSetInstanceView is the instance view of a virtual +// machine scale set. +type VirtualMachineScaleSetInstanceView struct { + autorest.Response `json:"-"` + VirtualMachine *VirtualMachineScaleSetInstanceViewStatusesSummary `json:"virtualMachine,omitempty"` + Extensions *[]VirtualMachineScaleSetVMExtensionsSummary `json:"extensions,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// VirtualMachineScaleSetInstanceViewStatusesSummary is instance view statuses +// summary for virtual machines of a virtual machine scale set. +type VirtualMachineScaleSetInstanceViewStatusesSummary struct { + StatusesSummary *[]VirtualMachineStatusCodeCount `json:"statusesSummary,omitempty"` +} + +// VirtualMachineScaleSetIPConfiguration is describes a virtual machine scale +// set network profile's IP configuration. +type VirtualMachineScaleSetIPConfiguration struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *VirtualMachineScaleSetIPConfigurationProperties `json:"properties,omitempty"` +} + +// VirtualMachineScaleSetIPConfigurationProperties is describes a virtual +// machine scale set network profile's IP configuration properties. +type VirtualMachineScaleSetIPConfigurationProperties struct { + Subnet *APIEntityReference `json:"subnet,omitempty"` + ApplicationGatewayBackendAddressPools *[]SubResource `json:"applicationGatewayBackendAddressPools,omitempty"` + LoadBalancerBackendAddressPools *[]SubResource `json:"loadBalancerBackendAddressPools,omitempty"` + LoadBalancerInboundNatPools *[]SubResource `json:"loadBalancerInboundNatPools,omitempty"` +} + +// VirtualMachineScaleSetListResult is the List Virtual Machine operation +// response. +type VirtualMachineScaleSetListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineScaleSet `json:"value,omitempty"` + NextLink *string `json:",omitempty"` +} + +// VirtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualMachineScaleSetListResult) VirtualMachineScaleSetListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualMachineScaleSetListSkusResult is the Virtual Machine Scale Set List +// Skus operation response. +type VirtualMachineScaleSetListSkusResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineScaleSetSku `json:"value,omitempty"` + NextLink *string `json:",omitempty"` +} + +// VirtualMachineScaleSetListSkusResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualMachineScaleSetListSkusResult) VirtualMachineScaleSetListSkusResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualMachineScaleSetListWithLinkResult is the List Virtual Machine +// operation response. +type VirtualMachineScaleSetListWithLinkResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineScaleSet `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualMachineScaleSetListWithLinkResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualMachineScaleSetListWithLinkResult) VirtualMachineScaleSetListWithLinkResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualMachineScaleSetNetworkConfiguration is describes a virtual machine +// scale set network profile's network configurations. +type VirtualMachineScaleSetNetworkConfiguration struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Properties *VirtualMachineScaleSetNetworkConfigurationProperties `json:"properties,omitempty"` +} + +// VirtualMachineScaleSetNetworkConfigurationProperties is describes a virtual +// machine scale set network profile's IP configuration. +type VirtualMachineScaleSetNetworkConfigurationProperties struct { + Primary *bool `json:"primary,omitempty"` + IPConfigurations *[]VirtualMachineScaleSetIPConfiguration `json:"ipConfigurations,omitempty"` +} + +// VirtualMachineScaleSetNetworkProfile is describes a virtual machine scale +// set network profile. +type VirtualMachineScaleSetNetworkProfile struct { + NetworkInterfaceConfigurations *[]VirtualMachineScaleSetNetworkConfiguration `json:"networkInterfaceConfigurations,omitempty"` +} + +// VirtualMachineScaleSetOSDisk is describes a virtual machine scale set +// operating system disk. +type VirtualMachineScaleSetOSDisk struct { + Name *string `json:"name,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` + OsType OperatingSystemTypes `json:"osType,omitempty"` + Image *VirtualHardDisk `json:"image,omitempty"` + VhdContainers *[]string `json:"vhdContainers,omitempty"` +} + +// VirtualMachineScaleSetOSProfile is describes a virtual machine scale set OS +// profile. +type VirtualMachineScaleSetOSProfile struct { + ComputerNamePrefix *string `json:"computerNamePrefix,omitempty"` + AdminUsername *string `json:"adminUsername,omitempty"` + AdminPassword *string `json:"adminPassword,omitempty"` + CustomData *string `json:"customData,omitempty"` + WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` + LinuxConfiguration *LinuxConfiguration `json:"linuxConfiguration,omitempty"` + Secrets *[]VaultSecretGroup `json:"secrets,omitempty"` +} + +// VirtualMachineScaleSetProperties is describes the properties of a Virtual +// Machine Scale Set. +type VirtualMachineScaleSetProperties struct { + UpgradePolicy *UpgradePolicy `json:"upgradePolicy,omitempty"` + VirtualMachineProfile *VirtualMachineScaleSetVMProfile `json:"virtualMachineProfile,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + OverProvision *bool `json:"overProvision,omitempty"` +} + +// VirtualMachineScaleSetSku is describes an available virtual machine scale +// set sku. +type VirtualMachineScaleSetSku struct { + ResourceType *string `json:"resourceType,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Capacity *VirtualMachineScaleSetSkuCapacity `json:"capacity,omitempty"` +} + +// VirtualMachineScaleSetSkuCapacity is describes scaling information of a sku. +type VirtualMachineScaleSetSkuCapacity struct { + Minimum *int64 `json:"minimum,omitempty"` + Maximum *int64 `json:"maximum,omitempty"` + DefaultCapacity *int64 `json:"defaultCapacity,omitempty"` + ScaleType VirtualMachineScaleSetSkuScaleType `json:"scaleType,omitempty"` +} + +// VirtualMachineScaleSetStorageProfile is describes a virtual machine scale +// set storage profile. +type VirtualMachineScaleSetStorageProfile struct { + ImageReference *ImageReference `json:"imageReference,omitempty"` + OsDisk *VirtualMachineScaleSetOSDisk `json:"osDisk,omitempty"` +} + +// VirtualMachineScaleSetVM is describes a virtual machine scale set virtual +// machine. +type VirtualMachineScaleSetVM struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + InstanceID *string `json:"instanceId,omitempty"` + Sku *Sku `json:"sku,omitempty"` + Properties *VirtualMachineScaleSetVMProperties `json:"properties,omitempty"` + Plan *Plan `json:"plan,omitempty"` + Resources *[]VirtualMachineExtension `json:"resources,omitempty"` +} + +// VirtualMachineScaleSetVMExtensionsSummary is extensions summary for virtual +// machines of a virtual machine scale set. +type VirtualMachineScaleSetVMExtensionsSummary struct { + Name *string `json:"name,omitempty"` + StatusesSummary *[]VirtualMachineStatusCodeCount `json:"statusesSummary,omitempty"` +} + +// VirtualMachineScaleSetVMInstanceIDs is specifies the list of virtual +// machine scale set instance IDs. +type VirtualMachineScaleSetVMInstanceIDs struct { + InstanceIds *[]string `json:"instanceIds,omitempty"` +} + +// VirtualMachineScaleSetVMInstanceRequiredIDs is specifies the list of +// virtual machine scale set instance IDs. +type VirtualMachineScaleSetVMInstanceRequiredIDs struct { + InstanceIds *[]string `json:"instanceIds,omitempty"` +} + +// VirtualMachineScaleSetVMInstanceView is the instance view of a virtual +// machine scale set VM. +type VirtualMachineScaleSetVMInstanceView struct { + autorest.Response `json:"-"` + PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` + PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` + RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` + VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` + Disks *[]DiskInstanceView `json:"disks,omitempty"` + Extensions *[]VirtualMachineExtensionInstanceView `json:"extensions,omitempty"` + BootDiagnostics *BootDiagnosticsInstanceView `json:"bootDiagnostics,omitempty"` + Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` +} + +// VirtualMachineScaleSetVMListResult is the List Virtual Machine Scale Set +// VMs operation response. +type VirtualMachineScaleSetVMListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineScaleSetVM `json:"value,omitempty"` + NextLink *string `json:",omitempty"` +} + +// VirtualMachineScaleSetVMListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualMachineScaleSetVMListResult) VirtualMachineScaleSetVMListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualMachineScaleSetVMProfile is describes a virtual machine scale set +// virtual machine profile. +type VirtualMachineScaleSetVMProfile struct { + OsProfile *VirtualMachineScaleSetOSProfile `json:"osProfile,omitempty"` + StorageProfile *VirtualMachineScaleSetStorageProfile `json:"storageProfile,omitempty"` + NetworkProfile *VirtualMachineScaleSetNetworkProfile `json:"networkProfile,omitempty"` + ExtensionProfile *VirtualMachineScaleSetExtensionProfile `json:"extensionProfile,omitempty"` +} + +// VirtualMachineScaleSetVMProperties is describes the properties of a virtual +// machine scale set virtual machine. +type VirtualMachineScaleSetVMProperties struct { + LatestModelApplied *bool `json:"latestModelApplied,omitempty"` + InstanceView *VirtualMachineInstanceView `json:"instanceView,omitempty"` + HardwareProfile *HardwareProfile `json:"hardwareProfile,omitempty"` + StorageProfile *StorageProfile `json:"storageProfile,omitempty"` + OsProfile *OSProfile `json:"osProfile,omitempty"` + NetworkProfile *NetworkProfile `json:"networkProfile,omitempty"` + DiagnosticsProfile *DiagnosticsProfile `json:"diagnosticsProfile,omitempty"` + AvailabilitySet *SubResource `json:"availabilitySet,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + LicenseType *string `json:"licenseType,omitempty"` +} + +// VirtualMachineSize is describes the properties of a VM size. +type VirtualMachineSize struct { + Name *string `json:"name,omitempty"` + NumberOfCores *int32 `json:"numberOfCores,omitempty"` + OsDiskSizeInMB *int32 `json:"osDiskSizeInMB,omitempty"` + ResourceDiskSizeInMB *int32 `json:"resourceDiskSizeInMB,omitempty"` + MemoryInMB *int32 `json:"memoryInMB,omitempty"` + MaxDataDiskCount *int32 `json:"maxDataDiskCount,omitempty"` +} + +// VirtualMachineSizeListResult is the List Virtual Machine operation response. +type VirtualMachineSizeListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineSize `json:"value,omitempty"` +} + +// VirtualMachineStatusCodeCount is the status code and count of the virtual +// machine scale set instance view status summary. +type VirtualMachineStatusCodeCount struct { + Code *string `json:"code,omitempty"` + Count *int32 `json:"count,omitempty"` +} + +// WindowsConfiguration is describes Windows Configuration of the OS Profile. +type WindowsConfiguration struct { + ProvisionVMAgent *bool `json:"provisionVMAgent,omitempty"` + EnableAutomaticUpdates *bool `json:"enableAutomaticUpdates,omitempty"` + TimeZone *string `json:"timeZone,omitempty"` + AdditionalUnattendContent *[]AdditionalUnattendContent `json:"additionalUnattendContent,omitempty"` + WinRM *WinRMConfiguration `json:"winRM,omitempty"` +} + +// WinRMConfiguration is describes Windows Remote Management configuration of +// the VM +type WinRMConfiguration struct { + Listeners *[]WinRMListener `json:"listeners,omitempty"` +} + +// WinRMListener is describes Protocol and thumbprint of Windows Remote +// Management listener +type WinRMListener struct { + Protocol ProtocolTypes `json:"protocol,omitempty"` + CertificateURL *string `json:"certificateUrl,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go new file mode 100644 index 000000000000..e54d8251dd86 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go @@ -0,0 +1,121 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// UsageOperationsClient is the the Compute Management Client. +type UsageOperationsClient struct { + ManagementClient +} + +// NewUsageOperationsClient creates an instance of the UsageOperationsClient +// client. +func NewUsageOperationsClient(subscriptionID string) UsageOperationsClient { + return UsageOperationsClient{New(subscriptionID)} +} + +// List lists compute usages for a subscription. +// +// location is the location upon which resource usage is queried. +func (client UsageOperationsClient) List(location string) (result ListUsagesResult, err error) { + req, err := client.ListPreparer(location) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client UsageOperationsClient) ListPreparer(location string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client UsageOperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client UsageOperationsClient) ListResponder(resp *http.Response) (result ListUsagesResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client UsageOperationsClient) ListNextResults(lastResults ListUsagesResult) (result ListUsagesResult, err error) { + req, err := lastResults.ListUsagesResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go new file mode 100644 index 000000000000..b107a0b64add --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go @@ -0,0 +1,43 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "fmt" +) + +const ( + major = "3" + minor = "0" + patch = "0" + // Always begin a "tag" with a dash (as per http://semver.org) + tag = "-beta" + semVerFormat = "%s.%s.%s%s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" +) + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return fmt.Sprintf(userAgentFormat, Version(), "compute", "2016-03-30") +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return fmt.Sprintf(semVerFormat, major, minor, patch, tag) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go new file mode 100644 index 000000000000..3438a25551e7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go @@ -0,0 +1,232 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineExtensionImagesClient is the the Compute Management Client. +type VirtualMachineExtensionImagesClient struct { + ManagementClient +} + +// NewVirtualMachineExtensionImagesClient creates an instance of the +// VirtualMachineExtensionImagesClient client. +func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachineExtensionImagesClient { + return VirtualMachineExtensionImagesClient{New(subscriptionID)} +} + +// Get gets a virtual machine extension image. +// +func (client VirtualMachineExtensionImagesClient) Get(location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, err error) { + req, err := client.GetPreparer(location, publisherName, typeParameter, version) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineExtensionImagesClient) GetPreparer(location string, publisherName string, typeParameter string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "publisherName": autorest.Encode("path", publisherName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "type": autorest.Encode("path", typeParameter), + "version": autorest.Encode("path", version), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionImagesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Response) (result VirtualMachineExtensionImage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListTypes gets a list of virtual machine extension image types. +// +func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result ListVirtualMachineExtensionImage, err error) { + req, err := client.ListTypesPreparer(location, publisherName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") + } + + resp, err := client.ListTypesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") + } + + result, err = client.ListTypesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure responding to request") + } + + return +} + +// ListTypesPreparer prepares the ListTypes request. +func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(location string, publisherName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "publisherName": autorest.Encode("path", publisherName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListTypesSender sends the ListTypes request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionImagesClient) ListTypesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListTypesResponder handles the response to the ListTypes request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http.Response) (result ListVirtualMachineExtensionImage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListVersions gets a list of virtual machine extension image versions. +// +// filter is the filter to apply on the operation. +func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (result ListVirtualMachineExtensionImage, err error) { + req, err := client.ListVersionsPreparer(location, publisherName, typeParameter, filter, top, orderby) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") + } + + resp, err := client.ListVersionsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") + } + + result, err = client.ListVersionsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure responding to request") + } + + return +} + +// ListVersionsPreparer prepares the ListVersions request. +func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "publisherName": autorest.Encode("path", publisherName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "type": autorest.Encode("path", typeParameter), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListVersionsSender sends the ListVersions request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionImagesClient) ListVersionsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListVersionsResponder handles the response to the ListVersions request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionImagesClient) ListVersionsResponder(resp *http.Response) (result ListVirtualMachineExtensionImage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go new file mode 100644 index 000000000000..a2d43b3c55f9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go @@ -0,0 +1,247 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineExtensionsClient is the the Compute Management Client. +type VirtualMachineExtensionsClient struct { + ManagementClient +} + +// NewVirtualMachineExtensionsClient creates an instance of the +// VirtualMachineExtensionsClient client. +func NewVirtualMachineExtensionsClient(subscriptionID string) VirtualMachineExtensionsClient { + return VirtualMachineExtensionsClient{New(subscriptionID)} +} + +// CreateOrUpdate the operation to create or update the extension. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine where the extension should be create or updated. +// vmExtensionName is the name of the virtual machine extension. +// extensionParameters is parameters supplied to the Create Virtual Machine +// Extension operation. +func (client VirtualMachineExtensionsClient) CreateOrUpdate(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, vmExtensionName, extensionParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmExtensionName": autorest.Encode("path", vmExtensionName), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), + autorest.WithJSON(extensionParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the operation to delete the extension. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine where the extension should be deleted. vmExtensionName +// is the name of the virtual machine extension. +func (client VirtualMachineExtensionsClient) Delete(resourceGroupName string, vmName string, vmExtensionName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmName, vmExtensionName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName string, vmName string, vmExtensionName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmExtensionName": autorest.Encode("path", vmExtensionName), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the operation to get the extension. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine containing the extension. vmExtensionName is the name +// of the virtual machine extension. expand is the expand expression to apply +// on the operation. +func (client VirtualMachineExtensionsClient) Get(resourceGroupName string, vmName string, vmExtensionName string, expand string) (result VirtualMachineExtension, err error) { + req, err := client.GetPreparer(resourceGroupName, vmName, vmExtensionName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineExtensionsClient) GetPreparer(resourceGroupName string, vmName string, vmExtensionName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmExtensionName": autorest.Encode("path", vmExtensionName), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineExtensionsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineExtensionsClient) GetResponder(resp *http.Response) (result VirtualMachineExtension, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go new file mode 100644 index 000000000000..5dba9ca7d55e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go @@ -0,0 +1,356 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineImagesClient is the the Compute Management Client. +type VirtualMachineImagesClient struct { + ManagementClient +} + +// NewVirtualMachineImagesClient creates an instance of the +// VirtualMachineImagesClient client. +func NewVirtualMachineImagesClient(subscriptionID string) VirtualMachineImagesClient { + return VirtualMachineImagesClient{New(subscriptionID)} +} + +// Get gets a virtual machine image. +// +func (client VirtualMachineImagesClient) Get(location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, err error) { + req, err := client.GetPreparer(location, publisherName, offer, skus, version) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineImagesClient) GetPreparer(location string, publisherName string, offer string, skus string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "offer": autorest.Encode("path", offer), + "publisherName": autorest.Encode("path", publisherName), + "skus": autorest.Encode("path", skus), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineImagesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (result VirtualMachineImage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets a list of virtual machine images. +// +// filter is the filter to apply on the operation. +func (client VirtualMachineImagesClient) List(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (result ListVirtualMachineImageResource, err error) { + req, err := client.ListPreparer(location, publisherName, offer, skus, filter, top, orderby) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachineImagesClient) ListPreparer(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "offer": autorest.Encode("path", offer), + "publisherName": autorest.Encode("path", publisherName), + "skus": autorest.Encode("path", skus), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineImagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListOffers gets a list of virtual machine image offers. +// +func (client VirtualMachineImagesClient) ListOffers(location string, publisherName string) (result ListVirtualMachineImageResource, err error) { + req, err := client.ListOffersPreparer(location, publisherName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request") + } + + resp, err := client.ListOffersSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") + } + + result, err = client.ListOffersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure responding to request") + } + + return +} + +// ListOffersPreparer prepares the ListOffers request. +func (client VirtualMachineImagesClient) ListOffersPreparer(location string, publisherName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "publisherName": autorest.Encode("path", publisherName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListOffersSender sends the ListOffers request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineImagesClient) ListOffersSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListOffersResponder handles the response to the ListOffers request. The method always +// closes the http.Response Body. +func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListPublishers gets a list of virtual machine image publishers. +// +func (client VirtualMachineImagesClient) ListPublishers(location string) (result ListVirtualMachineImageResource, err error) { + req, err := client.ListPublishersPreparer(location) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request") + } + + resp, err := client.ListPublishersSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") + } + + result, err = client.ListPublishersResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure responding to request") + } + + return +} + +// ListPublishersPreparer prepares the ListPublishers request. +func (client VirtualMachineImagesClient) ListPublishersPreparer(location string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListPublishersSender sends the ListPublishers request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineImagesClient) ListPublishersSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListPublishersResponder handles the response to the ListPublishers request. The method always +// closes the http.Response Body. +func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListSkus gets a list of virtual machine image skus. +// +func (client VirtualMachineImagesClient) ListSkus(location string, publisherName string, offer string) (result ListVirtualMachineImageResource, err error) { + req, err := client.ListSkusPreparer(location, publisherName, offer) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request") + } + + resp, err := client.ListSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") + } + + result, err = client.ListSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure responding to request") + } + + return +} + +// ListSkusPreparer prepares the ListSkus request. +func (client VirtualMachineImagesClient) ListSkusPreparer(location string, publisherName string, offer string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "offer": autorest.Encode("path", offer), + "publisherName": autorest.Encode("path", publisherName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSkusSender sends the ListSkus request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineImagesClient) ListSkusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListSkusResponder handles the response to the ListSkus request. The method always +// closes the http.Response Body. +func (client VirtualMachineImagesClient) ListSkusResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go new file mode 100644 index 000000000000..598eae4f5d0d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go @@ -0,0 +1,918 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachinesClient is the the Compute Management Client. +type VirtualMachinesClient struct { + ManagementClient +} + +// NewVirtualMachinesClient creates an instance of the VirtualMachinesClient +// client. +func NewVirtualMachinesClient(subscriptionID string) VirtualMachinesClient { + return VirtualMachinesClient{New(subscriptionID)} +} + +// Capture captures the VM by copying virtual hard disks of the VM and outputs +// a template that can be used to create similar VMs. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. parameters is parameters supplied to the Capture +// Virtual Machine operation. +func (client VirtualMachinesClient) Capture(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CapturePreparer(resourceGroupName, vmName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", nil, "Failure preparing request") + } + + resp, err := client.CaptureSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure sending request") + } + + result, err = client.CaptureResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure responding to request") + } + + return +} + +// CapturePreparer prepares the Capture request. +func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/capture", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CaptureSender sends the Capture request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) CaptureSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CaptureResponder handles the response to the Capture request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdate the operation to create or update a virtual machine. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. parameters is parameters supplied to the Create +// Virtual Machine operation. +func (client VirtualMachinesClient) CreateOrUpdate(resourceGroupName string, vmName string, parameters VirtualMachine, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, parameters VirtualMachine, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Deallocate shuts down the Virtual Machine and releases the compute +// resources. You are not billed for the compute resources that this Virtual +// Machine uses. This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Deallocate(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", nil, "Failure preparing request") + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure sending request") + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure responding to request") + } + + return +} + +// DeallocatePreparer prepares the Deallocate request. +func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeallocateSender sends the Deallocate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) DeallocateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeallocateResponder handles the response to the Deallocate request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the operation to delete a virtual machine. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Delete(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Generalize sets the state of the VM as Generalized. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Generalize(resourceGroupName string, vmName string) (result autorest.Response, err error) { + req, err := client.GeneralizePreparer(resourceGroupName, vmName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", nil, "Failure preparing request") + } + + resp, err := client.GeneralizeSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure sending request") + } + + result, err = client.GeneralizeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure responding to request") + } + + return +} + +// GeneralizePreparer prepares the Generalize request. +func (client VirtualMachinesClient) GeneralizePreparer(resourceGroupName string, vmName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/generalize", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GeneralizeSender sends the Generalize request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) GeneralizeSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GeneralizeResponder handles the response to the Generalize request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the operation to get a virtual machine. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. expand is the expand expression to apply on the +// operation. Possible values include: 'instanceView' +func (client VirtualMachinesClient) Get(resourceGroupName string, vmName string, expand InstanceViewTypes) (result VirtualMachine, err error) { + req, err := client.GetPreparer(resourceGroupName, vmName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachinesClient) GetPreparer(resourceGroupName string, vmName string, expand InstanceViewTypes) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(string(expand)) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result VirtualMachine, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the operation to list virtual machines under a resource group. +// +// resourceGroupName is the name of the resource group. +func (client VirtualMachinesClient) List(resourceGroupName string) (result VirtualMachineListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachinesClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ListResponder(resp *http.Response) (result VirtualMachineListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAll gets the list of Virtual Machines in the subscription. Use nextLink +// property in the response to get the next page of Virtual Machines. Do this +// till nextLink is not null to fetch all the Virtual Machines. +func (client VirtualMachinesClient) ListAll() (result VirtualMachineListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client VirtualMachinesClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ListAllResponder(resp *http.Response) (result VirtualMachineListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { + req, err := lastResults.VirtualMachineListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} + +// ListAvailableSizes lists all available virtual machine sizes it can be +// resized to for a virtual machine. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) ListAvailableSizes(resourceGroupName string, vmName string) (result VirtualMachineSizeListResult, err error) { + req, err := client.ListAvailableSizesPreparer(resourceGroupName, vmName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", nil, "Failure preparing request") + } + + resp, err := client.ListAvailableSizesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending request") + } + + result, err = client.ListAvailableSizesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure responding to request") + } + + return +} + +// ListAvailableSizesPreparer prepares the ListAvailableSizes request. +func (client VirtualMachinesClient) ListAvailableSizesPreparer(resourceGroupName string, vmName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/vmSizes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ListAvailableSizesResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// PowerOff the operation to power off (stop) a virtual machine. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) PowerOff(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", nil, "Failure preparing request") + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure sending request") + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure responding to request") + } + + return +} + +// PowerOffPreparer prepares the PowerOff request. +func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// PowerOffSender sends the PowerOff request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) PowerOffSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// PowerOffResponder handles the response to the PowerOff request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Redeploy the operation to redeploy a virtual machine. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Redeploy(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RedeployPreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", nil, "Failure preparing request") + } + + resp, err := client.RedeploySender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure sending request") + } + + result, err = client.RedeployResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure responding to request") + } + + return +} + +// RedeployPreparer prepares the Redeploy request. +func (client VirtualMachinesClient) RedeployPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/redeploy", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RedeploySender sends the Redeploy request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) RedeploySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RedeployResponder handles the response to the Redeploy request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Restart the operation to restart a virtual machine. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Restart(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", nil, "Failure preparing request") + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure sending request") + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure responding to request") + } + + return +} + +// RestartPreparer prepares the Restart request. +func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RestartSender sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) RestartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RestartResponder handles the response to the Restart request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start the operation to start a virtual machine. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmName is the name of +// the virtual machine. +func (client VirtualMachinesClient) Start(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", nil, "Failure preparing request") + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure sending request") + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure responding to request") + } + + return +} + +// StartPreparer prepares the Start request. +func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", vmName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) StartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go new file mode 100644 index 000000000000..dd16405fa533 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go @@ -0,0 +1,1063 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineScaleSetsClient is the the Compute Management Client. +type VirtualMachineScaleSetsClient struct { + ManagementClient +} + +// NewVirtualMachineScaleSetsClient creates an instance of the +// VirtualMachineScaleSetsClient client. +func NewVirtualMachineScaleSetsClient(subscriptionID string) VirtualMachineScaleSetsClient { + return VirtualMachineScaleSetsClient{New(subscriptionID)} +} + +// CreateOrUpdate allows you to create or update a virtual machine scale set +// by providing parameters or a path to pre-configured parameter file. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. name is parameters +// supplied to the Create Virtual Machine Scale Set operation. parameters is +// parameters supplied to the Create Virtual Machine Scale Set operation. +func (client VirtualMachineScaleSetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{name}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Deallocate allows you to deallocate virtual machines in a virtual machine +// scale set. Shuts down the virtual machines and releases the compute +// resources. You are not billed for the compute resources that this virtual +// machine scale set uses. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be +// used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) Deallocate(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", nil, "Failure preparing request") + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure sending request") + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure responding to request") + } + + return +} + +// DeallocatePreparer prepares the Deallocate request. +func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if vmInstanceIDs != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(vmInstanceIDs)) + } + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeallocateSender sends the Deallocate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) DeallocateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeallocateResponder handles the response to the Deallocate request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete allows you to delete a virtual machine scale set. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. +func (client VirtualMachineScaleSetsClient) Delete(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DeleteInstances allows you to delete virtual machines in a virtual machine +// scale set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) DeleteInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", nil, "Failure preparing request") + } + + resp, err := client.DeleteInstancesSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure sending request") + } + + result, err = client.DeleteInstancesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure responding to request") + } + + return +} + +// DeleteInstancesPreparer prepares the DeleteInstances request. +func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete", pathParameters), + autorest.WithJSON(vmInstanceIDs), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteInstancesSender sends the DeleteInstances request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) DeleteInstancesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteInstancesResponder handles the response to the DeleteInstances request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get display information about a virtual machine scale set. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. +func (client VirtualMachineScaleSetsClient) Get(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSet, err error) { + req, err := client.GetPreparer(resourceGroupName, vmScaleSetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineScaleSetsClient) GetPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetInstanceView displays status of a virtual machine scale set instance. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. +func (client VirtualMachineScaleSetsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetInstanceView, err error) { + req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", nil, "Failure preparing request") + } + + resp, err := client.GetInstanceViewSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure sending request") + } + + result, err = client.GetInstanceViewResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure responding to request") + } + + return +} + +// GetInstanceViewPreparer prepares the GetInstanceView request. +func (client VirtualMachineScaleSetsClient) GetInstanceViewPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/instanceView", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetInstanceViewSender sends the GetInstanceView request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetInstanceViewResponder handles the response to the GetInstanceView request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetInstanceView, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all virtual machine scale sets under a resource group. +// +// resourceGroupName is the name of the resource group. +func (client VirtualMachineScaleSetsClient) List(resourceGroupName string) (result VirtualMachineScaleSetListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachineScaleSetsClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualMachineScaleSetListResult) (result VirtualMachineScaleSetListResult, err error) { + req, err := lastResults.VirtualMachineScaleSetListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll lists all Virtual Machine Scale Sets in the subscription. Use +// nextLink property in the response to get the next page of Virtual Machine +// Scale Sets. Do this till nextLink is not null to fetch all the Virtual +// Machine Scale Sets. +func (client VirtualMachineScaleSetsClient) ListAll() (result VirtualMachineScaleSetListWithLinkResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client VirtualMachineScaleSetsClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) ListAllResponder(resp *http.Response) (result VirtualMachineScaleSetListWithLinkResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults VirtualMachineScaleSetListWithLinkResult) (result VirtualMachineScaleSetListWithLinkResult, err error) { + req, err := lastResults.VirtualMachineScaleSetListWithLinkResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} + +// ListSkus displays available skus for your virtual machine scale set +// including the minimum and maximum vm instances allowed for a particular +// sku. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. +func (client VirtualMachineScaleSetsClient) ListSkus(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetListSkusResult, err error) { + req, err := client.ListSkusPreparer(resourceGroupName, vmScaleSetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing request") + } + + resp, err := client.ListSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending request") + } + + result, err = client.ListSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure responding to request") + } + + return +} + +// ListSkusPreparer prepares the ListSkus request. +func (client VirtualMachineScaleSetsClient) ListSkusPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSkusSender sends the ListSkus request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) ListSkusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListSkusResponder handles the response to the ListSkus request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) ListSkusResponder(resp *http.Response) (result VirtualMachineScaleSetListSkusResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListSkusNextResults retrieves the next set of results, if any. +func (client VirtualMachineScaleSetsClient) ListSkusNextResults(lastResults VirtualMachineScaleSetListSkusResult) (result VirtualMachineScaleSetListSkusResult, err error) { + req, err := lastResults.VirtualMachineScaleSetListSkusResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending next results request request") + } + + result, err = client.ListSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure responding to next results request request") + } + + return +} + +// PowerOff allows you to power off (stop) virtual machines in a virtual +// machine scale set. Note that resources are still attached and you are +// getting charged for the resources. Use deallocate to release resources. +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) PowerOff(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", nil, "Failure preparing request") + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure sending request") + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure responding to request") + } + + return +} + +// PowerOffPreparer prepares the PowerOff request. +func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if vmInstanceIDs != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(vmInstanceIDs)) + } + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// PowerOffSender sends the PowerOff request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) PowerOffSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// PowerOffResponder handles the response to the PowerOff request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Reimage allows you to re-image(update the version of the installed +// operating system) virtual machines in a virtual machine scale set. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. +func (client VirtualMachineScaleSetsClient) Reimage(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ReimagePreparer(resourceGroupName, vmScaleSetName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", nil, "Failure preparing request") + } + + resp, err := client.ReimageSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure sending request") + } + + result, err = client.ReimageResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure responding to request") + } + + return +} + +// ReimagePreparer prepares the Reimage request. +func (client VirtualMachineScaleSetsClient) ReimagePreparer(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ReimageSender sends the Reimage request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) ReimageSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ReimageResponder handles the response to the Reimage request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Restart allows you to restart virtual machines in a virtual machine scale +// set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) Restart(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", nil, "Failure preparing request") + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure sending request") + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure responding to request") + } + + return +} + +// RestartPreparer prepares the Restart request. +func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if vmInstanceIDs != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(vmInstanceIDs)) + } + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RestartSender sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) RestartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RestartResponder handles the response to the Restart request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start allows you to start virtual machines in a virtual machine scale set. +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) Start(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", nil, "Failure preparing request") + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure sending request") + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure responding to request") + } + + return +} + +// StartPreparer prepares the Start request. +func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if vmInstanceIDs != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(vmInstanceIDs)) + } + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) StartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// UpdateInstances allows you to manually upgrade virtual machines in a +// virtual machine scale set. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. vmInstanceIDs is the list of +// virtual machine scale set instance IDs. +func (client VirtualMachineScaleSetsClient) UpdateInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.UpdateInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", nil, "Failure preparing request") + } + + resp, err := client.UpdateInstancesSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure sending request") + } + + result, err = client.UpdateInstancesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure responding to request") + } + + return +} + +// UpdateInstancesPreparer prepares the UpdateInstances request. +func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade", pathParameters), + autorest.WithJSON(vmInstanceIDs), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// UpdateInstancesSender sends the UpdateInstances request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) UpdateInstancesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// UpdateInstancesResponder handles the response to the UpdateInstances request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) UpdateInstancesResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go new file mode 100644 index 000000000000..436e0804429c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go @@ -0,0 +1,683 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineScaleSetVMsClient is the the Compute Management Client. +type VirtualMachineScaleSetVMsClient struct { + ManagementClient +} + +// NewVirtualMachineScaleSetVMsClient creates an instance of the +// VirtualMachineScaleSetVMsClient client. +func NewVirtualMachineScaleSetVMsClient(subscriptionID string) VirtualMachineScaleSetVMsClient { + return VirtualMachineScaleSetVMsClient{New(subscriptionID)} +} + +// Deallocate allows you to deallocate a virtual machine virtual machine scale +// set.Shuts down the virtual machine and releases the compute resources. You +// are not billed for the compute resources that this virtual machine uses. +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Deallocate(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure sending request") + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure responding to request") + } + + return +} + +// DeallocatePreparer prepares the Deallocate request. +func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/deallocate", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeallocateSender sends the Deallocate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeallocateResponder handles the response to the Deallocate request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete allows you to delete a virtual machine scale set. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Delete(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get displays information about a virtual machine scale set virtual machine. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Get(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVM, err error) { + req, err := client.GetPreparer(resourceGroupName, vmScaleSetName, instanceID) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineScaleSetVMsClient) GetPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) (result VirtualMachineScaleSetVM, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetInstanceView displays the status of a virtual machine scale set virtual +// machine. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { + req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName, instanceID) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") + } + + resp, err := client.GetInstanceViewSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") + } + + result, err = client.GetInstanceViewResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure responding to request") + } + + return +} + +// GetInstanceViewPreparer prepares the GetInstanceView request. +func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/instanceView", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetInstanceViewSender sends the GetInstanceView request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetInstanceViewResponder handles the response to the GetInstanceView request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *http.Response) (result VirtualMachineScaleSetVMInstanceView, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all virtual machines in a VM scale sets. +// +// resourceGroupName is the name of the resource group. +// virtualMachineScaleSetName is the name of the virtual machine scale set. +// filter is the filter to apply on the operation. selectParameter is the +// list parameters. expand is the expand expression to apply on the +// operation. +func (client VirtualMachineScaleSetVMsClient) List(resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachineScaleSetVMsClient) ListPreparer(resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if len(selectParameter) > 0 { + queryParameters["$select"] = autorest.Encode("query", selectParameter) + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) (result VirtualMachineScaleSetVMListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client VirtualMachineScaleSetVMsClient) ListNextResults(lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, err error) { + req, err := lastResults.VirtualMachineScaleSetVMListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// PowerOff allows you to power off (stop) a virtual machine in a VM scale +// set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) PowerOff(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure sending request") + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure responding to request") + } + + return +} + +// PowerOffPreparer prepares the PowerOff request. +func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/poweroff", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// PowerOffSender sends the PowerOff request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// PowerOffResponder handles the response to the PowerOff request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Reimage allows you to re-image(update the version of the installed +// operating system) a virtual machine scale set instance. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Reimage(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ReimagePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") + } + + resp, err := client.ReimageSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure sending request") + } + + result, err = client.ReimageResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure responding to request") + } + + return +} + +// ReimagePreparer prepares the Reimage request. +func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimage", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ReimageSender sends the Reimage request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) ReimageSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ReimageResponder handles the response to the Reimage request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Restart allows you to restart a virtual machine in a VM scale set. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Restart(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure sending request") + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure responding to request") + } + + return +} + +// RestartPreparer prepares the Restart request. +func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/restart", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RestartSender sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RestartResponder handles the response to the Restart request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start allows you to start a virtual machine in a VM scale set. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. vmScaleSetName is the +// name of the virtual machine scale set. instanceID is the instance id of +// the virtual machine. +func (client VirtualMachineScaleSetVMsClient) Start(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure sending request") + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure responding to request") + } + + return +} + +// StartPreparer prepares the Start request. +func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go new file mode 100644 index 000000000000..39ee07b0b32c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go @@ -0,0 +1,98 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualMachineSizesClient is the the Compute Management Client. +type VirtualMachineSizesClient struct { + ManagementClient +} + +// NewVirtualMachineSizesClient creates an instance of the +// VirtualMachineSizesClient client. +func NewVirtualMachineSizesClient(subscriptionID string) VirtualMachineSizesClient { + return VirtualMachineSizesClient{New(subscriptionID)} +} + +// List lists all available virtual machine sizes for a subscription in a +// location. +// +// location is the location upon which virtual-machine-sizes is queried. +func (client VirtualMachineSizesClient) List(location string) (result VirtualMachineSizeListResult, err error) { + req, err := client.ListPreparer(location) + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachineSizesClient) ListPreparer(location string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/vmSizes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineSizesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachineSizesClient) ListResponder(resp *http.Response) (result VirtualMachineSizeListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go new file mode 100644 index 000000000000..b1a128d7faeb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go @@ -0,0 +1,546 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ApplicationGatewaysClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type ApplicationGatewaysClient struct { + ManagementClient +} + +// NewApplicationGatewaysClient creates an instance of the +// ApplicationGatewaysClient client. +func NewApplicationGatewaysClient(subscriptionID string) ApplicationGatewaysClient { + return ApplicationGatewaysClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put ApplicationGateway operation creates/updates a +// ApplicationGateway This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. applicationGatewayName +// is the name of the ApplicationGateway. parameters is parameters supplied +// to the create/delete ApplicationGateway operation +func (client ApplicationGatewaysClient) CreateOrUpdate(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, applicationGatewayName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationGatewayName": autorest.Encode("path", applicationGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete applicationgateway operation deletes the specified +// applicationgateway. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. applicationGatewayName +// is the name of the applicationgateway. +func (client ApplicationGatewaysClient) Delete(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationGatewayName": autorest.Encode("path", applicationGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get applicationgateway operation retreives information about the +// specified applicationgateway. +// +// resourceGroupName is the name of the resource group. applicationGatewayName +// is the name of the applicationgateway. +func (client ApplicationGatewaysClient) Get(resourceGroupName string, applicationGatewayName string) (result ApplicationGateway, err error) { + req, err := client.GetPreparer(resourceGroupName, applicationGatewayName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationGatewaysClient) GetPreparer(resourceGroupName string, applicationGatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationGatewayName": autorest.Encode("path", applicationGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (result ApplicationGateway, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List ApplicationGateway opertion retrieves all the +// applicationgateways in a resource group. +// +// resourceGroupName is the name of the resource group. +func (client ApplicationGatewaysClient) List(resourceGroupName string) (result ApplicationGatewayListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationGatewaysClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) ListResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { + req, err := lastResults.ApplicationGatewayListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the List applicationgateway opertion retrieves all the +// applicationgateways in a subscription. +func (client ApplicationGatewaysClient) ListAll() (result ApplicationGatewayListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client ApplicationGatewaysClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGateways", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) ListAllResponder(resp *http.Response) (result ApplicationGatewayListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client ApplicationGatewaysClient) ListAllNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { + req, err := lastResults.ApplicationGatewayListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} + +// Start the Start ApplicationGateway operation starts application gatewayin +// the specified resource group through Network resource provider. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. applicationGatewayName +// is the name of the application gateway. +func (client ApplicationGatewaysClient) Start(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure sending request") + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure responding to request") + } + + return +} + +// StartPreparer prepares the Start request. +func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationGatewayName": autorest.Encode("path", applicationGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) StartSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop the STOP ApplicationGateway operation stops application gatewayin the +// specified resource group through Network resource provider. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. applicationGatewayName +// is the name of the application gateway. +func (client ApplicationGatewaysClient) Stop(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StopPreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", nil, "Failure preparing request") + } + + resp, err := client.StopSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure sending request") + } + + result, err = client.StopResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure responding to request") + } + + return +} + +// StopPreparer prepares the Stop request. +func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationGatewayName": autorest.Encode("path", applicationGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) StopSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go new file mode 100644 index 000000000000..04fdf7285e7b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go @@ -0,0 +1,125 @@ +// Package network implements the Azure ARM Network service API version +// 2016-03-30. +// +// The Microsoft Azure Network management API provides a RESTful set of web +// services that interact with Microsoft Azure Networks service to manage +// your network resrources. The API has entities that capture the +// relationship between an end user and the Microsoft Azure Networks service. +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +const ( + // APIVersion is the version of the Network + APIVersion = "2016-03-30" + + // DefaultBaseURI is the default URI used for the service Network + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Network. +type ManagementClient struct { + autorest.Client + BaseURI string + APIVersion string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: DefaultBaseURI, + APIVersion: APIVersion, + SubscriptionID: subscriptionID, + } +} + +// CheckDNSNameAvailability checks whether a domain name in the cloudapp.net +// zone is available for use. +// +// location is the location of the domain name domainNameLabel is the domain +// name to be verified. It must conform to the following regular expression: +// ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. +func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { + req, err := client.CheckDNSNameAvailabilityPreparer(location, domainNameLabel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request") + } + + resp, err := client.CheckDNSNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request") + } + + result, err = client.CheckDNSNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure responding to request") + } + + return +} + +// CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request. +func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string, domainNameLabel string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(domainNameLabel) > 0 { + queryParameters["domainNameLabel"] = autorest.Encode("query", domainNameLabel) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ManagementClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always +// closes the http.Response Body. +func (client ManagementClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go new file mode 100644 index 000000000000..f097126a87c1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go @@ -0,0 +1,337 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ExpressRouteCircuitAuthorizationsClient is the the Microsoft Azure Network +// management API provides a RESTful set of web services that interact with +// Microsoft Azure Networks service to manage your network resrources. The +// API has entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type ExpressRouteCircuitAuthorizationsClient struct { + ManagementClient +} + +// NewExpressRouteCircuitAuthorizationsClient creates an instance of the +// ExpressRouteCircuitAuthorizationsClient client. +func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRouteCircuitAuthorizationsClient { + return ExpressRouteCircuitAuthorizationsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put Authorization operation creates/updates an +// authorization in thespecified ExpressRouteCircuits This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. authorizationName is the name of the +// authorization. authorizationParameters is parameters supplied to the +// create/update ExpressRouteCircuitAuthorization operation +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, authorizationName, authorizationParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationName": autorest.Encode("path", authorizationName), + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), + autorest.WithJSON(authorizationParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete authorization operation deletes the specified +// authorization from the specified ExpressRouteCircuit. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. authorizationName is the name of the +// authorization. +func (client ExpressRouteCircuitAuthorizationsClient) Delete(resourceGroupName string, circuitName string, authorizationName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, authorizationName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGroupName string, circuitName string, authorizationName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationName": autorest.Encode("path", authorizationName), + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the GET authorization operation retrieves the specified authorization +// from the specified ExpressRouteCircuit. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. authorizationName is the name of the +// authorization. +func (client ExpressRouteCircuitAuthorizationsClient) Get(resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) { + req, err := client.GetPreparer(resourceGroupName, circuitName, authorizationName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationName": autorest.Encode("path", authorizationName), + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List authorization operation retrieves all the authorizations in +// an ExpressRouteCircuit. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the curcuit. +func (client ExpressRouteCircuitAuthorizationsClient) List(resourceGroupName string, circuitName string) (result AuthorizationListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, circuitName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(resourceGroupName string, circuitName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/authorizations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.Response) (result AuthorizationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ExpressRouteCircuitAuthorizationsClient) ListNextResults(lastResults AuthorizationListResult) (result AuthorizationListResult, err error) { + req, err := lastResults.AuthorizationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go new file mode 100644 index 000000000000..b78544fa4702 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go @@ -0,0 +1,333 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ExpressRouteCircuitPeeringsClient is the the Microsoft Azure Network +// management API provides a RESTful set of web services that interact with +// Microsoft Azure Networks service to manage your network resrources. The +// API has entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type ExpressRouteCircuitPeeringsClient struct { + ManagementClient +} + +// NewExpressRouteCircuitPeeringsClient creates an instance of the +// ExpressRouteCircuitPeeringsClient client. +func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient { + return ExpressRouteCircuitPeeringsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put Pering operation creates/updates an peering in the +// specified ExpressRouteCircuits This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. peeringName is the name of the peering. +// peeringParameters is parameters supplied to the create/update +// ExpressRouteCircuit Peering operation +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), + autorest.WithJSON(peeringParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete peering operation deletes the specified peering from the +// ExpressRouteCircuit. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. peeringName is the name of the peering. +func (client ExpressRouteCircuitPeeringsClient) Delete(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the GET peering operation retrieves the specified authorization from +// the ExpressRouteCircuit. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route circuit. peeringName is the name of the peering. +func (client ExpressRouteCircuitPeeringsClient) Get(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) { + req, err := client.GetPreparer(resourceGroupName, circuitName, peeringName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ExpressRouteCircuitPeeringsClient) GetPreparer(resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List peering operation retrieves all the peerings in an +// ExpressRouteCircuit. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the curcuit. +func (client ExpressRouteCircuitPeeringsClient) List(resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, circuitName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ExpressRouteCircuitPeeringsClient) ListPreparer(resourceGroupName string, circuitName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) { + req, err := lastResults.ExpressRouteCircuitPeeringListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go new file mode 100644 index 000000000000..fa7bbec254ae --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go @@ -0,0 +1,755 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ExpressRouteCircuitsClient is the the Microsoft Azure Network management +// API provides a RESTful set of web services that interact with Microsoft +// Azure Networks service to manage your network resrources. The API has +// entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type ExpressRouteCircuitsClient struct { + ManagementClient +} + +// NewExpressRouteCircuitsClient creates an instance of the +// ExpressRouteCircuitsClient client. +func NewExpressRouteCircuitsClient(subscriptionID string) ExpressRouteCircuitsClient { + return ExpressRouteCircuitsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put ExpressRouteCircuit operation creates/updates a +// ExpressRouteCircuit This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. parameters is parameters supplied to the +// create/delete ExpressRouteCircuit operation +func (client ExpressRouteCircuitsClient) CreateOrUpdate(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete ExpressRouteCircuit operation deletes the specified +// ExpressRouteCircuit. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the express route Circuit. +func (client ExpressRouteCircuitsClient) Delete(resourceGroupName string, circuitName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string, circuitName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get ExpressRouteCircuit operation retreives information about the +// specified ExpressRouteCircuit. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. +func (client ExpressRouteCircuitsClient) Get(resourceGroupName string, circuitName string) (result ExpressRouteCircuit, err error) { + req, err := client.GetPreparer(resourceGroupName, circuitName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ExpressRouteCircuitsClient) GetPreparer(resourceGroupName string, circuitName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetPeeringStats the Liststats ExpressRouteCircuit opertion retrieves all +// the stats from a ExpressRouteCircuits in a resource group. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. peeringName is the name of the peering. +func (client ExpressRouteCircuitsClient) GetPeeringStats(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitStats, err error) { + req, err := client.GetPeeringStatsPreparer(resourceGroupName, circuitName, peeringName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", nil, "Failure preparing request") + } + + resp, err := client.GetPeeringStatsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request") + } + + result, err = client.GetPeeringStatsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure responding to request") + } + + return +} + +// GetPeeringStatsPreparer prepares the GetPeeringStats request. +func (client ExpressRouteCircuitsClient) GetPeeringStatsPreparer(resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/stats", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetPeeringStatsSender sends the GetPeeringStats request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) GetPeeringStatsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetPeeringStatsResponder handles the response to the GetPeeringStats request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) GetPeeringStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetStats the Liststats ExpressRouteCircuit opertion retrieves all the stats +// from a ExpressRouteCircuits in a resource group. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. +func (client ExpressRouteCircuitsClient) GetStats(resourceGroupName string, circuitName string) (result ExpressRouteCircuitStats, err error) { + req, err := client.GetStatsPreparer(resourceGroupName, circuitName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", nil, "Failure preparing request") + } + + resp, err := client.GetStatsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request") + } + + result, err = client.GetStatsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure responding to request") + } + + return +} + +// GetStatsPreparer prepares the GetStats request. +func (client ExpressRouteCircuitsClient) GetStatsPreparer(resourceGroupName string, circuitName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/stats", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetStatsSender sends the GetStats request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) GetStatsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetStatsResponder handles the response to the GetStats request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) GetStatsResponder(resp *http.Response) (result ExpressRouteCircuitStats, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List ExpressRouteCircuit opertion retrieves all the +// ExpressRouteCircuits in a resource group. +// +// resourceGroupName is the name of the resource group. +func (client ExpressRouteCircuitsClient) List(resourceGroupName string) (result ExpressRouteCircuitListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ExpressRouteCircuitsClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { + req, err := lastResults.ExpressRouteCircuitListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the List ExpressRouteCircuit opertion retrieves all the +// ExpressRouteCircuits in a subscription. +func (client ExpressRouteCircuitsClient) ListAll() (result ExpressRouteCircuitListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client ExpressRouteCircuitsClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCircuits", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) (result ExpressRouteCircuitListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { + req, err := lastResults.ExpressRouteCircuitListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} + +// ListArpTable the ListArpTable from ExpressRouteCircuit opertion retrieves +// the currently advertised arp table associated with the +// ExpressRouteCircuits in a resource group. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. peeringName is the name of the peering. devicePath is +// the path of the device. +func (client ExpressRouteCircuitsClient) ListArpTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ListArpTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") + } + + resp, err := client.ListArpTableSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure sending request") + } + + result, err = client.ListArpTableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure responding to request") + } + + return +} + +// ListArpTablePreparer prepares the ListArpTable request. +func (client ExpressRouteCircuitsClient) ListArpTablePreparer(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "devicePath": autorest.Encode("path", devicePath), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/arpTables/{devicePath}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ListArpTableSender sends the ListArpTable request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ListArpTableResponder handles the response to the ListArpTable request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListRoutesTable the ListRoutesTable from ExpressRouteCircuit opertion +// retrieves the currently advertised routes table associated with the +// ExpressRouteCircuits in a resource group. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. peeringName is the name of the peering. devicePath is +// the path of the device. +func (client ExpressRouteCircuitsClient) ListRoutesTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ListRoutesTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") + } + + resp, err := client.ListRoutesTableSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure sending request") + } + + result, err = client.ListRoutesTableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure responding to request") + } + + return +} + +// ListRoutesTablePreparer prepares the ListRoutesTable request. +func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "devicePath": autorest.Encode("path", devicePath), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTables/{devicePath}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ListRoutesTableSender sends the ListRoutesTable request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListRoutesTableSummary the ListRoutesTable from ExpressRouteCircuit +// opertion retrieves the currently advertised routes table associated with +// the ExpressRouteCircuits in a resource group. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. circuitName is the +// name of the circuit. peeringName is the name of the peering. devicePath is +// the path of the device. +func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ListRoutesTableSummaryPreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request") + } + + resp, err := client.ListRoutesTableSummarySender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure sending request") + } + + result, err = client.ListRoutesTableSummaryResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure responding to request") + } + + return +} + +// ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. +func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryPreparer(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "circuitName": autorest.Encode("path", circuitName), + "devicePath": autorest.Encode("path", devicePath), + "peeringName": autorest.Encode("path", peeringName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}/routeTablesSummary/{devicePath}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ListRoutesTableSummarySender sends the ListRoutesTableSummary request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteCircuitsClient) ListRoutesTableSummarySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always +// closes the http.Response Body. +func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go new file mode 100644 index 000000000000..2f1452600bd0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go @@ -0,0 +1,123 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ExpressRouteServiceProvidersClient is the the Microsoft Azure Network +// management API provides a RESTful set of web services that interact with +// Microsoft Azure Networks service to manage your network resrources. The +// API has entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type ExpressRouteServiceProvidersClient struct { + ManagementClient +} + +// NewExpressRouteServiceProvidersClient creates an instance of the +// ExpressRouteServiceProvidersClient client. +func NewExpressRouteServiceProvidersClient(subscriptionID string) ExpressRouteServiceProvidersClient { + return ExpressRouteServiceProvidersClient{New(subscriptionID)} +} + +// List the List ExpressRouteServiceProvider opertion retrieves all the +// available ExpressRouteServiceProviders. +func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ExpressRouteServiceProvidersClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ExpressRouteServiceProvidersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Response) (result ExpressRouteServiceProviderListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ExpressRouteServiceProvidersClient) ListNextResults(lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, err error) { + req, err := lastResults.ExpressRouteServiceProviderListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go new file mode 100644 index 000000000000..59f3b6c34345 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go @@ -0,0 +1,665 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// InterfacesClient is the the Microsoft Azure Network management API provides +// a RESTful set of web services that interact with Microsoft Azure Networks +// service to manage your network resrources. The API has entities that +// capture the relationship between an end user and the Microsoft Azure +// Networks service. +type InterfacesClient struct { + ManagementClient +} + +// NewInterfacesClient creates an instance of the InterfacesClient client. +func NewInterfacesClient(subscriptionID string) InterfacesClient { + return InterfacesClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put NetworkInterface operation creates/updates a +// networkInterface This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. networkInterfaceName +// is the name of the network interface. parameters is parameters supplied to +// the create/update NetworkInterface operation +func (client InterfacesClient) CreateOrUpdate(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkInterfaceName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkInterfaceName": autorest.Encode("path", networkInterfaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete netwokInterface operation deletes the specified +// netwokInterface. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. networkInterfaceName +// is the name of the network interface. +func (client InterfacesClient) Delete(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkInterfaceName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkInterfaceName": autorest.Encode("path", networkInterfaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client InterfacesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get ntework interface operation retreives information about the +// specified network interface. +// +// resourceGroupName is the name of the resource group. networkInterfaceName +// is the name of the network interface. expand is expand references +// resources. +func (client InterfacesClient) Get(resourceGroupName string, networkInterfaceName string, expand string) (result Interface, err error) { + req, err := client.GetPreparer(resourceGroupName, networkInterfaceName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client InterfacesClient) GetPreparer(resourceGroupName string, networkInterfaceName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkInterfaceName": autorest.Encode("path", networkInterfaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client InterfacesClient) GetResponder(resp *http.Response) (result Interface, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetVirtualMachineScaleSetNetworkInterface the Get ntework interface +// operation retreives information about the specified network interface in a +// virtual machine scale set. +// +// resourceGroupName is the name of the resource group. +// virtualMachineScaleSetName is the name of the virtual machine scale set. +// virtualmachineIndex is the virtual machine index. networkInterfaceName is +// the name of the network interface. expand is expand references resources. +func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result Interface, err error) { + req, err := client.GetVirtualMachineScaleSetNetworkInterfacePreparer(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", nil, "Failure preparing request") + } + + resp, err := client.GetVirtualMachineScaleSetNetworkInterfaceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") + } + + result, err = client.GetVirtualMachineScaleSetNetworkInterfaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure responding to request") + } + + return +} + +// GetVirtualMachineScaleSetNetworkInterfacePreparer prepares the GetVirtualMachineScaleSetNetworkInterface request. +func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkInterfaceName": autorest.Encode("path", networkInterfaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), + "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetVirtualMachineScaleSetNetworkInterfaceSender sends the GetVirtualMachineScaleSetNetworkInterface request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetVirtualMachineScaleSetNetworkInterfaceResponder handles the response to the GetVirtualMachineScaleSetNetworkInterface request. The method always +// closes the http.Response Body. +func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponder(resp *http.Response) (result Interface, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List networkInterfaces opertion retrieves all the +// networkInterfaces in a resource group. +// +// resourceGroupName is the name of the resource group. +func (client InterfacesClient) List(resourceGroupName string) (result InterfaceListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client InterfacesClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client InterfacesClient) ListResponder(resp *http.Response) (result InterfaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { + req, err := lastResults.InterfaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the List networkInterfaces opertion retrieves all the +// networkInterfaces in a subscription. +func (client InterfacesClient) ListAll() (result InterfaceListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client InterfacesClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkInterfaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client InterfacesClient) ListAllResponder(resp *http.Response) (result InterfaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { + req, err := lastResults.InterfaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} + +// ListVirtualMachineScaleSetNetworkInterfaces the list network interface +// operation retrieves information about all network interfaces in a virtual +// machine scale set. +// +// resourceGroupName is the name of the resource group. +// virtualMachineScaleSetName is the name of the virtual machine scale set. +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResult, err error) { + req, err := client.ListVirtualMachineScaleSetNetworkInterfacesPreparer(resourceGroupName, virtualMachineScaleSetName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") + } + + resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") + } + + result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to request") + } + + return +} + +// ListVirtualMachineScaleSetNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetNetworkInterfaces request. +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPreparer(resourceGroupName string, virtualMachineScaleSetName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/networkInterfaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListVirtualMachineScaleSetNetworkInterfacesSender sends the ListVirtualMachineScaleSetNetworkInterfaces request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListVirtualMachineScaleSetNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetNetworkInterfaces request. The method always +// closes the http.Response Body. +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListVirtualMachineScaleSetNetworkInterfacesNextResults retrieves the next set of results, if any. +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { + req, err := lastResults.InterfaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending next results request request") + } + + result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to next results request request") + } + + return +} + +// ListVirtualMachineScaleSetVMNetworkInterfaces the list network interface +// operation retrieves information about all network interfaces in a virtual +// machine from a virtual machine scale set. +// +// resourceGroupName is the name of the resource group. +// virtualMachineScaleSetName is the name of the virtual machine scale set. +// virtualmachineIndex is the virtual machine index. +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResult, err error) { + req, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing request") + } + + resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") + } + + result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to request") + } + + return +} + +// ListVirtualMachineScaleSetVMNetworkInterfacesPreparer prepares the ListVirtualMachineScaleSetVMNetworkInterfaces request. +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualmachineIndex": autorest.Encode("path", virtualmachineIndex), + "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListVirtualMachineScaleSetVMNetworkInterfacesSender sends the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method will close the +// http.Response Body if it receives an error. +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListVirtualMachineScaleSetVMNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method always +// closes the http.Response Body. +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp *http.Response) (result InterfaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListVirtualMachineScaleSetVMNetworkInterfacesNextResults retrieves the next set of results, if any. +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { + req, err := lastResults.InterfaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending next results request request") + } + + result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go new file mode 100644 index 000000000000..92fc83b885b5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go @@ -0,0 +1,413 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// LoadBalancersClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type LoadBalancersClient struct { + ManagementClient +} + +// NewLoadBalancersClient creates an instance of the LoadBalancersClient +// client. +func NewLoadBalancersClient(subscriptionID string) LoadBalancersClient { + return LoadBalancersClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put LoadBalancer operation creates/updates a +// LoadBalancer This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. loadBalancerName is +// the name of the loadBalancer. parameters is parameters supplied to the +// create/delete LoadBalancer operation +func (client LoadBalancersClient) CreateOrUpdate(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, loadBalancerName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "loadBalancerName": autorest.Encode("path", loadBalancerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete loadbalancer operation deletes the specified +// loadbalancer. This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. loadBalancerName is +// the name of the loadBalancer. +func (client LoadBalancersClient) Delete(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, loadBalancerName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "loadBalancerName": autorest.Encode("path", loadBalancerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancersClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get ntework interface operation retreives information about the +// specified network interface. +// +// resourceGroupName is the name of the resource group. loadBalancerName is +// the name of the loadBalancer. expand is expand references resources. +func (client LoadBalancersClient) Get(resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) { + req, err := client.GetPreparer(resourceGroupName, loadBalancerName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client LoadBalancersClient) GetPreparer(resourceGroupName string, loadBalancerName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "loadBalancerName": autorest.Encode("path", loadBalancerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client LoadBalancersClient) GetResponder(resp *http.Response) (result LoadBalancer, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List loadBalancer opertion retrieves all the loadbalancers in a +// resource group. +// +// resourceGroupName is the name of the resource group. +func (client LoadBalancersClient) List(resourceGroupName string) (result LoadBalancerListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client LoadBalancersClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client LoadBalancersClient) ListResponder(resp *http.Response) (result LoadBalancerListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { + req, err := lastResults.LoadBalancerListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the List loadBalancer opertion retrieves all the loadbalancers in a +// subscription. +func (client LoadBalancersClient) ListAll() (result LoadBalancerListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client LoadBalancersClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result LoadBalancerListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client LoadBalancersClient) ListAllNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { + req, err := lastResults.LoadBalancerListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go new file mode 100644 index 000000000000..498cb416c2d9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go @@ -0,0 +1,330 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// LocalNetworkGatewaysClient is the the Microsoft Azure Network management +// API provides a RESTful set of web services that interact with Microsoft +// Azure Networks service to manage your network resrources. The API has +// entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type LocalNetworkGatewaysClient struct { + ManagementClient +} + +// NewLocalNetworkGatewaysClient creates an instance of the +// LocalNetworkGatewaysClient client. +func NewLocalNetworkGatewaysClient(subscriptionID string) LocalNetworkGatewaysClient { + return LocalNetworkGatewaysClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put LocalNetworkGateway operation creates/updates a +// local network gateway in the specified resource group through Network +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// localNetworkGatewayName is the name of the local network gateway. +// parameters is parameters supplied to the Begin Create or update Local +// Network Gateway operation through Network resource provider. +func (client LocalNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, localNetworkGatewayName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client LocalNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete LocalNetworkGateway operation deletes the specifed local +// network Gateway through Network resource provider. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. +// localNetworkGatewayName is the name of the local network gateway. +func (client LocalNetworkGatewaysClient) Delete(resourceGroupName string, localNetworkGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, localNetworkGatewayName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string, localNetworkGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client LocalNetworkGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get LocalNetworkGateway operation retrieves information about the +// specified local network gateway through Network resource provider. +// +// resourceGroupName is the name of the resource group. +// localNetworkGatewayName is the name of the local network gateway. +func (client LocalNetworkGatewaysClient) Get(resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGateway, err error) { + req, err := client.GetPreparer(resourceGroupName, localNetworkGatewayName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client LocalNetworkGatewaysClient) GetPreparer(resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "localNetworkGatewayName": autorest.Encode("path", localNetworkGatewayName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client LocalNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (result LocalNetworkGateway, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List LocalNetworkGateways opertion retrieves all the local network +// gateways stored. +// +// resourceGroupName is the name of the resource group. +func (client LocalNetworkGatewaysClient) List(resourceGroupName string) (result LocalNetworkGatewayListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client LocalNetworkGatewaysClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client LocalNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client LocalNetworkGatewaysClient) ListResponder(resp *http.Response) (result LocalNetworkGatewayListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client LocalNetworkGatewaysClient) ListNextResults(lastResults LocalNetworkGatewayListResult) (result LocalNetworkGatewayListResult, err error) { + req, err := lastResults.LocalNetworkGatewayListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go new file mode 100644 index 000000000000..79bfafc3aafe --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go @@ -0,0 +1,1853 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// ApplicationGatewayCookieBasedAffinity enumerates the values for application +// gateway cookie based affinity. +type ApplicationGatewayCookieBasedAffinity string + +const ( + // Disabled specifies the disabled state for application gateway cookie + // based affinity. + Disabled ApplicationGatewayCookieBasedAffinity = "Disabled" + // Enabled specifies the enabled state for application gateway cookie + // based affinity. + Enabled ApplicationGatewayCookieBasedAffinity = "Enabled" +) + +// ApplicationGatewayOperationalState enumerates the values for application +// gateway operational state. +type ApplicationGatewayOperationalState string + +const ( + // Running specifies the running state for application gateway operational + // state. + Running ApplicationGatewayOperationalState = "Running" + // Starting specifies the starting state for application gateway + // operational state. + Starting ApplicationGatewayOperationalState = "Starting" + // Stopped specifies the stopped state for application gateway operational + // state. + Stopped ApplicationGatewayOperationalState = "Stopped" + // Stopping specifies the stopping state for application gateway + // operational state. + Stopping ApplicationGatewayOperationalState = "Stopping" +) + +// ApplicationGatewayProtocol enumerates the values for application gateway +// protocol. +type ApplicationGatewayProtocol string + +const ( + // HTTP specifies the http state for application gateway protocol. + HTTP ApplicationGatewayProtocol = "Http" + // HTTPS specifies the https state for application gateway protocol. + HTTPS ApplicationGatewayProtocol = "Https" +) + +// ApplicationGatewayRequestRoutingRuleType enumerates the values for +// application gateway request routing rule type. +type ApplicationGatewayRequestRoutingRuleType string + +const ( + // Basic specifies the basic state for application gateway request routing + // rule type. + Basic ApplicationGatewayRequestRoutingRuleType = "Basic" + // PathBasedRouting specifies the path based routing state for application + // gateway request routing rule type. + PathBasedRouting ApplicationGatewayRequestRoutingRuleType = "PathBasedRouting" +) + +// ApplicationGatewaySkuName enumerates the values for application gateway sku +// name. +type ApplicationGatewaySkuName string + +const ( + // StandardLarge specifies the standard large state for application + // gateway sku name. + StandardLarge ApplicationGatewaySkuName = "Standard_Large" + // StandardMedium specifies the standard medium state for application + // gateway sku name. + StandardMedium ApplicationGatewaySkuName = "Standard_Medium" + // StandardSmall specifies the standard small state for application + // gateway sku name. + StandardSmall ApplicationGatewaySkuName = "Standard_Small" +) + +// ApplicationGatewayTier enumerates the values for application gateway tier. +type ApplicationGatewayTier string + +const ( + // Standard specifies the standard state for application gateway tier. + Standard ApplicationGatewayTier = "Standard" +) + +// AuthorizationUseStatus enumerates the values for authorization use status. +type AuthorizationUseStatus string + +const ( + // Available specifies the available state for authorization use status. + Available AuthorizationUseStatus = "Available" + // InUse specifies the in use state for authorization use status. + InUse AuthorizationUseStatus = "InUse" +) + +// ExpressRouteCircuitPeeringAdvertisedPublicPrefixState enumerates the values +// for express route circuit peering advertised public prefix state. +type ExpressRouteCircuitPeeringAdvertisedPublicPrefixState string + +const ( + // Configured specifies the configured state for express route circuit + // peering advertised public prefix state. + Configured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configured" + // Configuring specifies the configuring state for express route circuit + // peering advertised public prefix state. + Configuring ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "Configuring" + // NotConfigured specifies the not configured state for express route + // circuit peering advertised public prefix state. + NotConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "NotConfigured" + // ValidationNeeded specifies the validation needed state for express + // route circuit peering advertised public prefix state. + ValidationNeeded ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "ValidationNeeded" +) + +// ExpressRouteCircuitPeeringState enumerates the values for express route +// circuit peering state. +type ExpressRouteCircuitPeeringState string + +const ( + // ExpressRouteCircuitPeeringStateDisabled specifies the express route + // circuit peering state disabled state for express route circuit peering + // state. + ExpressRouteCircuitPeeringStateDisabled ExpressRouteCircuitPeeringState = "Disabled" + // ExpressRouteCircuitPeeringStateEnabled specifies the express route + // circuit peering state enabled state for express route circuit peering + // state. + ExpressRouteCircuitPeeringStateEnabled ExpressRouteCircuitPeeringState = "Enabled" +) + +// ExpressRouteCircuitPeeringType enumerates the values for express route +// circuit peering type. +type ExpressRouteCircuitPeeringType string + +const ( + // AzurePrivatePeering specifies the azure private peering state for + // express route circuit peering type. + AzurePrivatePeering ExpressRouteCircuitPeeringType = "AzurePrivatePeering" + // AzurePublicPeering specifies the azure public peering state for express + // route circuit peering type. + AzurePublicPeering ExpressRouteCircuitPeeringType = "AzurePublicPeering" + // MicrosoftPeering specifies the microsoft peering state for express + // route circuit peering type. + MicrosoftPeering ExpressRouteCircuitPeeringType = "MicrosoftPeering" +) + +// ExpressRouteCircuitSkuFamily enumerates the values for express route +// circuit sku family. +type ExpressRouteCircuitSkuFamily string + +const ( + // MeteredData specifies the metered data state for express route circuit + // sku family. + MeteredData ExpressRouteCircuitSkuFamily = "MeteredData" + // UnlimitedData specifies the unlimited data state for express route + // circuit sku family. + UnlimitedData ExpressRouteCircuitSkuFamily = "UnlimitedData" +) + +// ExpressRouteCircuitSkuTier enumerates the values for express route circuit +// sku tier. +type ExpressRouteCircuitSkuTier string + +const ( + // ExpressRouteCircuitSkuTierPremium specifies the express route circuit + // sku tier premium state for express route circuit sku tier. + ExpressRouteCircuitSkuTierPremium ExpressRouteCircuitSkuTier = "Premium" + // ExpressRouteCircuitSkuTierStandard specifies the express route circuit + // sku tier standard state for express route circuit sku tier. + ExpressRouteCircuitSkuTierStandard ExpressRouteCircuitSkuTier = "Standard" +) + +// IPAllocationMethod enumerates the values for ip allocation method. +type IPAllocationMethod string + +const ( + // Dynamic specifies the dynamic state for ip allocation method. + Dynamic IPAllocationMethod = "Dynamic" + // Static specifies the static state for ip allocation method. + Static IPAllocationMethod = "Static" +) + +// IPVersion enumerates the values for ip version. +type IPVersion string + +const ( + // IPv4 specifies the i pv 4 state for ip version. + IPv4 IPVersion = "IPv4" + // IPv6 specifies the i pv 6 state for ip version. + IPv6 IPVersion = "IPv6" +) + +// LoadDistribution enumerates the values for load distribution. +type LoadDistribution string + +const ( + // Default specifies the default state for load distribution. + Default LoadDistribution = "Default" + // SourceIP specifies the source ip state for load distribution. + SourceIP LoadDistribution = "SourceIP" + // SourceIPProtocol specifies the source ip protocol state for load + // distribution. + SourceIPProtocol LoadDistribution = "SourceIPProtocol" +) + +// OperationStatus enumerates the values for operation status. +type OperationStatus string + +const ( + // Failed specifies the failed state for operation status. + Failed OperationStatus = "Failed" + // InProgress specifies the in progress state for operation status. + InProgress OperationStatus = "InProgress" + // Succeeded specifies the succeeded state for operation status. + Succeeded OperationStatus = "Succeeded" +) + +// ProbeProtocol enumerates the values for probe protocol. +type ProbeProtocol string + +const ( + // ProbeProtocolHTTP specifies the probe protocol http state for probe + // protocol. + ProbeProtocolHTTP ProbeProtocol = "Http" + // ProbeProtocolTCP specifies the probe protocol tcp state for probe + // protocol. + ProbeProtocolTCP ProbeProtocol = "Tcp" +) + +// ProcessorArchitecture enumerates the values for processor architecture. +type ProcessorArchitecture string + +const ( + // Amd64 specifies the amd 64 state for processor architecture. + Amd64 ProcessorArchitecture = "Amd64" + // X86 specifies the x86 state for processor architecture. + X86 ProcessorArchitecture = "X86" +) + +// RouteNextHopType enumerates the values for route next hop type. +type RouteNextHopType string + +const ( + // RouteNextHopTypeInternet specifies the route next hop type internet + // state for route next hop type. + RouteNextHopTypeInternet RouteNextHopType = "Internet" + // RouteNextHopTypeNone specifies the route next hop type none state for + // route next hop type. + RouteNextHopTypeNone RouteNextHopType = "None" + // RouteNextHopTypeVirtualAppliance specifies the route next hop type + // virtual appliance state for route next hop type. + RouteNextHopTypeVirtualAppliance RouteNextHopType = "VirtualAppliance" + // RouteNextHopTypeVirtualNetworkGateway specifies the route next hop type + // virtual network gateway state for route next hop type. + RouteNextHopTypeVirtualNetworkGateway RouteNextHopType = "VirtualNetworkGateway" + // RouteNextHopTypeVnetLocal specifies the route next hop type vnet local + // state for route next hop type. + RouteNextHopTypeVnetLocal RouteNextHopType = "VnetLocal" +) + +// SecurityRuleAccess enumerates the values for security rule access. +type SecurityRuleAccess string + +const ( + // Allow specifies the allow state for security rule access. + Allow SecurityRuleAccess = "Allow" + // Deny specifies the deny state for security rule access. + Deny SecurityRuleAccess = "Deny" +) + +// SecurityRuleDirection enumerates the values for security rule direction. +type SecurityRuleDirection string + +const ( + // Inbound specifies the inbound state for security rule direction. + Inbound SecurityRuleDirection = "Inbound" + // Outbound specifies the outbound state for security rule direction. + Outbound SecurityRuleDirection = "Outbound" +) + +// SecurityRuleProtocol enumerates the values for security rule protocol. +type SecurityRuleProtocol string + +const ( + // Asterisk specifies the asterisk state for security rule protocol. + Asterisk SecurityRuleProtocol = "*" + // TCP specifies the tcp state for security rule protocol. + TCP SecurityRuleProtocol = "Tcp" + // UDP specifies the udp state for security rule protocol. + UDP SecurityRuleProtocol = "Udp" +) + +// ServiceProviderProvisioningState enumerates the values for service provider +// provisioning state. +type ServiceProviderProvisioningState string + +const ( + // Deprovisioning specifies the deprovisioning state for service provider + // provisioning state. + Deprovisioning ServiceProviderProvisioningState = "Deprovisioning" + // NotProvisioned specifies the not provisioned state for service provider + // provisioning state. + NotProvisioned ServiceProviderProvisioningState = "NotProvisioned" + // Provisioned specifies the provisioned state for service provider + // provisioning state. + Provisioned ServiceProviderProvisioningState = "Provisioned" + // Provisioning specifies the provisioning state for service provider + // provisioning state. + Provisioning ServiceProviderProvisioningState = "Provisioning" +) + +// TransportProtocol enumerates the values for transport protocol. +type TransportProtocol string + +const ( + // TransportProtocolTCP specifies the transport protocol tcp state for + // transport protocol. + TransportProtocolTCP TransportProtocol = "Tcp" + // TransportProtocolUDP specifies the transport protocol udp state for + // transport protocol. + TransportProtocolUDP TransportProtocol = "Udp" +) + +// VirtualNetworkGatewayConnectionStatus enumerates the values for virtual +// network gateway connection status. +type VirtualNetworkGatewayConnectionStatus string + +const ( + // Connected specifies the connected state for virtual network gateway + // connection status. + Connected VirtualNetworkGatewayConnectionStatus = "Connected" + // Connecting specifies the connecting state for virtual network gateway + // connection status. + Connecting VirtualNetworkGatewayConnectionStatus = "Connecting" + // NotConnected specifies the not connected state for virtual network + // gateway connection status. + NotConnected VirtualNetworkGatewayConnectionStatus = "NotConnected" + // Unknown specifies the unknown state for virtual network gateway + // connection status. + Unknown VirtualNetworkGatewayConnectionStatus = "Unknown" +) + +// VirtualNetworkGatewayConnectionType enumerates the values for virtual +// network gateway connection type. +type VirtualNetworkGatewayConnectionType string + +const ( + // ExpressRoute specifies the express route state for virtual network + // gateway connection type. + ExpressRoute VirtualNetworkGatewayConnectionType = "ExpressRoute" + // IPsec specifies the i psec state for virtual network gateway connection + // type. + IPsec VirtualNetworkGatewayConnectionType = "IPsec" + // Vnet2Vnet specifies the vnet 2 vnet state for virtual network gateway + // connection type. + Vnet2Vnet VirtualNetworkGatewayConnectionType = "Vnet2Vnet" + // VPNClient specifies the vpn client state for virtual network gateway + // connection type. + VPNClient VirtualNetworkGatewayConnectionType = "VPNClient" +) + +// VirtualNetworkGatewaySkuName enumerates the values for virtual network +// gateway sku name. +type VirtualNetworkGatewaySkuName string + +const ( + // VirtualNetworkGatewaySkuNameBasic specifies the virtual network gateway + // sku name basic state for virtual network gateway sku name. + VirtualNetworkGatewaySkuNameBasic VirtualNetworkGatewaySkuName = "Basic" + // VirtualNetworkGatewaySkuNameHighPerformance specifies the virtual + // network gateway sku name high performance state for virtual network + // gateway sku name. + VirtualNetworkGatewaySkuNameHighPerformance VirtualNetworkGatewaySkuName = "HighPerformance" + // VirtualNetworkGatewaySkuNameStandard specifies the virtual network + // gateway sku name standard state for virtual network gateway sku name. + VirtualNetworkGatewaySkuNameStandard VirtualNetworkGatewaySkuName = "Standard" +) + +// VirtualNetworkGatewaySkuTier enumerates the values for virtual network +// gateway sku tier. +type VirtualNetworkGatewaySkuTier string + +const ( + // VirtualNetworkGatewaySkuTierBasic specifies the virtual network gateway + // sku tier basic state for virtual network gateway sku tier. + VirtualNetworkGatewaySkuTierBasic VirtualNetworkGatewaySkuTier = "Basic" + // VirtualNetworkGatewaySkuTierHighPerformance specifies the virtual + // network gateway sku tier high performance state for virtual network + // gateway sku tier. + VirtualNetworkGatewaySkuTierHighPerformance VirtualNetworkGatewaySkuTier = "HighPerformance" + // VirtualNetworkGatewaySkuTierStandard specifies the virtual network + // gateway sku tier standard state for virtual network gateway sku tier. + VirtualNetworkGatewaySkuTierStandard VirtualNetworkGatewaySkuTier = "Standard" +) + +// VirtualNetworkGatewayType enumerates the values for virtual network gateway +// type. +type VirtualNetworkGatewayType string + +const ( + // VirtualNetworkGatewayTypeExpressRoute specifies the virtual network + // gateway type express route state for virtual network gateway type. + VirtualNetworkGatewayTypeExpressRoute VirtualNetworkGatewayType = "ExpressRoute" + // VirtualNetworkGatewayTypeVpn specifies the virtual network gateway type + // vpn state for virtual network gateway type. + VirtualNetworkGatewayTypeVpn VirtualNetworkGatewayType = "Vpn" +) + +// VpnType enumerates the values for vpn type. +type VpnType string + +const ( + // PolicyBased specifies the policy based state for vpn type. + PolicyBased VpnType = "PolicyBased" + // RouteBased specifies the route based state for vpn type. + RouteBased VpnType = "RouteBased" +) + +// AddressSpace is addressSpace contains an array of IP address ranges that +// can be used by subnets +type AddressSpace struct { + AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` +} + +// ApplicationGateway is applicationGateways resource +type ApplicationGateway struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *ApplicationGatewayPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayBackendAddress is backend Address of application gateway +type ApplicationGatewayBackendAddress struct { + Fqdn *string `json:"fqdn,omitempty"` + IPAddress *string `json:"ipAddress,omitempty"` +} + +// ApplicationGatewayBackendAddressPool is backend Address Pool of application +// gateway +type ApplicationGatewayBackendAddressPool struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayBackendAddressPoolPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayBackendAddressPoolPropertiesFormat is properties of +// Backend Address Pool of application gateway +type ApplicationGatewayBackendAddressPoolPropertiesFormat struct { + BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` + BackendAddresses *[]ApplicationGatewayBackendAddress `json:"backendAddresses,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayBackendHTTPSettings is backend address pool settings of +// application gateway +type ApplicationGatewayBackendHTTPSettings struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayBackendHTTPSettingsPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayBackendHTTPSettingsPropertiesFormat is properties of +// Backend address pool settings of application gateway +type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { + Port *int32 `json:"port,omitempty"` + Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` + CookieBasedAffinity ApplicationGatewayCookieBasedAffinity `json:"cookieBasedAffinity,omitempty"` + RequestTimeout *int32 `json:"requestTimeout,omitempty"` + Probe *SubResource `json:"probe,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayFrontendIPConfiguration is frontend IP configuration of +// application gateway +type ApplicationGatewayFrontendIPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayFrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayFrontendIPConfigurationPropertiesFormat is properties of +// Frontend IP configuration of application gateway +type ApplicationGatewayFrontendIPConfigurationPropertiesFormat struct { + PrivateIPAddress *string `json:"privateIPAddress,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` + Subnet *SubResource `json:"subnet,omitempty"` + PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayFrontendPort is frontend Port of application gateway +type ApplicationGatewayFrontendPort struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayFrontendPortPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayFrontendPortPropertiesFormat is properties of Frontend +// Port of application gateway +type ApplicationGatewayFrontendPortPropertiesFormat struct { + Port *int32 `json:"port,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayHTTPListener is http listener of application gateway +type ApplicationGatewayHTTPListener struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayHTTPListenerPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayHTTPListenerPropertiesFormat is properties of Http +// listener of application gateway +type ApplicationGatewayHTTPListenerPropertiesFormat struct { + FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` + FrontendPort *SubResource `json:"frontendPort,omitempty"` + Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` + HostName *string `json:"hostName,omitempty"` + SslCertificate *SubResource `json:"sslCertificate,omitempty"` + RequireServerNameIndication *bool `json:"requireServerNameIndication,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayIPConfiguration is iP configuration of application gateway +type ApplicationGatewayIPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayIPConfigurationPropertiesFormat is properties of IP +// configuration of application gateway +type ApplicationGatewayIPConfigurationPropertiesFormat struct { + Subnet *SubResource `json:"subnet,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayListResult is response for ListLoadBalancers Api service +// call +type ApplicationGatewayListResult struct { + autorest.Response `json:"-"` + Value *[]ApplicationGateway `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ApplicationGatewayListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ApplicationGatewayListResult) ApplicationGatewayListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ApplicationGatewayPathRule is path rule of URL path map of application +// gateway +type ApplicationGatewayPathRule struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayPathRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayPathRulePropertiesFormat is properties of probe of +// application gateway +type ApplicationGatewayPathRulePropertiesFormat struct { + Paths *[]string `json:"paths,omitempty"` + BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` + BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayProbe is probe of application gateway +type ApplicationGatewayProbe struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayProbePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayProbePropertiesFormat is properties of probe of +// application gateway +type ApplicationGatewayProbePropertiesFormat struct { + Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` + Host *string `json:"host,omitempty"` + Path *string `json:"path,omitempty"` + Interval *int32 `json:"interval,omitempty"` + Timeout *int32 `json:"timeout,omitempty"` + UnhealthyThreshold *int32 `json:"unhealthyThreshold,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayPropertiesFormat is properties of Application Gateway +type ApplicationGatewayPropertiesFormat struct { + Sku *ApplicationGatewaySku `json:"sku,omitempty"` + OperationalState ApplicationGatewayOperationalState `json:"operationalState,omitempty"` + GatewayIPConfigurations *[]ApplicationGatewayIPConfiguration `json:"gatewayIPConfigurations,omitempty"` + SslCertificates *[]ApplicationGatewaySslCertificate `json:"sslCertificates,omitempty"` + FrontendIPConfigurations *[]ApplicationGatewayFrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` + FrontendPorts *[]ApplicationGatewayFrontendPort `json:"frontendPorts,omitempty"` + Probes *[]ApplicationGatewayProbe `json:"probes,omitempty"` + BackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"backendAddressPools,omitempty"` + BackendHTTPSettingsCollection *[]ApplicationGatewayBackendHTTPSettings `json:"backendHttpSettingsCollection,omitempty"` + HTTPListeners *[]ApplicationGatewayHTTPListener `json:"httpListeners,omitempty"` + URLPathMaps *[]ApplicationGatewayURLPathMap `json:"urlPathMaps,omitempty"` + RequestRoutingRules *[]ApplicationGatewayRequestRoutingRule `json:"requestRoutingRules,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayRequestRoutingRule is request routing rule of application +// gateway +type ApplicationGatewayRequestRoutingRule struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayRequestRoutingRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayRequestRoutingRulePropertiesFormat is properties of +// Request routing rule of application gateway +type ApplicationGatewayRequestRoutingRulePropertiesFormat struct { + RuleType ApplicationGatewayRequestRoutingRuleType `json:"ruleType,omitempty"` + BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` + BackendHTTPSettings *SubResource `json:"backendHttpSettings,omitempty"` + HTTPListener *SubResource `json:"httpListener,omitempty"` + URLPathMap *SubResource `json:"urlPathMap,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewaySku is sKU of application gateway +type ApplicationGatewaySku struct { + Name ApplicationGatewaySkuName `json:"name,omitempty"` + Tier ApplicationGatewayTier `json:"tier,omitempty"` + Capacity *int32 `json:"capacity,omitempty"` +} + +// ApplicationGatewaySslCertificate is sSL certificates of application gateway +type ApplicationGatewaySslCertificate struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewaySslCertificatePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewaySslCertificatePropertiesFormat is properties of SSL +// certificates of application gateway +type ApplicationGatewaySslCertificatePropertiesFormat struct { + Data *string `json:"data,omitempty"` + Password *string `json:"password,omitempty"` + PublicCertData *string `json:"publicCertData,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationGatewayURLPathMap is urlPathMap of application gateway +type ApplicationGatewayURLPathMap struct { + ID *string `json:"id,omitempty"` + Properties *ApplicationGatewayURLPathMapPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ApplicationGatewayURLPathMapPropertiesFormat is properties of probe of +// application gateway +type ApplicationGatewayURLPathMapPropertiesFormat struct { + DefaultBackendAddressPool *SubResource `json:"defaultBackendAddressPool,omitempty"` + DefaultBackendHTTPSettings *SubResource `json:"defaultBackendHttpSettings,omitempty"` + PathRules *[]ApplicationGatewayPathRule `json:"pathRules,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// AuthorizationListResult is response for ListAuthorizations Api service +// callRetrieves all authorizations that belongs to an ExpressRouteCircuit +type AuthorizationListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuitAuthorization `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// AuthorizationListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client AuthorizationListResult) AuthorizationListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// AuthorizationPropertiesFormat is +type AuthorizationPropertiesFormat struct { + AuthorizationKey *string `json:"authorizationKey,omitempty"` + AuthorizationUseStatus AuthorizationUseStatus `json:"authorizationUseStatus,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// AzureAsyncOperationResult is the response body contains the status of the +// specified asynchronous operation, indicating whether it has succeeded, is +// inprogress, or has failed. Note that this status is distinct from the HTTP +// status code returned for the Get Operation Status operation itself. If the +// asynchronous operation succeeded, the response body includes the HTTP +// status code for the successful request. If the asynchronous operation +// failed, the response body includes the HTTP status code for the failed +// request and error information regarding the failure. +type AzureAsyncOperationResult struct { + Status OperationStatus `json:"status,omitempty"` + Error *Error `json:"error,omitempty"` +} + +// BackendAddressPool is pool of backend IP addresseses +type BackendAddressPool struct { + ID *string `json:"id,omitempty"` + Properties *BackendAddressPoolPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// BackendAddressPoolPropertiesFormat is properties of BackendAddressPool +type BackendAddressPoolPropertiesFormat struct { + BackendIPConfigurations *[]InterfaceIPConfiguration `json:"backendIPConfigurations,omitempty"` + LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` + OutboundNatRule *SubResource `json:"outboundNatRule,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// BgpSettings is +type BgpSettings struct { + Asn *int64 `json:"asn,omitempty"` + BgpPeeringAddress *string `json:"bgpPeeringAddress,omitempty"` + PeerWeight *int32 `json:"peerWeight,omitempty"` +} + +// ConnectionResetSharedKey is +type ConnectionResetSharedKey struct { + autorest.Response `json:"-"` + KeyLength *int64 `json:"keyLength,omitempty"` +} + +// ConnectionSharedKey is response for GetConnectionSharedKey Api servive call +type ConnectionSharedKey struct { + autorest.Response `json:"-"` + Value *string `json:"value,omitempty"` +} + +// ConnectionSharedKeyResult is response for CheckConnectionSharedKey Api +// servive call +type ConnectionSharedKeyResult struct { + autorest.Response `json:"-"` + Value *string `json:"value,omitempty"` +} + +// DhcpOptions is dHCPOptions contains an array of DNS servers available to +// VMs deployed in the virtual networkStandard DHCP option for a subnet +// overrides VNET DHCP options. +type DhcpOptions struct { + DNSServers *[]string `json:"dnsServers,omitempty"` +} + +// DNSNameAvailabilityResult is response for CheckDnsNameAvailability Api +// servive call +type DNSNameAvailabilityResult struct { + autorest.Response `json:"-"` + Available *bool `json:"available,omitempty"` +} + +// Error is +type Error struct { + Code *string `json:"code,omitempty"` + Message *string `json:"message,omitempty"` + Target *string `json:"target,omitempty"` + Details *[]ErrorDetails `json:"details,omitempty"` + InnerError *string `json:"innerError,omitempty"` +} + +// ErrorDetails is +type ErrorDetails struct { + Code *string `json:"code,omitempty"` + Target *string `json:"target,omitempty"` + Message *string `json:"message,omitempty"` +} + +// ExpressRouteCircuit is expressRouteCircuit resource +type ExpressRouteCircuit struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Sku *ExpressRouteCircuitSku `json:"sku,omitempty"` + Properties *ExpressRouteCircuitPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ExpressRouteCircuitArpTable is the arp table associated with the +// ExpressRouteCircuit +type ExpressRouteCircuitArpTable struct { + Age *int32 `json:"age,omitempty"` + Interface *string `json:"interface,omitempty"` + IPAddress *string `json:"ipAddress,omitempty"` + MacAddress *string `json:"macAddress,omitempty"` +} + +// ExpressRouteCircuitAuthorization is authorization in a ExpressRouteCircuit +// resource +type ExpressRouteCircuitAuthorization struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *AuthorizationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ExpressRouteCircuitListResult is response for ListExpressRouteCircuit Api +// service call +type ExpressRouteCircuitListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuit `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteCircuitListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ExpressRouteCircuitListResult) ExpressRouteCircuitListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ExpressRouteCircuitPeering is peering in a ExpressRouteCircuit resource +type ExpressRouteCircuitPeering struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *ExpressRouteCircuitPeeringPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ExpressRouteCircuitPeeringConfig is specfies the peering config +type ExpressRouteCircuitPeeringConfig struct { + AdvertisedPublicPrefixes *[]string `json:"advertisedPublicPrefixes,omitempty"` + AdvertisedPublicPrefixesState ExpressRouteCircuitPeeringAdvertisedPublicPrefixState `json:"advertisedPublicPrefixesState,omitempty"` + CustomerASN *int32 `json:"customerASN,omitempty"` + RoutingRegistryName *string `json:"routingRegistryName,omitempty"` +} + +// ExpressRouteCircuitPeeringListResult is response for ListPeering Api +// service callRetrieves all Peerings that belongs to an ExpressRouteCircuit +type ExpressRouteCircuitPeeringListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuitPeering `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteCircuitPeeringListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ExpressRouteCircuitPeeringListResult) ExpressRouteCircuitPeeringListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ExpressRouteCircuitPeeringPropertiesFormat is +type ExpressRouteCircuitPeeringPropertiesFormat struct { + PeeringType ExpressRouteCircuitPeeringType `json:"peeringType,omitempty"` + State ExpressRouteCircuitPeeringState `json:"state,omitempty"` + AzureASN *int32 `json:"azureASN,omitempty"` + PeerASN *int32 `json:"peerASN,omitempty"` + PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` + SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` + PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` + SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` + SharedKey *string `json:"sharedKey,omitempty"` + VlanID *int32 `json:"vlanId,omitempty"` + MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` + Stats *ExpressRouteCircuitStats `json:"stats,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ExpressRouteCircuitPropertiesFormat is properties of ExpressRouteCircuit +type ExpressRouteCircuitPropertiesFormat struct { + AllowClassicOperations *bool `json:"allowClassicOperations,omitempty"` + CircuitProvisioningState *string `json:"circuitProvisioningState,omitempty"` + ServiceProviderProvisioningState ServiceProviderProvisioningState `json:"serviceProviderProvisioningState,omitempty"` + Authorizations *[]ExpressRouteCircuitAuthorization `json:"authorizations,omitempty"` + Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` + ServiceKey *string `json:"serviceKey,omitempty"` + ServiceProviderNotes *string `json:"serviceProviderNotes,omitempty"` + ServiceProviderProperties *ExpressRouteCircuitServiceProviderProperties `json:"serviceProviderProperties,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ExpressRouteCircuitRoutesTable is the routes table associated with the +// ExpressRouteCircuit +type ExpressRouteCircuitRoutesTable struct { + Network *string `json:"network,omitempty"` + NextHop *string `json:"nextHop,omitempty"` + LocPrf *string `json:"locPrf,omitempty"` + Weight *int32 `json:"weight,omitempty"` + Path *string `json:"path,omitempty"` +} + +// ExpressRouteCircuitRoutesTableSummary is the routes table associated with +// the ExpressRouteCircuit +type ExpressRouteCircuitRoutesTableSummary struct { + Neighbor *string `json:"neighbor,omitempty"` + V *int32 `json:"v,omitempty"` + As *int32 `json:"as,omitempty"` + UpDown *string `json:"upDown,omitempty"` + StatePfxRcd *string `json:"statePfxRcd,omitempty"` +} + +// ExpressRouteCircuitsArpTableListResult is response for ListArpTable +// associated with the Express Route Circuits Api +type ExpressRouteCircuitsArpTableListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuitArpTable `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteCircuitServiceProviderProperties is contains +// ServiceProviderProperties in an ExpressRouteCircuit +type ExpressRouteCircuitServiceProviderProperties struct { + ServiceProviderName *string `json:"serviceProviderName,omitempty"` + PeeringLocation *string `json:"peeringLocation,omitempty"` + BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` +} + +// ExpressRouteCircuitSku is contains sku in an ExpressRouteCircuit +type ExpressRouteCircuitSku struct { + Name *string `json:"name,omitempty"` + Tier ExpressRouteCircuitSkuTier `json:"tier,omitempty"` + Family ExpressRouteCircuitSkuFamily `json:"family,omitempty"` +} + +// ExpressRouteCircuitsRoutesTableListResult is response for ListRoutesTable +// associated with the Express Route Circuits Api +type ExpressRouteCircuitsRoutesTableListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuitRoutesTable `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteCircuitsRoutesTableSummaryListResult is response for +// ListRoutesTable associated with the Express Route Circuits Api +type ExpressRouteCircuitsRoutesTableSummaryListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteCircuitRoutesTableSummary `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteCircuitStats is contains Stats associated with the peering +type ExpressRouteCircuitStats struct { + autorest.Response `json:"-"` + PrimarybytesIn *int64 `json:"primarybytesIn,omitempty"` + PrimarybytesOut *int64 `json:"primarybytesOut,omitempty"` + SecondarybytesIn *int64 `json:"secondarybytesIn,omitempty"` + SecondarybytesOut *int64 `json:"secondarybytesOut,omitempty"` +} + +// ExpressRouteServiceProvider is expressRouteResourceProvider object +type ExpressRouteServiceProvider struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *ExpressRouteServiceProviderPropertiesFormat `json:"properties,omitempty"` +} + +// ExpressRouteServiceProviderBandwidthsOffered is contains Bandwidths offered +// in ExpressRouteServiceProviders +type ExpressRouteServiceProviderBandwidthsOffered struct { + OfferName *string `json:"offerName,omitempty"` + ValueInMbps *int32 `json:"valueInMbps,omitempty"` +} + +// ExpressRouteServiceProviderListResult is response for +// ListExpressRouteServiceProvider Api service call +type ExpressRouteServiceProviderListResult struct { + autorest.Response `json:"-"` + Value *[]ExpressRouteServiceProvider `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ExpressRouteServiceProviderListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ExpressRouteServiceProviderListResult) ExpressRouteServiceProviderListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ExpressRouteServiceProviderPropertiesFormat is properties of +// ExpressRouteServiceProvider +type ExpressRouteServiceProviderPropertiesFormat struct { + PeeringLocations *[]string `json:"peeringLocations,omitempty"` + BandwidthsOffered *[]ExpressRouteServiceProviderBandwidthsOffered `json:"bandwidthsOffered,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// FrontendIPConfiguration is frontend IP address of the load balancer +type FrontendIPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *FrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// FrontendIPConfigurationPropertiesFormat is properties of Frontend IP +// Configuration of the load balancer +type FrontendIPConfigurationPropertiesFormat struct { + InboundNatRules *[]SubResource `json:"inboundNatRules,omitempty"` + InboundNatPools *[]SubResource `json:"inboundNatPools,omitempty"` + OutboundNatRules *[]SubResource `json:"outboundNatRules,omitempty"` + LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` + PrivateIPAddress *string `json:"privateIPAddress,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` + Subnet *Subnet `json:"subnet,omitempty"` + PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// InboundNatPool is inbound NAT pool of the loadbalancer +type InboundNatPool struct { + ID *string `json:"id,omitempty"` + Properties *InboundNatPoolPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// InboundNatPoolPropertiesFormat is properties of Inbound NAT pool +type InboundNatPoolPropertiesFormat struct { + FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` + Protocol TransportProtocol `json:"protocol,omitempty"` + FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` + FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// InboundNatRule is inbound NAT rule of the loadbalancer +type InboundNatRule struct { + ID *string `json:"id,omitempty"` + Properties *InboundNatRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// InboundNatRulePropertiesFormat is properties of Inbound NAT rule +type InboundNatRulePropertiesFormat struct { + FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` + BackendIPConfiguration *InterfaceIPConfiguration `json:"backendIPConfiguration,omitempty"` + Protocol TransportProtocol `json:"protocol,omitempty"` + FrontendPort *int32 `json:"frontendPort,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` + EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// Interface is a NetworkInterface in a resource group +type Interface struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *InterfacePropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// InterfaceDNSSettings is dns Settings of a network interface +type InterfaceDNSSettings struct { + DNSServers *[]string `json:"dnsServers,omitempty"` + AppliedDNSServers *[]string `json:"appliedDnsServers,omitempty"` + InternalDNSNameLabel *string `json:"internalDnsNameLabel,omitempty"` + InternalFqdn *string `json:"internalFqdn,omitempty"` + InternalDomainNameSuffix *string `json:"internalDomainNameSuffix,omitempty"` +} + +// InterfaceIPConfiguration is iPConfiguration in a NetworkInterface +type InterfaceIPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *InterfaceIPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// InterfaceIPConfigurationPropertiesFormat is properties of IPConfiguration +type InterfaceIPConfigurationPropertiesFormat struct { + ApplicationGatewayBackendAddressPools *[]ApplicationGatewayBackendAddressPool `json:"applicationGatewayBackendAddressPools,omitempty"` + LoadBalancerBackendAddressPools *[]BackendAddressPool `json:"loadBalancerBackendAddressPools,omitempty"` + LoadBalancerInboundNatRules *[]InboundNatRule `json:"loadBalancerInboundNatRules,omitempty"` + PrivateIPAddress *string `json:"privateIPAddress,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` + PrivateIPAddressVersion IPVersion `json:"privateIPAddressVersion,omitempty"` + Subnet *Subnet `json:"subnet,omitempty"` + Primary *bool `json:"primary,omitempty"` + PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// InterfaceListResult is response for ListNetworkInterface Api service call +type InterfaceListResult struct { + autorest.Response `json:"-"` + Value *[]Interface `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// InterfaceListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client InterfaceListResult) InterfaceListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// InterfacePropertiesFormat is networkInterface properties. +type InterfacePropertiesFormat struct { + VirtualMachine *SubResource `json:"virtualMachine,omitempty"` + NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` + IPConfigurations *[]InterfaceIPConfiguration `json:"ipConfigurations,omitempty"` + DNSSettings *InterfaceDNSSettings `json:"dnsSettings,omitempty"` + MacAddress *string `json:"macAddress,omitempty"` + Primary *bool `json:"primary,omitempty"` + EnableIPForwarding *bool `json:"enableIPForwarding,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// IPConfiguration is iPConfiguration +type IPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *IPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// IPConfigurationPropertiesFormat is properties of IPConfiguration +type IPConfigurationPropertiesFormat struct { + PrivateIPAddress *string `json:"privateIPAddress,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` + Subnet *Subnet `json:"subnet,omitempty"` + PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// LoadBalancer is loadBalancer resource +type LoadBalancer struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *LoadBalancerPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// LoadBalancerListResult is response for ListLoadBalancers Api service call +type LoadBalancerListResult struct { + autorest.Response `json:"-"` + Value *[]LoadBalancer `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// LoadBalancerListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client LoadBalancerListResult) LoadBalancerListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// LoadBalancerPropertiesFormat is properties of Load Balancer +type LoadBalancerPropertiesFormat struct { + FrontendIPConfigurations *[]FrontendIPConfiguration `json:"frontendIPConfigurations,omitempty"` + BackendAddressPools *[]BackendAddressPool `json:"backendAddressPools,omitempty"` + LoadBalancingRules *[]LoadBalancingRule `json:"loadBalancingRules,omitempty"` + Probes *[]Probe `json:"probes,omitempty"` + InboundNatRules *[]InboundNatRule `json:"inboundNatRules,omitempty"` + InboundNatPools *[]InboundNatPool `json:"inboundNatPools,omitempty"` + OutboundNatRules *[]OutboundNatRule `json:"outboundNatRules,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// LoadBalancingRule is rules of the load balancer +type LoadBalancingRule struct { + ID *string `json:"id,omitempty"` + Properties *LoadBalancingRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// LoadBalancingRulePropertiesFormat is properties of the load balancer +type LoadBalancingRulePropertiesFormat struct { + FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` + BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` + Probe *SubResource `json:"probe,omitempty"` + Protocol TransportProtocol `json:"protocol,omitempty"` + LoadDistribution LoadDistribution `json:"loadDistribution,omitempty"` + FrontendPort *int32 `json:"frontendPort,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` + EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// LocalNetworkGateway is a common class for general resource information +type LocalNetworkGateway struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *LocalNetworkGatewayPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// LocalNetworkGatewayListResult is response for ListLocalNetworkGateways Api +// service call +type LocalNetworkGatewayListResult struct { + autorest.Response `json:"-"` + Value *[]LocalNetworkGateway `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// LocalNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client LocalNetworkGatewayListResult) LocalNetworkGatewayListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// LocalNetworkGatewayPropertiesFormat is localNetworkGateway properties +type LocalNetworkGatewayPropertiesFormat struct { + LocalNetworkAddressSpace *AddressSpace `json:"localNetworkAddressSpace,omitempty"` + GatewayIPAddress *string `json:"gatewayIpAddress,omitempty"` + BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// OutboundNatRule is outbound NAT pool of the loadbalancer +type OutboundNatRule struct { + ID *string `json:"id,omitempty"` + Properties *OutboundNatRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// OutboundNatRulePropertiesFormat is outbound NAT pool of the loadbalancer +type OutboundNatRulePropertiesFormat struct { + AllocatedOutboundPorts *int32 `json:"allocatedOutboundPorts,omitempty"` + FrontendIPConfigurations *[]SubResource `json:"frontendIPConfigurations,omitempty"` + BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// Probe is load balancer Probe +type Probe struct { + ID *string `json:"id,omitempty"` + Properties *ProbePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// ProbePropertiesFormat is +type ProbePropertiesFormat struct { + LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` + Protocol ProbeProtocol `json:"protocol,omitempty"` + Port *int32 `json:"port,omitempty"` + IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` + NumberOfProbes *int32 `json:"numberOfProbes,omitempty"` + RequestPath *string `json:"requestPath,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// PublicIPAddress is publicIPAddress resource +type PublicIPAddress struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *PublicIPAddressPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// PublicIPAddressDNSSettings is contains FQDN of the DNS record associated +// with the public IP address +type PublicIPAddressDNSSettings struct { + DomainNameLabel *string `json:"domainNameLabel,omitempty"` + Fqdn *string `json:"fqdn,omitempty"` + ReverseFqdn *string `json:"reverseFqdn,omitempty"` +} + +// PublicIPAddressListResult is response for ListPublicIpAddresses Api service +// call +type PublicIPAddressListResult struct { + autorest.Response `json:"-"` + Value *[]PublicIPAddress `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// PublicIPAddressListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client PublicIPAddressListResult) PublicIPAddressListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// PublicIPAddressPropertiesFormat is publicIpAddress properties +type PublicIPAddressPropertiesFormat struct { + PublicIPAllocationMethod IPAllocationMethod `json:"publicIPAllocationMethod,omitempty"` + PublicIPAddressVersion IPVersion `json:"publicIPAddressVersion,omitempty"` + IPConfiguration *IPConfiguration `json:"ipConfiguration,omitempty"` + DNSSettings *PublicIPAddressDNSSettings `json:"dnsSettings,omitempty"` + IPAddress *string `json:"ipAddress,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// Resource is +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// Route is route resource +type Route struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *RoutePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// RouteListResult is response for ListRoute Api servive call +type RouteListResult struct { + autorest.Response `json:"-"` + Value *[]Route `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// RouteListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client RouteListResult) RouteListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RoutePropertiesFormat is route resource +type RoutePropertiesFormat struct { + AddressPrefix *string `json:"addressPrefix,omitempty"` + NextHopType RouteNextHopType `json:"nextHopType,omitempty"` + NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// RouteTable is routeTable resource +type RouteTable struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *RouteTablePropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// RouteTableListResult is response for ListRouteTable Api servive call +type RouteTableListResult struct { + autorest.Response `json:"-"` + Value *[]RouteTable `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// RouteTableListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client RouteTableListResult) RouteTableListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RouteTablePropertiesFormat is route Table resource +type RouteTablePropertiesFormat struct { + Routes *[]Route `json:"routes,omitempty"` + Subnets *[]Subnet `json:"subnets,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// SecurityGroup is networkSecurityGroup resource +type SecurityGroup struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *SecurityGroupPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// SecurityGroupListResult is response for ListNetworkSecurityGroups Api +// servive call +type SecurityGroupListResult struct { + autorest.Response `json:"-"` + Value *[]SecurityGroup `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SecurityGroupListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SecurityGroupListResult) SecurityGroupListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SecurityGroupPropertiesFormat is network Security Group resource +type SecurityGroupPropertiesFormat struct { + SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` + DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` + NetworkInterfaces *[]Interface `json:"networkInterfaces,omitempty"` + Subnets *[]Subnet `json:"subnets,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// SecurityRule is network security rule +type SecurityRule struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *SecurityRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// SecurityRuleListResult is response for ListSecurityRule Api service +// callRetrieves all security rules that belongs to a network security group +type SecurityRuleListResult struct { + autorest.Response `json:"-"` + Value *[]SecurityRule `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SecurityRuleListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SecurityRuleListResult) SecurityRuleListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SecurityRulePropertiesFormat is +type SecurityRulePropertiesFormat struct { + Description *string `json:"description,omitempty"` + Protocol SecurityRuleProtocol `json:"protocol,omitempty"` + SourcePortRange *string `json:"sourcePortRange,omitempty"` + DestinationPortRange *string `json:"destinationPortRange,omitempty"` + SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` + DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` + Access SecurityRuleAccess `json:"access,omitempty"` + Priority *int32 `json:"priority,omitempty"` + Direction SecurityRuleDirection `json:"direction,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// String is +type String struct { + autorest.Response `json:"-"` + Value *string `json:"value,omitempty"` +} + +// Subnet is subnet in a VirtualNework resource +type Subnet struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Properties *SubnetPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// SubnetListResult is response for ListSubnets Api service callRetrieves all +// subnet that belongs to a virtual network +type SubnetListResult struct { + autorest.Response `json:"-"` + Value *[]Subnet `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SubnetListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SubnetListResult) SubnetListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SubnetPropertiesFormat is +type SubnetPropertiesFormat struct { + AddressPrefix *string `json:"addressPrefix,omitempty"` + NetworkSecurityGroup *SecurityGroup `json:"networkSecurityGroup,omitempty"` + RouteTable *RouteTable `json:"routeTable,omitempty"` + IPConfigurations *[]IPConfiguration `json:"ipConfigurations,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// SubResource is +type SubResource struct { + ID *string `json:"id,omitempty"` +} + +// Usage is describes Network Resource Usage. +type Usage struct { + Unit *string `json:"unit,omitempty"` + CurrentValue *int64 `json:"currentValue,omitempty"` + Limit *int64 `json:"limit,omitempty"` + Name *UsageName `json:"name,omitempty"` +} + +// UsageName is the Usage Names. +type UsageName struct { + Value *string `json:"value,omitempty"` + LocalizedValue *string `json:"localizedValue,omitempty"` +} + +// UsagesListResult is the List Usages operation response. +type UsagesListResult struct { + autorest.Response `json:"-"` + Value *[]Usage `json:"value,omitempty"` + NextLink *string `json:",omitempty"` +} + +// UsagesListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client UsagesListResult) UsagesListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualNetwork is virtual Network resource +type VirtualNetwork struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualNetworkPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VirtualNetworkGateway is a common class for general resource information +type VirtualNetworkGateway struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualNetworkGatewayPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VirtualNetworkGatewayConnection is a common class for general resource +// information +type VirtualNetworkGatewayConnection struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Properties *VirtualNetworkGatewayConnectionPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VirtualNetworkGatewayConnectionListResult is response for +// ListVirtualNetworkGatewayConnections Api service call +type VirtualNetworkGatewayConnectionListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualNetworkGatewayConnection `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualNetworkGatewayConnectionListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualNetworkGatewayConnectionListResult) VirtualNetworkGatewayConnectionListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualNetworkGatewayConnectionPropertiesFormat is +// virtualNeworkGatewayConnection properties +type VirtualNetworkGatewayConnectionPropertiesFormat struct { + AuthorizationKey *string `json:"authorizationKey,omitempty"` + VirtualNetworkGateway1 *VirtualNetworkGateway `json:"virtualNetworkGateway1,omitempty"` + VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` + LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` + ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` + RoutingWeight *int32 `json:"routingWeight,omitempty"` + SharedKey *string `json:"sharedKey,omitempty"` + ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` + EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` + IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` + Peer *SubResource `json:"peer,omitempty"` + EnableBgp *bool `json:"enableBgp,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VirtualNetworkGatewayIPConfiguration is ipConfiguration for Virtual network +// gateway +type VirtualNetworkGatewayIPConfiguration struct { + ID *string `json:"id,omitempty"` + Properties *VirtualNetworkGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VirtualNetworkGatewayIPConfigurationPropertiesFormat is properties of +// VirtualNetworkGatewayIPConfiguration +type VirtualNetworkGatewayIPConfigurationPropertiesFormat struct { + PrivateIPAddress *string `json:"privateIPAddress,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` + Subnet *SubResource `json:"subnet,omitempty"` + PublicIPAddress *SubResource `json:"publicIPAddress,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VirtualNetworkGatewayListResult is response for ListVirtualNetworkGateways +// Api service call +type VirtualNetworkGatewayListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualNetworkGateway `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualNetworkGatewayListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualNetworkGatewayListResult) VirtualNetworkGatewayListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualNetworkGatewayPropertiesFormat is virtualNeworkGateay properties +type VirtualNetworkGatewayPropertiesFormat struct { + IPConfigurations *[]VirtualNetworkGatewayIPConfiguration `json:"ipConfigurations,omitempty"` + GatewayType VirtualNetworkGatewayType `json:"gatewayType,omitempty"` + VpnType VpnType `json:"vpnType,omitempty"` + EnableBgp *bool `json:"enableBgp,omitempty"` + GatewayDefaultSite *SubResource `json:"gatewayDefaultSite,omitempty"` + Sku *VirtualNetworkGatewaySku `json:"sku,omitempty"` + VpnClientConfiguration *VpnClientConfiguration `json:"vpnClientConfiguration,omitempty"` + BgpSettings *BgpSettings `json:"bgpSettings,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VirtualNetworkGatewaySku is virtualNetworkGatewaySku details +type VirtualNetworkGatewaySku struct { + Name VirtualNetworkGatewaySkuName `json:"name,omitempty"` + Tier VirtualNetworkGatewaySkuTier `json:"tier,omitempty"` + Capacity *int32 `json:"capacity,omitempty"` +} + +// VirtualNetworkListResult is response for ListVirtualNetworks Api servive +// call +type VirtualNetworkListResult struct { + autorest.Response `json:"-"` + Value *[]VirtualNetwork `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualNetworkListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client VirtualNetworkListResult) VirtualNetworkListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// VirtualNetworkPropertiesFormat is +type VirtualNetworkPropertiesFormat struct { + AddressSpace *AddressSpace `json:"addressSpace,omitempty"` + DhcpOptions *DhcpOptions `json:"dhcpOptions,omitempty"` + Subnets *[]Subnet `json:"subnets,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VpnClientConfiguration is vpnClientConfiguration for P2S client +type VpnClientConfiguration struct { + VpnClientAddressPool *AddressSpace `json:"vpnClientAddressPool,omitempty"` + VpnClientRootCertificates *[]VpnClientRootCertificate `json:"vpnClientRootCertificates,omitempty"` + VpnClientRevokedCertificates *[]VpnClientRevokedCertificate `json:"vpnClientRevokedCertificates,omitempty"` +} + +// VpnClientParameters is vpnClientParameters +type VpnClientParameters struct { + ProcessorArchitecture ProcessorArchitecture `json:"ProcessorArchitecture,omitempty"` +} + +// VpnClientRevokedCertificate is vPN client revoked certificate of virtual +// network gateway +type VpnClientRevokedCertificate struct { + ID *string `json:"id,omitempty"` + Properties *VpnClientRevokedCertificatePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VpnClientRevokedCertificatePropertiesFormat is properties of the revoked +// VPN client certificate of virtual network gateway +type VpnClientRevokedCertificatePropertiesFormat struct { + Thumbprint *string `json:"thumbprint,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VpnClientRootCertificate is vPN client root certificate of virtual network +// gateway +type VpnClientRootCertificate struct { + ID *string `json:"id,omitempty"` + Properties *VpnClientRootCertificatePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// VpnClientRootCertificatePropertiesFormat is properties of SSL certificates +// of application gateway +type VpnClientRootCertificatePropertiesFormat struct { + PublicCertData *string `json:"publicCertData,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go new file mode 100644 index 000000000000..0dda5e7fd689 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go @@ -0,0 +1,413 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// PublicIPAddressesClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type PublicIPAddressesClient struct { + ManagementClient +} + +// NewPublicIPAddressesClient creates an instance of the +// PublicIPAddressesClient client. +func NewPublicIPAddressesClient(subscriptionID string) PublicIPAddressesClient { + return PublicIPAddressesClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put PublicIPAddress operation creates/updates a +// stable/dynamic PublicIP address This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. publicIPAddressName is +// the name of the publicIpAddress. parameters is parameters supplied to the +// create/update PublicIPAddress operation +func (client PublicIPAddressesClient) CreateOrUpdate(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, publicIPAddressName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "publicIpAddressName": autorest.Encode("path", publicIPAddressName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete publicIpAddress operation deletes the specified +// publicIpAddress. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. publicIPAddressName is +// the name of the subnet. +func (client PublicIPAddressesClient) Delete(resourceGroupName string, publicIPAddressName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, publicIPAddressName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, publicIPAddressName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "publicIpAddressName": autorest.Encode("path", publicIPAddressName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client PublicIPAddressesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get publicIpAddress operation retreives information about the +// specified pubicIpAddress +// +// resourceGroupName is the name of the resource group. publicIPAddressName is +// the name of the subnet. expand is expand references resources. +func (client PublicIPAddressesClient) Get(resourceGroupName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { + req, err := client.GetPreparer(resourceGroupName, publicIPAddressName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PublicIPAddressesClient) GetPreparer(resourceGroupName string, publicIPAddressName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "publicIpAddressName": autorest.Encode("path", publicIPAddressName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client PublicIPAddressesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result PublicIPAddress, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List publicIpAddress opertion retrieves all the publicIpAddresses +// in a resource group. +// +// resourceGroupName is the name of the resource group. +func (client PublicIPAddressesClient) List(resourceGroupName string) (result PublicIPAddressListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PublicIPAddressesClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client PublicIPAddressesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { + req, err := lastResults.PublicIPAddressListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the List publicIpAddress opertion retrieves all the +// publicIpAddresses in a subscription. +func (client PublicIPAddressesClient) ListAll() (result PublicIPAddressListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client PublicIPAddressesClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client PublicIPAddressesClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (result PublicIPAddressListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client PublicIPAddressesClient) ListAllNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { + req, err := lastResults.PublicIPAddressListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go new file mode 100644 index 000000000000..706b8c29a0c7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go @@ -0,0 +1,331 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// RoutesClient is the the Microsoft Azure Network management API provides a +// RESTful set of web services that interact with Microsoft Azure Networks +// service to manage your network resrources. The API has entities that +// capture the relationship between an end user and the Microsoft Azure +// Networks service. +type RoutesClient struct { + ManagementClient +} + +// NewRoutesClient creates an instance of the RoutesClient client. +func NewRoutesClient(subscriptionID string) RoutesClient { + return RoutesClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put route operation creates/updates a route in the +// specified route table This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. routeName is the name of the route. +// routeParameters is parameters supplied to the create/update routeoperation +func (client RoutesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, routeName string, routeParameters Route, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, routeName, routeParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, routeName string, routeParameters Route, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeName": autorest.Encode("path", routeName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), + autorest.WithJSON(routeParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RoutesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete route operation deletes the specified route from a route +// table. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. routeName is the name of the route. +func (client RoutesClient) Delete(resourceGroupName string, routeTableName string, routeName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, routeTableName, routeName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableName string, routeName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeName": autorest.Encode("path", routeName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RoutesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get route operation retreives information about the specified route +// from the route table. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. routeName is the name of the route. +func (client RoutesClient) Get(resourceGroupName string, routeTableName string, routeName string) (result Route, err error) { + req, err := client.GetPreparer(resourceGroupName, routeTableName, routeName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RoutesClient) GetPreparer(resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeName": autorest.Encode("path", routeName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RoutesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List network security rule opertion retrieves all the routes in a +// route table. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. +func (client RoutesClient) List(resourceGroupName string, routeTableName string) (result RouteListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, routeTableName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client RoutesClient) ListPreparer(resourceGroupName string, routeTableName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client RoutesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client RoutesClient) ListResponder(resp *http.Response) (result RouteListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client RoutesClient) ListNextResults(lastResults RouteListResult) (result RouteListResult, err error) { + req, err := lastResults.RouteListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go new file mode 100644 index 000000000000..6d5d335fe13e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go @@ -0,0 +1,410 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// RouteTablesClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type RouteTablesClient struct { + ManagementClient +} + +// NewRouteTablesClient creates an instance of the RouteTablesClient client. +func NewRouteTablesClient(subscriptionID string) RouteTablesClient { + return RouteTablesClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put RouteTable operation creates/updates a route tablein +// the specified resource group. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. parameters is parameters supplied to the +// create/update Route Table operation +func (client RouteTablesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RouteTablesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete RouteTable operation deletes the specifed Route Table +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. +func (client RouteTablesClient) Delete(resourceGroupName string, routeTableName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, routeTableName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTableName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RouteTablesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get RouteTables operation retrieves information about the specified +// route table. +// +// resourceGroupName is the name of the resource group. routeTableName is the +// name of the route table. expand is expand references resources. +func (client RouteTablesClient) Get(resourceGroupName string, routeTableName string, expand string) (result RouteTable, err error) { + req, err := client.GetPreparer(resourceGroupName, routeTableName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RouteTablesClient) GetPreparer(resourceGroupName string, routeTableName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeTableName": autorest.Encode("path", routeTableName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RouteTablesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteTable, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the list RouteTables returns all route tables in a resource group +// +// resourceGroupName is the name of the resource group. +func (client RouteTablesClient) List(resourceGroupName string) (result RouteTableListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client RouteTablesClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client RouteTablesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client RouteTablesClient) ListResponder(resp *http.Response) (result RouteTableListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client RouteTablesClient) ListNextResults(lastResults RouteTableListResult) (result RouteTableListResult, err error) { + req, err := lastResults.RouteTableListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the list RouteTables returns all route tables in a subscription +func (client RouteTablesClient) ListAll() (result RouteTableListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client RouteTablesClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client RouteTablesClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client RouteTablesClient) ListAllResponder(resp *http.Response) (result RouteTableListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client RouteTablesClient) ListAllNextResults(lastResults RouteTableListResult) (result RouteTableListResult, err error) { + req, err := lastResults.RouteTableListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go new file mode 100644 index 000000000000..02ee8a177c90 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go @@ -0,0 +1,416 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// SecurityGroupsClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type SecurityGroupsClient struct { + ManagementClient +} + +// NewSecurityGroupsClient creates an instance of the SecurityGroupsClient +// client. +func NewSecurityGroupsClient(subscriptionID string) SecurityGroupsClient { + return SecurityGroupsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put NetworkSecurityGroup operation creates/updates a +// network security groupin the specified resource group. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +// parameters is parameters supplied to the create/update Network Security +// Group operation +func (client SecurityGroupsClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete NetworkSecurityGroup operation deletes the specifed +// network security group This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +func (client SecurityGroupsClient) Delete(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityGroupsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get NetworkSecurityGroups operation retrieves information about the +// specified network security group. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. expand +// is expand references resources. +func (client SecurityGroupsClient) Get(resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, err error) { + req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SecurityGroupsClient) GetPreparer(resourceGroupName string, networkSecurityGroupName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result SecurityGroup, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the list NetworkSecurityGroups returns all network security groups in +// a resource group +// +// resourceGroupName is the name of the resource group. +func (client SecurityGroupsClient) List(resourceGroupName string) (result SecurityGroupListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SecurityGroupsClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result SecurityGroupListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { + req, err := lastResults.SecurityGroupListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the list NetworkSecurityGroups returns all network security groups +// in a subscription +func (client SecurityGroupsClient) ListAll() (result SecurityGroupListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client SecurityGroupsClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkSecurityGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result SecurityGroupListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client SecurityGroupsClient) ListAllNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { + req, err := lastResults.SecurityGroupListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go new file mode 100644 index 000000000000..e4abcb16c086 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go @@ -0,0 +1,337 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// SecurityRulesClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type SecurityRulesClient struct { + ManagementClient +} + +// NewSecurityRulesClient creates an instance of the SecurityRulesClient +// client. +func NewSecurityRulesClient(subscriptionID string) SecurityRulesClient { + return SecurityRulesClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put network security rule operation creates/updates a +// security rule in the specified network security group This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +// securityRuleName is the name of the security rule. securityRuleParameters +// is parameters supplied to the create/update network security rule +// operation +func (client SecurityRulesClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "securityRuleName": autorest.Encode("path", securityRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), + autorest.WithJSON(securityRuleParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityRulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete network security rule operation deletes the specified +// network security rule. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +// securityRuleName is the name of the security rule. +func (client SecurityRulesClient) Delete(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "securityRuleName": autorest.Encode("path", securityRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityRulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get NetworkSecurityRule operation retreives information about the +// specified network security rule. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +// securityRuleName is the name of the security rule. +func (client SecurityRulesClient) Get(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRule, err error) { + req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, securityRuleName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SecurityRulesClient) GetPreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "securityRuleName": autorest.Encode("path", securityRuleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SecurityRulesClient) GetResponder(resp *http.Response) (result SecurityRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List network security rule opertion retrieves all the security +// rules in a network security group. +// +// resourceGroupName is the name of the resource group. +// networkSecurityGroupName is the name of the network security group. +func (client SecurityRulesClient) List(resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, networkSecurityGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SecurityRulesClient) ListPreparer(resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkSecurityGroupName": autorest.Encode("path", networkSecurityGroupName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client SecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SecurityRulesClient) ListResponder(resp *http.Response) (result SecurityRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client SecurityRulesClient) ListNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { + req, err := lastResults.SecurityRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go new file mode 100644 index 000000000000..c5acdf72c0e7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go @@ -0,0 +1,336 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// SubnetsClient is the the Microsoft Azure Network management API provides a +// RESTful set of web services that interact with Microsoft Azure Networks +// service to manage your network resrources. The API has entities that +// capture the relationship between an end user and the Microsoft Azure +// Networks service. +type SubnetsClient struct { + ManagementClient +} + +// NewSubnetsClient creates an instance of the SubnetsClient client. +func NewSubnetsClient(subscriptionID string) SubnetsClient { + return SubnetsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put Subnet operation creates/updates a subnet in +// thespecified virtual network This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. subnetName is the name of the subnet. +// subnetParameters is parameters supplied to the create/update Subnet +// operation +func (client SubnetsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subnetName": autorest.Encode("path", subnetName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), + autorest.WithJSON(subnetParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SubnetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the delete subnet operation deletes the specified subnet. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. subnetName is the name of the subnet. +func (client SubnetsClient) Delete(resourceGroupName string, virtualNetworkName string, subnetName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, subnetName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetworkName string, subnetName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subnetName": autorest.Encode("path", subnetName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client SubnetsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get subnet operation retreives information about the specified +// subnet. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. subnetName is the name of the subnet. +// expand is expand references resources. +func (client SubnetsClient) Get(resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result Subnet, err error) { + req, err := client.GetPreparer(resourceGroupName, virtualNetworkName, subnetName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SubnetsClient) GetPreparer(resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subnetName": autorest.Encode("path", subnetName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SubnetsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List subnets opertion retrieves all the subnets in a virtual +// network. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. +func (client SubnetsClient) List(resourceGroupName string, virtualNetworkName string) (result SubnetListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, virtualNetworkName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SubnetsClient) ListPreparer(resourceGroupName string, virtualNetworkName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client SubnetsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SubnetsClient) ListResponder(resp *http.Response) (result SubnetListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client SubnetsClient) ListNextResults(lastResults SubnetListResult) (result SubnetListResult, err error) { + req, err := lastResults.SubnetListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go new file mode 100644 index 000000000000..95ad01e48835 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go @@ -0,0 +1,124 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// UsagesClient is the the Microsoft Azure Network management API provides a +// RESTful set of web services that interact with Microsoft Azure Networks +// service to manage your network resrources. The API has entities that +// capture the relationship between an end user and the Microsoft Azure +// Networks service. +type UsagesClient struct { + ManagementClient +} + +// NewUsagesClient creates an instance of the UsagesClient client. +func NewUsagesClient(subscriptionID string) UsagesClient { + return UsagesClient{New(subscriptionID)} +} + +// List lists compute usages for a subscription. +// +// location is the location upon which resource usage is queried. +func (client UsagesClient) List(location string) (result UsagesListResult, err error) { + req, err := client.ListPreparer(location) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client UsagesClient) ListPreparer(location string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client UsagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client UsagesClient) ListResponder(resp *http.Response) (result UsagesListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client UsagesClient) ListNextResults(lastResults UsagesListResult) (result UsagesListResult, err error) { + req, err := lastResults.UsagesListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go new file mode 100644 index 000000000000..7eb65d69287e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go @@ -0,0 +1,43 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "fmt" +) + +const ( + major = "3" + minor = "0" + patch = "0" + // Always begin a "tag" with a dash (as per http://semver.org) + tag = "-beta" + semVerFormat = "%s.%s.%s%s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" +) + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return fmt.Sprintf(userAgentFormat, Version(), "network", "2016-03-30") +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return fmt.Sprintf(semVerFormat, major, minor, patch, tag) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go new file mode 100644 index 000000000000..eacc11c8bf2c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go @@ -0,0 +1,549 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualNetworkGatewayConnectionsClient is the the Microsoft Azure Network +// management API provides a RESTful set of web services that interact with +// Microsoft Azure Networks service to manage your network resrources. The +// API has entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type VirtualNetworkGatewayConnectionsClient struct { + ManagementClient +} + +// NewVirtualNetworkGatewayConnectionsClient creates an instance of the +// VirtualNetworkGatewayConnectionsClient client. +func NewVirtualNetworkGatewayConnectionsClient(subscriptionID string) VirtualNetworkGatewayConnectionsClient { + return VirtualNetworkGatewayConnectionsClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put VirtualNetworkGatewayConnection operation +// creates/updates a virtual network gateway connection in the specified +// resource group through Network resource provider. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayConnectionName is the name of the virtual network +// gateway conenction. parameters is parameters supplied to the Begin Create +// or update Virtual Network Gateway connection operation through Network +// resource provider. +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete VirtualNetworkGatewayConnection operation deletes the +// specifed virtual network Gateway connection through Network resource +// provider. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayConnectionName is the name of the virtual network +// gateway connection. +func (client VirtualNetworkGatewayConnectionsClient) Delete(resourceGroupName string, virtualNetworkGatewayConnectionName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get VirtualNetworkGatewayConnection operation retrieves information +// about the specified virtual network gateway connection through Network +// resource provider. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayConnectionName is the name of the virtual network +// gateway connection. +func (client VirtualNetworkGatewayConnectionsClient) Get(resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnection, err error) { + req, err := client.GetPreparer(resourceGroupName, virtualNetworkGatewayConnectionName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualNetworkGatewayConnectionsClient) GetPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetSharedKey the Get VirtualNetworkGatewayConnectionSharedKey operation +// retrieves information about the specified virtual network gateway +// connection shared key through Network resource provider. +// +// resourceGroupName is the name of the resource group. +// connectionSharedKeyName is the virtual network gateway connection shared +// key name. +func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(resourceGroupName string, connectionSharedKeyName string) (result ConnectionSharedKeyResult, err error) { + req, err := client.GetSharedKeyPreparer(resourceGroupName, connectionSharedKeyName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", nil, "Failure preparing request") + } + + resp, err := client.GetSharedKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") + } + + result, err = client.GetSharedKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure responding to request") + } + + return +} + +// GetSharedKeyPreparer prepares the GetSharedKey request. +func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyPreparer(resourceGroupName string, connectionSharedKeyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "connectionSharedKeyName": autorest.Encode("path", connectionSharedKeyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{connectionSharedKeyName}/sharedkey", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSharedKeySender sends the GetSharedKey request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetSharedKeyResponder handles the response to the GetSharedKey request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKeyResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List VirtualNetworkGatewayConnections operation retrieves all the +// virtual network gateways connections created. +// +// resourceGroupName is the name of the resource group. +func (client VirtualNetworkGatewayConnectionsClient) List(resourceGroupName string) (result VirtualNetworkGatewayConnectionListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualNetworkGatewayConnectionsClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayConnectionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client VirtualNetworkGatewayConnectionsClient) ListNextResults(lastResults VirtualNetworkGatewayConnectionListResult) (result VirtualNetworkGatewayConnectionListResult, err error) { + req, err := lastResults.VirtualNetworkGatewayConnectionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ResetSharedKey the VirtualNetworkGatewayConnectionResetSharedKey operation +// resets the virtual network gateway connection shared key for passed +// virtual network gateway connection in the specified resource group through +// Network resource provider. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayConnectionName is the virtual network gateway +// connection reset shared key Name. parameters is parameters supplied to the +// Begin Reset Virtual Network Gateway connection shared key operation +// through Network resource provider. +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ResetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") + } + + resp, err := client.ResetSharedKeySender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure sending request") + } + + result, err = client.ResetSharedKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure responding to request") + } + + return +} + +// ResetSharedKeyPreparer prepares the ResetSharedKey request. +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ResetSharedKeySender sends the ResetSharedKey request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ResetSharedKeyResponder handles the response to the ResetSharedKey request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// SetSharedKey the Put VirtualNetworkGatewayConnectionSharedKey operation +// sets the virtual network gateway connection shared key for passed virtual +// network gateway connection in the specified resource group through Network +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayConnectionName is the virtual network gateway +// connection name. parameters is parameters supplied to the Begin Set +// Virtual Network Gateway conection Shared key operation throughNetwork +// resource provider. +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.SetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") + } + + resp, err := client.SetSharedKeySender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure sending request") + } + + result, err = client.SetSharedKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure responding to request") + } + + return +} + +// SetSharedKeyPreparer prepares the SetSharedKey request. +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// SetSharedKeySender sends the SetSharedKey request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// SetSharedKeyResponder handles the response to the SetSharedKey request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go new file mode 100644 index 000000000000..f272ccc725c6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go @@ -0,0 +1,471 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualNetworkGatewaysClient is the the Microsoft Azure Network management +// API provides a RESTful set of web services that interact with Microsoft +// Azure Networks service to manage your network resrources. The API has +// entities that capture the relationship between an end user and the +// Microsoft Azure Networks service. +type VirtualNetworkGatewaysClient struct { + ManagementClient +} + +// NewVirtualNetworkGatewaysClient creates an instance of the +// VirtualNetworkGatewaysClient client. +func NewVirtualNetworkGatewaysClient(subscriptionID string) VirtualNetworkGatewaysClient { + return VirtualNetworkGatewaysClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put VirtualNetworkGateway operation creates/updates a +// virtual network gateway in the specified resource group through Network +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayName is the name of the virtual network gateway. +// parameters is parameters supplied to the Begin Create or update Virtual +// Network Gateway operation through Network resource provider. +func (client VirtualNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete VirtualNetworkGateway operation deletes the specifed +// virtual network Gateway through Network resource provider. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayName is the name of the virtual network gateway. +func (client VirtualNetworkGatewaysClient) Delete(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Generatevpnclientpackage the Generatevpnclientpackage operation generates +// Vpn client package for P2S client of the virtual network gateway in the +// specified resource group through Network resource provider. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayName is the name of the virtual network gateway. +// parameters is parameters supplied to the Begin Generating Virtual Network +// Gateway Vpn client package operation through Network resource provider. +func (client VirtualNetworkGatewaysClient) Generatevpnclientpackage(resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result String, err error) { + req, err := client.GeneratevpnclientpackagePreparer(resourceGroupName, virtualNetworkGatewayName, parameters) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", nil, "Failure preparing request") + } + + resp, err := client.GeneratevpnclientpackageSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure sending request") + } + + result, err = client.GeneratevpnclientpackageResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure responding to request") + } + + return +} + +// GeneratevpnclientpackagePreparer prepares the Generatevpnclientpackage request. +func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackagePreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/generatevpnclientpackage", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GeneratevpnclientpackageSender sends the Generatevpnclientpackage request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GeneratevpnclientpackageResponder handles the response to the Generatevpnclientpackage request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(resp *http.Response) (result String, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get the Get VirtualNetworkGateway operation retrieves information about the +// specified virtual network gateway through Network resource provider. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayName is the name of the virtual network gateway. +func (client VirtualNetworkGatewaysClient) Get(resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGateway, err error) { + req, err := client.GetPreparer(resourceGroupName, virtualNetworkGatewayName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualNetworkGatewaysClient) GetPreparer(resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the List VirtualNetworkGateways opertion retrieves all the virtual +// network gateways stored. +// +// resourceGroupName is the name of the resource group. +func (client VirtualNetworkGatewaysClient) List(resourceGroupName string) (result VirtualNetworkGatewayListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualNetworkGatewaysClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) ListResponder(resp *http.Response) (result VirtualNetworkGatewayListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNetworkGatewayListResult) (result VirtualNetworkGatewayListResult, err error) { + req, err := lastResults.VirtualNetworkGatewayListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// Reset the Reset VirtualNetworkGateway operation resets the primary of the +// virtual network gateway in the specified resource group through Network +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. +// virtualNetworkGatewayName is the name of the virtual network gateway. +// parameters is parameters supplied to the Begin Reset Virtual Network +// Gateway operation through Network resource provider. +func (client VirtualNetworkGatewaysClient) Reset(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ResetPreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") + } + + resp, err := client.ResetSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure sending request") + } + + result, err = client.ResetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure responding to request") + } + + return +} + +// ResetPreparer prepares the Reset request. +func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/reset", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ResetSender sends the Reset request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) ResetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ResetResponder handles the response to the Reset request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go new file mode 100644 index 000000000000..9272610dd29c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go @@ -0,0 +1,414 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VirtualNetworksClient is the the Microsoft Azure Network management API +// provides a RESTful set of web services that interact with Microsoft Azure +// Networks service to manage your network resrources. The API has entities +// that capture the relationship between an end user and the Microsoft Azure +// Networks service. +type VirtualNetworksClient struct { + ManagementClient +} + +// NewVirtualNetworksClient creates an instance of the VirtualNetworksClient +// client. +func NewVirtualNetworksClient(subscriptionID string) VirtualNetworksClient { + return VirtualNetworksClient{New(subscriptionID)} +} + +// CreateOrUpdate the Put VirtualNetwork operation creates/updates a virtual +// network in the specified resource group. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. parameters is parameters supplied to the +// create/update Virtual Network operation +func (client VirtualNetworksClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, parameters, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure sending request") + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByClosing()) + result.Response = resp + return +} + +// Delete the Delete VirtualNetwork operation deletes the specifed virtual +// network This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. +func (client VirtualNetworksClient) Delete(resourceGroupName string, virtualNetworkName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, cancel) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", nil, "Failure preparing request") + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure sending request") + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, virtualNetworkName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworksClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get the Get VirtualNetwork operation retrieves information about the +// specified virtual network. +// +// resourceGroupName is the name of the resource group. virtualNetworkName is +// the name of the virtual network. expand is expand references resources. +func (client VirtualNetworksClient) Get(resourceGroupName string, virtualNetworkName string, expand string) (result VirtualNetwork, err error) { + req, err := client.GetPreparer(resourceGroupName, virtualNetworkName, expand) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", nil, "Failure preparing request") + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualNetworksClient) GetPreparer(resourceGroupName string, virtualNetworkName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkName": autorest.Encode("path", virtualNetworkName), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result VirtualNetwork, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List the list VirtualNetwork returns all Virtual Networks in a resource +// group +// +// resourceGroupName is the name of the resource group. +func (client VirtualNetworksClient) List(resourceGroupName string) (result VirtualNetworkListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing request") + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualNetworksClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { + req, err := lastResults.VirtualNetworkListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending next results request request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to next results request request") + } + + return +} + +// ListAll the list VirtualNetwork returns all Virtual Networks in a +// subscription +func (client VirtualNetworksClient) ListAll() (result VirtualNetworkListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client VirtualNetworksClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": client.APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworksClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) ListAllResponder(resp *http.Response) (result VirtualNetworkListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAllNextResults retrieves the next set of results, if any. +func (client VirtualNetworksClient) ListAllNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { + req, err := lastResults.VirtualNetworkListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing next results request request") + } + if req == nil { + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending next results request request") + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to next results request request") + } + + return +} diff --git a/vendor/github.com/stretchr/objx/LICENSE.md b/vendor/github.com/Azure/go-ansiterm/LICENSE similarity index 85% rename from vendor/github.com/stretchr/objx/LICENSE.md rename to vendor/github.com/Azure/go-ansiterm/LICENSE index 2199945813c8..e3d9a64d1d85 100644 --- a/vendor/github.com/stretchr/objx/LICENSE.md +++ b/vendor/github.com/Azure/go-ansiterm/LICENSE @@ -1,8 +1,6 @@ -objx - by Mat Ryer and Tyler Bunnell - The MIT License (MIT) -Copyright (c) 2014 Stretchr, Inc. +Copyright (c) 2015 Microsoft Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -11,13 +9,13 @@ 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 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. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md new file mode 100644 index 000000000000..e25e38210168 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/README.md @@ -0,0 +1,9 @@ +# go-ansiterm + +This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. + +For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. + +The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). + +See parser_test.go for examples exercising the state machine and generating appropriate function calls. diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go new file mode 100644 index 000000000000..ebfce8a8d38b --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/constants.go @@ -0,0 +1,188 @@ +package ansiterm + +const LogEnv = "DEBUG_TERMINAL" + +// ANSI constants +// References: +// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm +// -- http://man7.org/linux/man-pages/man4/console_codes.4.html +// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html +// -- http://en.wikipedia.org/wiki/ANSI_escape_code +// -- http://vt100.net/emu/dec_ansi_parser +// -- http://vt100.net/emu/vt500_parser.svg +// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html +// -- http://www.inwap.com/pdp10/ansicode.txt +const ( + // ECMA-48 Set Graphics Rendition + // Note: + // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved + // -- Fonts could possibly be supported via SetCurrentConsoleFontEx + // -- Windows does not expose the per-window cursor (i.e., caret) blink times + ANSI_SGR_RESET = 0 + ANSI_SGR_BOLD = 1 + ANSI_SGR_DIM = 2 + _ANSI_SGR_ITALIC = 3 + ANSI_SGR_UNDERLINE = 4 + _ANSI_SGR_BLINKSLOW = 5 + _ANSI_SGR_BLINKFAST = 6 + ANSI_SGR_REVERSE = 7 + _ANSI_SGR_INVISIBLE = 8 + _ANSI_SGR_LINETHROUGH = 9 + _ANSI_SGR_FONT_00 = 10 + _ANSI_SGR_FONT_01 = 11 + _ANSI_SGR_FONT_02 = 12 + _ANSI_SGR_FONT_03 = 13 + _ANSI_SGR_FONT_04 = 14 + _ANSI_SGR_FONT_05 = 15 + _ANSI_SGR_FONT_06 = 16 + _ANSI_SGR_FONT_07 = 17 + _ANSI_SGR_FONT_08 = 18 + _ANSI_SGR_FONT_09 = 19 + _ANSI_SGR_FONT_10 = 20 + _ANSI_SGR_DOUBLEUNDERLINE = 21 + ANSI_SGR_BOLD_DIM_OFF = 22 + _ANSI_SGR_ITALIC_OFF = 23 + ANSI_SGR_UNDERLINE_OFF = 24 + _ANSI_SGR_BLINK_OFF = 25 + _ANSI_SGR_RESERVED_00 = 26 + ANSI_SGR_REVERSE_OFF = 27 + _ANSI_SGR_INVISIBLE_OFF = 28 + _ANSI_SGR_LINETHROUGH_OFF = 29 + ANSI_SGR_FOREGROUND_BLACK = 30 + ANSI_SGR_FOREGROUND_RED = 31 + ANSI_SGR_FOREGROUND_GREEN = 32 + ANSI_SGR_FOREGROUND_YELLOW = 33 + ANSI_SGR_FOREGROUND_BLUE = 34 + ANSI_SGR_FOREGROUND_MAGENTA = 35 + ANSI_SGR_FOREGROUND_CYAN = 36 + ANSI_SGR_FOREGROUND_WHITE = 37 + _ANSI_SGR_RESERVED_01 = 38 + ANSI_SGR_FOREGROUND_DEFAULT = 39 + ANSI_SGR_BACKGROUND_BLACK = 40 + ANSI_SGR_BACKGROUND_RED = 41 + ANSI_SGR_BACKGROUND_GREEN = 42 + ANSI_SGR_BACKGROUND_YELLOW = 43 + ANSI_SGR_BACKGROUND_BLUE = 44 + ANSI_SGR_BACKGROUND_MAGENTA = 45 + ANSI_SGR_BACKGROUND_CYAN = 46 + ANSI_SGR_BACKGROUND_WHITE = 47 + _ANSI_SGR_RESERVED_02 = 48 + ANSI_SGR_BACKGROUND_DEFAULT = 49 + // 50 - 65: Unsupported + + ANSI_MAX_CMD_LENGTH = 4096 + + MAX_INPUT_EVENTS = 128 + DEFAULT_WIDTH = 80 + DEFAULT_HEIGHT = 24 + + ANSI_BEL = 0x07 + ANSI_BACKSPACE = 0x08 + ANSI_TAB = 0x09 + ANSI_LINE_FEED = 0x0A + ANSI_VERTICAL_TAB = 0x0B + ANSI_FORM_FEED = 0x0C + ANSI_CARRIAGE_RETURN = 0x0D + ANSI_ESCAPE_PRIMARY = 0x1B + ANSI_ESCAPE_SECONDARY = 0x5B + ANSI_OSC_STRING_ENTRY = 0x5D + ANSI_COMMAND_FIRST = 0x40 + ANSI_COMMAND_LAST = 0x7E + DCS_ENTRY = 0x90 + CSI_ENTRY = 0x9B + OSC_STRING = 0x9D + ANSI_PARAMETER_SEP = ";" + ANSI_CMD_G0 = '(' + ANSI_CMD_G1 = ')' + ANSI_CMD_G2 = '*' + ANSI_CMD_G3 = '+' + ANSI_CMD_DECPNM = '>' + ANSI_CMD_DECPAM = '=' + ANSI_CMD_OSC = ']' + ANSI_CMD_STR_TERM = '\\' + + KEY_CONTROL_PARAM_2 = ";2" + KEY_CONTROL_PARAM_3 = ";3" + KEY_CONTROL_PARAM_4 = ";4" + KEY_CONTROL_PARAM_5 = ";5" + KEY_CONTROL_PARAM_6 = ";6" + KEY_CONTROL_PARAM_7 = ";7" + KEY_CONTROL_PARAM_8 = ";8" + KEY_ESC_CSI = "\x1B[" + KEY_ESC_N = "\x1BN" + KEY_ESC_O = "\x1BO" + + FILL_CHARACTER = ' ' +) + +func getByteRange(start byte, end byte) []byte { + bytes := make([]byte, 0, 32) + for i := start; i <= end; i++ { + bytes = append(bytes, byte(i)) + } + + return bytes +} + +var ToGroundBytes = getToGroundBytes() +var Executors = getExecuteBytes() + +// SPACE 20+A0 hex Always and everywhere a blank space +// Intermediate 20-2F hex !"#$%&'()*+,-./ +var Intermeds = getByteRange(0x20, 0x2F) + +// Parameters 30-3F hex 0123456789:;<=>? +// CSI Parameters 30-39, 3B hex 0123456789; +var CsiParams = getByteRange(0x30, 0x3F) + +var CsiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) + +// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ +var UpperCase = getByteRange(0x40, 0x5F) + +// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ +var LowerCase = getByteRange(0x60, 0x7E) + +// Alphabetics 40-7E hex (all of upper and lower case) +var Alphabetics = append(UpperCase, LowerCase...) + +var Printables = getByteRange(0x20, 0x7F) + +var EscapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) +var EscapeToGroundBytes = getEscapeToGroundBytes() + +// See http://www.vt100.net/emu/vt500_parser.png for description of the complex +// byte ranges below + +func getEscapeToGroundBytes() []byte { + escapeToGroundBytes := getByteRange(0x30, 0x4F) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...) + escapeToGroundBytes = append(escapeToGroundBytes, 0x59) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5A) + escapeToGroundBytes = append(escapeToGroundBytes, 0x5C) + escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...) + return escapeToGroundBytes +} + +func getExecuteBytes() []byte { + executeBytes := getByteRange(0x00, 0x17) + executeBytes = append(executeBytes, 0x19) + executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...) + return executeBytes +} + +func getToGroundBytes() []byte { + groundBytes := []byte{0x18} + groundBytes = append(groundBytes, 0x1A) + groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...) + groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...) + groundBytes = append(groundBytes, 0x99) + groundBytes = append(groundBytes, 0x9A) + groundBytes = append(groundBytes, 0x9C) + return groundBytes +} + +// Delete 7F hex Always and everywhere ignored +// C1 Control 80-9F hex 32 additional control characters +// G1 Displayable A1-FE hex 94 additional displayable characters +// Special A0+FF hex Same as SPACE and DELETE diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go new file mode 100644 index 000000000000..d55cc2aec793 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/context.go @@ -0,0 +1,7 @@ +package ansiterm + +type AnsiContext struct { + currentChar byte + paramBuffer []byte + interBuffer []byte +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go new file mode 100644 index 000000000000..9fd4bd28e23f --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go @@ -0,0 +1,49 @@ +package ansiterm + +type CsiEntryState struct { + BaseState +} + +func (csiState CsiEntryState) Handle(b byte) (s State, e error) { + logger.Infof("CsiEntry::Handle %#x", b) + + nextState, err := csiState.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(Alphabetics, b): + return csiState.parser.Ground, nil + case sliceContains(CsiCollectables, b): + return csiState.parser.CsiParam, nil + case sliceContains(Executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState CsiEntryState) Transition(s State) error { + logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.BaseState.Transition(s) + + switch s { + case csiState.parser.Ground: + return csiState.parser.csiDispatch() + case csiState.parser.CsiParam: + switch { + case sliceContains(CsiParams, csiState.parser.context.currentChar): + csiState.parser.collectParam() + case sliceContains(Intermeds, csiState.parser.context.currentChar): + csiState.parser.collectInter() + } + } + + return nil +} + +func (csiState CsiEntryState) Enter() error { + csiState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go new file mode 100644 index 000000000000..27807dd35b99 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go @@ -0,0 +1,38 @@ +package ansiterm + +type CsiParamState struct { + BaseState +} + +func (csiState CsiParamState) Handle(b byte) (s State, e error) { + logger.Infof("CsiParam::Handle %#x", b) + + nextState, err := csiState.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(Alphabetics, b): + return csiState.parser.Ground, nil + case sliceContains(CsiCollectables, b): + csiState.parser.collectParam() + return csiState, nil + case sliceContains(Executors, b): + return csiState, csiState.parser.execute() + } + + return csiState, nil +} + +func (csiState CsiParamState) Transition(s State) error { + logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) + csiState.BaseState.Transition(s) + + switch s { + case csiState.parser.Ground: + return csiState.parser.csiDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go new file mode 100644 index 000000000000..b14e0ce97736 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go @@ -0,0 +1,36 @@ +package ansiterm + +type EscapeIntermediateState struct { + BaseState +} + +func (escState EscapeIntermediateState) Handle(b byte) (s State, e error) { + logger.Infof("EscapeIntermediateState::Handle %#x", b) + nextState, err := escState.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(Intermeds, b): + return escState, escState.parser.collectInter() + case sliceContains(Executors, b): + return escState, escState.parser.execute() + case sliceContains(EscapeIntermediateToGroundBytes, b): + return escState.parser.Ground, nil + } + + return escState, nil +} + +func (escState EscapeIntermediateState) Transition(s State) error { + logger.Infof("EscapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) + escState.BaseState.Transition(s) + + switch s { + case escState.parser.Ground: + return escState.parser.escDispatch() + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go new file mode 100644 index 000000000000..232dd8e0d17e --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go @@ -0,0 +1,47 @@ +package ansiterm + +type EscapeState struct { + BaseState +} + +func (escState EscapeState) Handle(b byte) (s State, e error) { + logger.Infof("EscapeState::Handle %#x", b) + nextState, err := escState.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case b == ANSI_ESCAPE_SECONDARY: + return escState.parser.CsiEntry, nil + case b == ANSI_OSC_STRING_ENTRY: + return escState.parser.OscString, nil + case sliceContains(Executors, b): + return escState, escState.parser.execute() + case sliceContains(EscapeToGroundBytes, b): + return escState.parser.Ground, nil + case sliceContains(Intermeds, b): + return escState.parser.EscapeIntermediate, nil + } + + return escState, nil +} + +func (escState EscapeState) Transition(s State) error { + logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name()) + escState.BaseState.Transition(s) + + switch s { + case escState.parser.Ground: + return escState.parser.escDispatch() + case escState.parser.EscapeIntermediate: + return escState.parser.collectInter() + } + + return nil +} + +func (escState EscapeState) Enter() error { + escState.parser.clear() + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go new file mode 100644 index 000000000000..98087b38c202 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/event_handler.go @@ -0,0 +1,90 @@ +package ansiterm + +type AnsiEventHandler interface { + // Print + Print(b byte) error + + // Execute C0 commands + Execute(b byte) error + + // CUrsor Up + CUU(int) error + + // CUrsor Down + CUD(int) error + + // CUrsor Forward + CUF(int) error + + // CUrsor Backward + CUB(int) error + + // Cursor to Next Line + CNL(int) error + + // Cursor to Previous Line + CPL(int) error + + // Cursor Horizontal position Absolute + CHA(int) error + + // Vertical line Position Absolute + VPA(int) error + + // CUrsor Position + CUP(int, int) error + + // Horizontal and Vertical Position (depends on PUM) + HVP(int, int) error + + // Text Cursor Enable Mode + DECTCEM(bool) error + + // Origin Mode + DECOM(bool) error + + // 132 Column Mode + DECCOLM(bool) error + + // Erase in Display + ED(int) error + + // Erase in Line + EL(int) error + + // Insert Line + IL(int) error + + // Delete Line + DL(int) error + + // Insert Character + ICH(int) error + + // Delete Character + DCH(int) error + + // Set Graphics Rendition + SGR([]int) error + + // Pan Down + SU(int) error + + // Pan Up + SD(int) error + + // Device Attributes + DA([]string) error + + // Set Top and Bottom Margins + DECSTBM(int, int) error + + // Index + IND() error + + // Reverse Index + RI() error + + // Flush updates from previous commands + Flush() error +} diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go new file mode 100644 index 000000000000..d600e3e4ae65 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/ground_state.go @@ -0,0 +1,24 @@ +package ansiterm + +type GroundState struct { + BaseState +} + +func (gs GroundState) Handle(b byte) (s State, e error) { + gs.parser.context.currentChar = b + + nextState, err := gs.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case sliceContains(Printables, b): + return gs, gs.parser.print() + + case sliceContains(Executors, b): + return gs, gs.parser.execute() + } + + return gs, nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go new file mode 100644 index 000000000000..4490e3cdf6b4 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go @@ -0,0 +1,31 @@ +package ansiterm + +type OscStringState struct { + BaseState +} + +func (oscState OscStringState) Handle(b byte) (s State, e error) { + logger.Infof("OscString::Handle %#x", b) + nextState, err := oscState.BaseState.Handle(b) + if nextState != nil || err != nil { + return nextState, err + } + + switch { + case isOscStringTerminator(b): + return oscState.parser.Ground, nil + } + + return oscState, nil +} + +// See below for OSC string terminators for linux +// http://man7.org/linux/man-pages/man4/console_codes.4.html +func isOscStringTerminator(b byte) bool { + + if b == ANSI_BEL || b == 0x5C { + return true + } + + return false +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go new file mode 100644 index 000000000000..ef5e0ad19984 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser.go @@ -0,0 +1,137 @@ +package ansiterm + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + + "github.com/Sirupsen/logrus" +) + +var logger *logrus.Logger + +type AnsiParser struct { + currState State + eventHandler AnsiEventHandler + context *AnsiContext + CsiEntry State + CsiParam State + DcsEntry State + Escape State + EscapeIntermediate State + Error State + Ground State + OscString State + stateMap []State +} + +func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser { + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("ansiParser.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.InfoLevel, + } + + parser := &AnsiParser{ + eventHandler: evtHandler, + context: &AnsiContext{}, + } + + parser.CsiEntry = CsiEntryState{BaseState{name: "CsiEntry", parser: parser}} + parser.CsiParam = CsiParamState{BaseState{name: "CsiParam", parser: parser}} + parser.DcsEntry = DcsEntryState{BaseState{name: "DcsEntry", parser: parser}} + parser.Escape = EscapeState{BaseState{name: "Escape", parser: parser}} + parser.EscapeIntermediate = EscapeIntermediateState{BaseState{name: "EscapeIntermediate", parser: parser}} + parser.Error = ErrorState{BaseState{name: "Error", parser: parser}} + parser.Ground = GroundState{BaseState{name: "Ground", parser: parser}} + parser.OscString = OscStringState{BaseState{name: "OscString", parser: parser}} + + parser.stateMap = []State{ + parser.CsiEntry, + parser.CsiParam, + parser.DcsEntry, + parser.Escape, + parser.EscapeIntermediate, + parser.Error, + parser.Ground, + parser.OscString, + } + + parser.currState = getState(initialState, parser.stateMap) + + logger.Infof("CreateParser: parser %p", parser) + return parser +} + +func getState(name string, states []State) State { + for _, el := range states { + if el.Name() == name { + return el + } + } + + return nil +} + +func (ap *AnsiParser) Parse(bytes []byte) (int, error) { + for i, b := range bytes { + if err := ap.handle(b); err != nil { + return i, err + } + } + + return len(bytes), ap.eventHandler.Flush() +} + +func (ap *AnsiParser) handle(b byte) error { + ap.context.currentChar = b + newState, err := ap.currState.Handle(b) + if err != nil { + return err + } + + if newState == nil { + logger.Warning("newState is nil") + return errors.New(fmt.Sprintf("New state of 'nil' is invalid.")) + } + + if newState != ap.currState { + if err := ap.changeState(newState); err != nil { + return err + } + } + + return nil +} + +func (ap *AnsiParser) changeState(newState State) error { + logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) + + // Exit old state + if err := ap.currState.Exit(); err != nil { + logger.Infof("Exit state '%s' failed with : '%v'", ap.currState.Name(), err) + return err + } + + // Perform transition action + if err := ap.currState.Transition(newState); err != nil { + logger.Infof("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) + return err + } + + // Enter new state + if err := newState.Enter(); err != nil { + logger.Infof("Enter state '%s' failed with: '%v'", newState.Name(), err) + return err + } + + ap.currState = newState + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go new file mode 100644 index 000000000000..438802097ddb --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go @@ -0,0 +1,103 @@ +package ansiterm + +import ( + "strconv" +) + +func parseParams(bytes []byte) ([]string, error) { + paramBuff := make([]byte, 0, 0) + params := []string{} + + for _, v := range bytes { + if v == ';' { + if len(paramBuff) > 0 { + // Completed parameter, append it to the list + s := string(paramBuff) + params = append(params, s) + paramBuff = make([]byte, 0, 0) + } + } else { + paramBuff = append(paramBuff, v) + } + } + + // Last parameter may not be terminated with ';' + if len(paramBuff) > 0 { + s := string(paramBuff) + params = append(params, s) + } + + logger.Infof("Parsed params: %v with length: %d", params, len(params)) + return params, nil +} + +func parseCmd(context AnsiContext) (string, error) { + return string(context.currentChar), nil +} + +func getInt(params []string, dflt int) int { + i := getInts(params, 1, dflt)[0] + logger.Infof("getInt: %v", i) + return i +} + +func getInts(params []string, minCount int, dflt int) []int { + ints := []int{} + + for _, v := range params { + i, _ := strconv.Atoi(v) + // Zero is mapped to the default value in VT100. + if i == 0 { + i = dflt + } + ints = append(ints, i) + } + + if len(ints) < minCount { + remaining := minCount - len(ints) + for i := 0; i < remaining; i++ { + ints = append(ints, dflt) + } + } + + logger.Infof("getInts: %v", ints) + + return ints +} + +func (ap *AnsiParser) modeDispatch(param string, set bool) error { + switch param { + case "?3": + return ap.eventHandler.DECCOLM(set) + case "?6": + return ap.eventHandler.DECOM(set) + case "?25": + return ap.eventHandler.DECTCEM(set) + } + return nil +} + +func (ap *AnsiParser) hDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], true) + } + + return nil +} + +func (ap *AnsiParser) lDispatch(params []string) error { + if len(params) == 1 { + return ap.modeDispatch(params[0], false) + } + + return nil +} + +func getEraseParam(params []string) int { + param := getInt(params, 0) + if param < 0 || 3 < param { + param = 0 + } + + return param +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go new file mode 100644 index 000000000000..260e6aae3c52 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go @@ -0,0 +1,122 @@ +package ansiterm + +import ( + "fmt" +) + +func (ap *AnsiParser) collectParam() error { + currChar := ap.context.currentChar + logger.Infof("collectParam %#x", currChar) + ap.context.paramBuffer = append(ap.context.paramBuffer, currChar) + return nil +} + +func (ap *AnsiParser) collectInter() error { + currChar := ap.context.currentChar + logger.Infof("collectInter %#x", currChar) + ap.context.paramBuffer = append(ap.context.interBuffer, currChar) + return nil +} + +func (ap *AnsiParser) escDispatch() error { + cmd, _ := parseCmd(*ap.context) + intermeds := ap.context.interBuffer + logger.Infof("escDispatch currentChar: %#x", ap.context.currentChar) + logger.Infof("escDispatch: %v(%v)", cmd, intermeds) + + switch cmd { + case "D": // IND + return ap.eventHandler.IND() + case "E": // NEL, equivalent to CRLF + err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN) + if err == nil { + err = ap.eventHandler.Execute(ANSI_LINE_FEED) + } + return err + case "M": // RI + return ap.eventHandler.RI() + } + + return nil +} + +func (ap *AnsiParser) csiDispatch() error { + cmd, _ := parseCmd(*ap.context) + params, _ := parseParams(ap.context.paramBuffer) + + logger.Infof("csiDispatch: %v(%v)", cmd, params) + + switch cmd { + case "@": + return ap.eventHandler.ICH(getInt(params, 1)) + case "A": + return ap.eventHandler.CUU(getInt(params, 1)) + case "B": + return ap.eventHandler.CUD(getInt(params, 1)) + case "C": + return ap.eventHandler.CUF(getInt(params, 1)) + case "D": + return ap.eventHandler.CUB(getInt(params, 1)) + case "E": + return ap.eventHandler.CNL(getInt(params, 1)) + case "F": + return ap.eventHandler.CPL(getInt(params, 1)) + case "G": + return ap.eventHandler.CHA(getInt(params, 1)) + case "H": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.CUP(x, y) + case "J": + param := getEraseParam(params) + return ap.eventHandler.ED(param) + case "K": + param := getEraseParam(params) + return ap.eventHandler.EL(param) + case "L": + return ap.eventHandler.IL(getInt(params, 1)) + case "M": + return ap.eventHandler.DL(getInt(params, 1)) + case "P": + return ap.eventHandler.DCH(getInt(params, 1)) + case "S": + return ap.eventHandler.SU(getInt(params, 1)) + case "T": + return ap.eventHandler.SD(getInt(params, 1)) + case "c": + return ap.eventHandler.DA(params) + case "d": + return ap.eventHandler.VPA(getInt(params, 1)) + case "f": + ints := getInts(params, 2, 1) + x, y := ints[0], ints[1] + return ap.eventHandler.HVP(x, y) + case "h": + return ap.hDispatch(params) + case "l": + return ap.lDispatch(params) + case "m": + return ap.eventHandler.SGR(getInts(params, 1, 0)) + case "r": + ints := getInts(params, 2, 1) + top, bottom := ints[0], ints[1] + return ap.eventHandler.DECSTBM(top, bottom) + default: + logger.Errorf(fmt.Sprintf("Unsupported CSI command: '%s', with full context: %v", cmd, ap.context)) + return nil + } + +} + +func (ap *AnsiParser) print() error { + return ap.eventHandler.Print(ap.context.currentChar) +} + +func (ap *AnsiParser) clear() error { + ap.context = &AnsiContext{} + return nil +} + +func (ap *AnsiParser) execute() error { + return ap.eventHandler.Execute(ap.context.currentChar) +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go new file mode 100644 index 000000000000..562f215d342d --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go @@ -0,0 +1,114 @@ +package ansiterm + +import ( + "fmt" + "testing" +) + +func getStateNames() []string { + parser, _ := createTestParser("Ground") + + stateNames := []string{} + for _, state := range parser.stateMap { + stateNames = append(stateNames, state.Name()) + } + + return stateNames +} + +func stateTransitionHelper(t *testing.T, start string, end string, bytes []byte) { + for _, b := range bytes { + bytes := []byte{byte(b)} + parser, _ := createTestParser(start) + parser.Parse(bytes) + validateState(t, parser.currState, end) + } +} + +func anyToXHelper(t *testing.T, bytes []byte, expectedState string) { + for _, s := range getStateNames() { + stateTransitionHelper(t, s, expectedState, bytes) + } +} + +func funcCallParamHelper(t *testing.T, bytes []byte, start string, expected string, expectedCalls []string) { + parser, evtHandler := createTestParser(start) + parser.Parse(bytes) + validateState(t, parser.currState, expected) + validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) +} + +func parseParamsHelper(t *testing.T, bytes []byte, expectedParams []string) { + params, err := parseParams(bytes) + + if err != nil { + t.Errorf("Parameter parse error: %v", err) + return + } + + if len(params) != len(expectedParams) { + t.Errorf("Parsed parameters: %v", params) + t.Errorf("Expected parameters: %v", expectedParams) + t.Errorf("Parameter length failure: %d != %d", len(params), len(expectedParams)) + return + } + + for i, v := range expectedParams { + if v != params[i] { + t.Errorf("Parsed parameters: %v", params) + t.Errorf("Expected parameters: %v", expectedParams) + t.Errorf("Parameter parse failure: %s != %s at position %d", v, params[i], i) + } + } +} + +func cursorSingleParamHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) +} + +func cursorTwoParamHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23 1])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) + funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) +} + +func eraseHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) + funcCallParamHelper(t, []byte{'3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([3])", funcName)}) + funcCallParamHelper(t, []byte{'4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) + funcCallParamHelper(t, []byte{'1', ';', '2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) +} + +func scrollHelper(t *testing.T, command byte, funcName string) { + funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) + funcCallParamHelper(t, []byte{'5', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([5])", funcName)}) + funcCallParamHelper(t, []byte{'4', ';', '6', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([4])", funcName)}) +} + +func clearOnStateChangeHelper(t *testing.T, start string, end string, bytes []byte) { + p, _ := createTestParser(start) + fillContext(p.context) + p.Parse(bytes) + validateState(t, p.currState, end) + validateEmptyContext(t, p.context) +} + +func c0Helper(t *testing.T, bytes []byte, expectedState string, expectedCalls []string) { + parser, evtHandler := createTestParser("Ground") + parser.Parse(bytes) + validateState(t, parser.currState, expectedState) + validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) +} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go b/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go new file mode 100644 index 000000000000..51d1d49bf03f --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go @@ -0,0 +1,66 @@ +package ansiterm + +import ( + "testing" +) + +func createTestParser(s string) (*AnsiParser, *TestAnsiEventHandler) { + evtHandler := CreateTestAnsiEventHandler() + parser := CreateParser(s, evtHandler) + + return parser, evtHandler +} + +func validateState(t *testing.T, actualState State, expectedStateName string) { + actualName := "Nil" + + if actualState != nil { + actualName = actualState.Name() + } + + if actualName != expectedStateName { + t.Errorf("Invalid State: '%s' != '%s'", actualName, expectedStateName) + } +} + +func validateFuncCalls(t *testing.T, actualCalls []string, expectedCalls []string) { + actualCount := len(actualCalls) + expectedCount := len(expectedCalls) + + if actualCount != expectedCount { + t.Errorf("Actual calls: %v", actualCalls) + t.Errorf("Expected calls: %v", expectedCalls) + t.Errorf("Call count error: %d != %d", actualCount, expectedCount) + return + } + + for i, v := range actualCalls { + if v != expectedCalls[i] { + t.Errorf("Actual calls: %v", actualCalls) + t.Errorf("Expected calls: %v", expectedCalls) + t.Errorf("Mismatched calls: %s != %s with lengths %d and %d", v, expectedCalls[i], len(v), len(expectedCalls[i])) + } + } +} + +func fillContext(context *AnsiContext) { + context.currentChar = 'A' + context.paramBuffer = []byte{'C', 'D', 'E'} + context.interBuffer = []byte{'F', 'G', 'H'} +} + +func validateEmptyContext(t *testing.T, context *AnsiContext) { + var expectedCurrChar byte = 0x0 + if context.currentChar != expectedCurrChar { + t.Errorf("Currentchar mismatch '%#x' != '%#x'", context.currentChar, expectedCurrChar) + } + + if len(context.paramBuffer) != 0 { + t.Errorf("Non-empty parameter buffer: %v", context.paramBuffer) + } + + if len(context.paramBuffer) != 0 { + t.Errorf("Non-empty intermediate buffer: %v", context.interBuffer) + } + +} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go new file mode 100644 index 000000000000..0cbdcb3c8345 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/states.go @@ -0,0 +1,71 @@ +package ansiterm + +type StateId int + +type State interface { + Enter() error + Exit() error + Handle(byte) (State, error) + Name() string + Transition(State) error +} + +type BaseState struct { + name string + parser *AnsiParser +} + +func (base BaseState) Enter() error { + return nil +} + +func (base BaseState) Exit() error { + return nil +} + +func (base BaseState) Handle(b byte) (s State, e error) { + + switch { + case b == CSI_ENTRY: + return base.parser.CsiEntry, nil + case b == DCS_ENTRY: + return base.parser.DcsEntry, nil + case b == ANSI_ESCAPE_PRIMARY: + return base.parser.Escape, nil + case b == OSC_STRING: + return base.parser.OscString, nil + case sliceContains(ToGroundBytes, b): + return base.parser.Ground, nil + } + + return nil, nil +} + +func (base BaseState) Name() string { + return base.name +} + +func (base BaseState) Transition(s State) error { + if s == base.parser.Ground { + execBytes := []byte{0x18} + execBytes = append(execBytes, 0x1A) + execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) + execBytes = append(execBytes, getByteRange(0x91, 0x97)...) + execBytes = append(execBytes, 0x99) + execBytes = append(execBytes, 0x9A) + + if sliceContains(execBytes, base.parser.context.currentChar) { + return base.parser.execute() + } + } + + return nil +} + +type DcsEntryState struct { + BaseState +} + +type ErrorState struct { + BaseState +} diff --git a/vendor/github.com/Azure/go-ansiterm/test_event_handler.go b/vendor/github.com/Azure/go-ansiterm/test_event_handler.go new file mode 100644 index 000000000000..60f9f30b98d7 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/test_event_handler.go @@ -0,0 +1,173 @@ +package ansiterm + +import ( + "fmt" + "strconv" +) + +type TestAnsiEventHandler struct { + FunctionCalls []string +} + +func CreateTestAnsiEventHandler() *TestAnsiEventHandler { + evtHandler := TestAnsiEventHandler{} + evtHandler.FunctionCalls = make([]string, 0) + return &evtHandler +} + +func (h *TestAnsiEventHandler) recordCall(call string, params []string) { + s := fmt.Sprintf("%s(%v)", call, params) + h.FunctionCalls = append(h.FunctionCalls, s) +} + +func (h *TestAnsiEventHandler) Print(b byte) error { + h.recordCall("Print", []string{string(b)}) + return nil +} + +func (h *TestAnsiEventHandler) Execute(b byte) error { + h.recordCall("Execute", []string{string(b)}) + return nil +} + +func (h *TestAnsiEventHandler) CUU(param int) error { + h.recordCall("CUU", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUD(param int) error { + h.recordCall("CUD", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUF(param int) error { + h.recordCall("CUF", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUB(param int) error { + h.recordCall("CUB", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CNL(param int) error { + h.recordCall("CNL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CPL(param int) error { + h.recordCall("CPL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CHA(param int) error { + h.recordCall("CHA", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) VPA(param int) error { + h.recordCall("VPA", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) CUP(x int, y int) error { + xS, yS := strconv.Itoa(x), strconv.Itoa(y) + h.recordCall("CUP", []string{xS, yS}) + return nil +} + +func (h *TestAnsiEventHandler) HVP(x int, y int) error { + xS, yS := strconv.Itoa(x), strconv.Itoa(y) + h.recordCall("HVP", []string{xS, yS}) + return nil +} + +func (h *TestAnsiEventHandler) DECTCEM(visible bool) error { + h.recordCall("DECTCEM", []string{strconv.FormatBool(visible)}) + return nil +} + +func (h *TestAnsiEventHandler) DECOM(visible bool) error { + h.recordCall("DECOM", []string{strconv.FormatBool(visible)}) + return nil +} + +func (h *TestAnsiEventHandler) DECCOLM(use132 bool) error { + h.recordCall("DECOLM", []string{strconv.FormatBool(use132)}) + return nil +} + +func (h *TestAnsiEventHandler) ED(param int) error { + h.recordCall("ED", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) EL(param int) error { + h.recordCall("EL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) IL(param int) error { + h.recordCall("IL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DL(param int) error { + h.recordCall("DL", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) ICH(param int) error { + h.recordCall("ICH", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DCH(param int) error { + h.recordCall("DCH", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) SGR(params []int) error { + strings := []string{} + for _, v := range params { + strings = append(strings, strconv.Itoa(v)) + } + + h.recordCall("SGR", strings) + return nil +} + +func (h *TestAnsiEventHandler) SU(param int) error { + h.recordCall("SU", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) SD(param int) error { + h.recordCall("SD", []string{strconv.Itoa(param)}) + return nil +} + +func (h *TestAnsiEventHandler) DA(params []string) error { + h.recordCall("DA", params) + return nil +} + +func (h *TestAnsiEventHandler) DECSTBM(top int, bottom int) error { + topS, bottomS := strconv.Itoa(top), strconv.Itoa(bottom) + h.recordCall("DECSTBM", []string{topS, bottomS}) + return nil +} + +func (h *TestAnsiEventHandler) RI() error { + h.recordCall("RI", nil) + return nil +} + +func (h *TestAnsiEventHandler) IND() error { + h.recordCall("IND", nil) + return nil +} + +func (h *TestAnsiEventHandler) Flush() error { + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go new file mode 100644 index 000000000000..392114493a22 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/utilities.go @@ -0,0 +1,21 @@ +package ansiterm + +import ( + "strconv" +) + +func sliceContains(bytes []byte, b byte) bool { + for _, v := range bytes { + if v == b { + return true + } + } + + return false +} + +func convertBytesToInteger(bytes []byte) int { + s := string(bytes) + i, _ := strconv.Atoi(s) + return i +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go new file mode 100644 index 000000000000..78fe92fe65f1 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -0,0 +1,182 @@ +// +build windows + +package winterm + +import ( + "fmt" + "os" + "strconv" + "strings" + "syscall" + + . "github.com/Azure/go-ansiterm" +) + +// Windows keyboard constants +// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. +const ( + VK_PRIOR = 0x21 // PAGE UP key + VK_NEXT = 0x22 // PAGE DOWN key + VK_END = 0x23 // END key + VK_HOME = 0x24 // HOME key + VK_LEFT = 0x25 // LEFT ARROW key + VK_UP = 0x26 // UP ARROW key + VK_RIGHT = 0x27 // RIGHT ARROW key + VK_DOWN = 0x28 // DOWN ARROW key + VK_SELECT = 0x29 // SELECT key + VK_PRINT = 0x2A // PRINT key + VK_EXECUTE = 0x2B // EXECUTE key + VK_SNAPSHOT = 0x2C // PRINT SCREEN key + VK_INSERT = 0x2D // INS key + VK_DELETE = 0x2E // DEL key + VK_HELP = 0x2F // HELP key + VK_F1 = 0x70 // F1 key + VK_F2 = 0x71 // F2 key + VK_F3 = 0x72 // F3 key + VK_F4 = 0x73 // F4 key + VK_F5 = 0x74 // F5 key + VK_F6 = 0x75 // F6 key + VK_F7 = 0x76 // F7 key + VK_F8 = 0x77 // F8 key + VK_F9 = 0x78 // F9 key + VK_F10 = 0x79 // F10 key + VK_F11 = 0x7A // F11 key + VK_F12 = 0x7B // F12 key + + RIGHT_ALT_PRESSED = 0x0001 + LEFT_ALT_PRESSED = 0x0002 + RIGHT_CTRL_PRESSED = 0x0004 + LEFT_CTRL_PRESSED = 0x0008 + SHIFT_PRESSED = 0x0010 + NUMLOCK_ON = 0x0020 + SCROLLLOCK_ON = 0x0040 + CAPSLOCK_ON = 0x0080 + ENHANCED_KEY = 0x0100 +) + +type ansiCommand struct { + CommandBytes []byte + Command string + Parameters []string + IsSpecial bool +} + +func newAnsiCommand(command []byte) *ansiCommand { + + if isCharacterSelectionCmdChar(command[1]) { + // Is Character Set Selection commands + return &ansiCommand{ + CommandBytes: command, + Command: string(command), + IsSpecial: true, + } + } + + // last char is command character + lastCharIndex := len(command) - 1 + + ac := &ansiCommand{ + CommandBytes: command, + Command: string(command[lastCharIndex]), + IsSpecial: false, + } + + // more than a single escape + if lastCharIndex != 0 { + start := 1 + // skip if double char escape sequence + if command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { + start++ + } + // convert this to GetNextParam method + ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) + } + + return ac +} + +func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT { + if index < 0 || index >= len(ac.Parameters) { + return defaultValue + } + + param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) + if err != nil { + return defaultValue + } + + return SHORT(param) +} + +func (ac *ansiCommand) String() string { + return fmt.Sprintf("0x%v \"%v\" (\"%v\")", + bytesToHex(ac.CommandBytes), + ac.Command, + strings.Join(ac.Parameters, "\",\"")) +} + +// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. +// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. +func isAnsiCommandChar(b byte) bool { + switch { + case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: + return true + case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: + // non-CSI escape sequence terminator + return true + case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: + // String escape sequence terminator + return true + } + return false +} + +func isXtermOscSequence(command []byte, current byte) bool { + return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) +} + +func isCharacterSelectionCmdChar(b byte) bool { + return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) +} + +// bytesToHex converts a slice of bytes to a human-readable string. +func bytesToHex(b []byte) string { + hex := make([]string, len(b)) + for i, ch := range b { + hex[i] = fmt.Sprintf("%X", ch) + } + return strings.Join(hex, "") +} + +// ensureInRange adjusts the passed value, if necessary, to ensure it is within +// the passed min / max range. +func ensureInRange(n SHORT, min SHORT, max SHORT) SHORT { + if n < min { + return min + } else if n > max { + return max + } else { + return n + } +} + +func GetStdFile(nFile int) (*os.File, uintptr) { + var file *os.File + switch nFile { + case syscall.STD_INPUT_HANDLE: + file = os.Stdin + case syscall.STD_OUTPUT_HANDLE: + file = os.Stdout + case syscall.STD_ERROR_HANDLE: + file = os.Stderr + default: + panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) + } + + fd, err := syscall.GetStdHandle(nFile) + if err != nil { + panic(fmt.Errorf("Invalid standard handle indentifier: %v -- %v", nFile, err)) + } + + return file, uintptr(fd) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go new file mode 100644 index 000000000000..1f2f3853cc4e --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -0,0 +1,329 @@ +// +build windows + +package winterm + +import ( + "fmt" + "syscall" + "unsafe" +) + +//=========================================================================================================== +// IMPORTANT NOTE: +// +// The methods below make extensive use of the "unsafe" package to obtain the required pointers. +// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack +// variables) the pointers reference *before* the API completes. +// +// As a result, in those cases, the code must hint that the variables remain in active by invoking the +// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer +// require unsafe pointers. +// +// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform +// the garbage collector the variables remain in use if: +// +// -- The value is not a pointer (e.g., int32, struct) +// -- The value is not referenced by the method after passing the pointer to Windows +// +// See http://golang.org/doc/go1.3. +//=========================================================================================================== + +var ( + kernel32DLL = syscall.NewLazyDLL("kernel32.dll") + + getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") + setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") + setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") + setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") + getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") + setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") + scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA") + setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") + setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") + writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") + readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") + waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject") +) + +// Windows Console constants +const ( + // Console modes + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. + ENABLE_PROCESSED_INPUT = 0x0001 + ENABLE_LINE_INPUT = 0x0002 + ENABLE_ECHO_INPUT = 0x0004 + ENABLE_WINDOW_INPUT = 0x0008 + ENABLE_MOUSE_INPUT = 0x0010 + ENABLE_INSERT_MODE = 0x0020 + ENABLE_QUICK_EDIT_MODE = 0x0040 + ENABLE_EXTENDED_FLAGS = 0x0080 + + ENABLE_PROCESSED_OUTPUT = 0x0001 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 + + // Character attributes + // Note: + // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). + // Clearing all foreground or background colors results in black; setting all creates white. + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. + FOREGROUND_BLUE WORD = 0x0001 + FOREGROUND_GREEN WORD = 0x0002 + FOREGROUND_RED WORD = 0x0004 + FOREGROUND_INTENSITY WORD = 0x0008 + FOREGROUND_MASK WORD = 0x000F + + BACKGROUND_BLUE WORD = 0x0010 + BACKGROUND_GREEN WORD = 0x0020 + BACKGROUND_RED WORD = 0x0040 + BACKGROUND_INTENSITY WORD = 0x0080 + BACKGROUND_MASK WORD = 0x00F0 + + COMMON_LVB_MASK WORD = 0xFF00 + COMMON_LVB_REVERSE_VIDEO WORD = 0x4000 + COMMON_LVB_UNDERSCORE WORD = 0x8000 + + // Input event types + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + KEY_EVENT = 0x0001 + MOUSE_EVENT = 0x0002 + WINDOW_BUFFER_SIZE_EVENT = 0x0004 + MENU_EVENT = 0x0008 + FOCUS_EVENT = 0x0010 + + // WaitForSingleObject return codes + WAIT_ABANDONED = 0x00000080 + WAIT_FAILED = 0xFFFFFFFF + WAIT_SIGNALED = 0x0000000 + WAIT_TIMEOUT = 0x00000102 + + // WaitForSingleObject wait duration + WAIT_INFINITE = 0xFFFFFFFF + WAIT_ONE_SECOND = 1000 + WAIT_HALF_SECOND = 500 + WAIT_QUARTER_SECOND = 250 +) + +// Windows API Console types +// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx for core types (e.g., SHORT) +// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) +// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment +type ( + SHORT int16 + BOOL int32 + WORD uint16 + WCHAR uint16 + DWORD uint32 + + CHAR_INFO struct { + UnicodeChar WCHAR + Attributes WORD + } + + CONSOLE_CURSOR_INFO struct { + Size DWORD + Visible BOOL + } + + CONSOLE_SCREEN_BUFFER_INFO struct { + Size COORD + CursorPosition COORD + Attributes WORD + Window SMALL_RECT + MaximumWindowSize COORD + } + + COORD struct { + X SHORT + Y SHORT + } + + SMALL_RECT struct { + Left SHORT + Top SHORT + Right SHORT + Bottom SHORT + } + + // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest + // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. + INPUT_RECORD struct { + EventType WORD + KeyEvent KEY_EVENT_RECORD + } + + KEY_EVENT_RECORD struct { + KeyDown BOOL + RepeatCount WORD + VirtualKeyCode WORD + VirtualScanCode WORD + UnicodeChar WCHAR + ControlKeyState DWORD + } + + WINDOW_BUFFER_SIZE struct { + Size COORD + } +) + +// boolToBOOL converts a Go bool into a Windows BOOL. +func boolToBOOL(f bool) BOOL { + if f { + return BOOL(1) + } else { + return BOOL(0) + } +} + +// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx. +func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorInfo sets the size and visiblity of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx. +func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { + r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) + return checkError(r1, r2, err) +} + +// SetConsoleCursorPosition location of the console cursor. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx. +func SetConsoleCursorPosition(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// GetConsoleMode gets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx. +func GetConsoleMode(handle uintptr) (mode uint32, err error) { + err = syscall.GetConsoleMode(syscall.Handle(handle), &mode) + return mode, err +} + +// SetConsoleMode sets the console mode for given file descriptor +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. +func SetConsoleMode(handle uintptr, mode uint32) error { + r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0) + use(mode) + return checkError(r1, r2, err) +} + +// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx. +func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { + info := CONSOLE_SCREEN_BUFFER_INFO{} + err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)) + if err != nil { + return nil, err + } + return &info, nil +} + +func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error { + r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char))) + use(scrollRect) + use(clipRect) + use(destOrigin) + use(char) + return checkError(r1, r2, err) +} + +// SetConsoleScreenBufferSize sets the size of the console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx. +func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { + r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord)) + use(coord) + return checkError(r1, r2, err) +} + +// SetConsoleTextAttribute sets the attributes of characters written to the +// console screen buffer by the WriteFile or WriteConsole function. +// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. +func SetConsoleTextAttribute(handle uintptr, attribute WORD) error { + r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) + use(attribute) + return checkError(r1, r2, err) +} + +// SetConsoleWindowInfo sets the size and position of the console screen buffer's window. +// Note that the size and location must be within and no larger than the backing console screen buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx. +func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error { + r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect))) + use(isAbsolute) + use(rect) + return checkError(r1, r2, err) +} + +// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx. +func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error { + r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion))) + use(buffer) + use(bufferSize) + use(bufferCoord) + return checkError(r1, r2, err) +} + +// ReadConsoleInput reads (and removes) data from the console input buffer. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx. +func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error { + r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count))) + use(buffer) + return checkError(r1, r2, err) +} + +// WaitForSingleObject waits for the passed handle to be signaled. +// It returns true if the handle was signaled; false otherwise. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. +func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { + r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(DWORD(msWait))) + switch r1 { + case WAIT_ABANDONED, WAIT_TIMEOUT: + return false, nil + case WAIT_SIGNALED: + return true, nil + } + use(msWait) + return false, err +} + +// String helpers +func (info CONSOLE_SCREEN_BUFFER_INFO) String() string { + return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize) +} + +func (coord COORD) String() string { + return fmt.Sprintf("%v,%v", coord.X, coord.Y) +} + +func (rect SMALL_RECT) String() string { + return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom) +} + +// checkError evaluates the results of a Windows API call and returns the error if it failed. +func checkError(r1, r2 uintptr, err error) error { + // Windows APIs return non-zero to indicate success + if r1 != 0 { + return nil + } + + // Return the error if provided, otherwise default to EINVAL + if err != nil { + return err + } + return syscall.EINVAL +} + +// coordToPointer converts a COORD into a uintptr (by fooling the type system). +func coordToPointer(c COORD) uintptr { + // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to DWORD is just to get a pointer to pass. + return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) +} + +// use is a no-op, but the compiler cannot see that it is. +// Calling use(p) ensures that p is kept live until that point. +func use(p interface{}) {} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go new file mode 100644 index 000000000000..94665db6fb0c --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -0,0 +1,102 @@ +// +build windows + +package winterm + +import ( + . "github.com/Azure/go-ansiterm" +) + +const ( + FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE +) + +// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the +// request represented by the passed ANSI mode. +func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode WORD, ansiMode SHORT) (WORD, bool) { + switch ansiMode { + + // Mode styles + case ANSI_SGR_BOLD: + windowsMode = windowsMode | FOREGROUND_INTENSITY + + case ANSI_SGR_DIM, ANSI_SGR_BOLD_DIM_OFF: + windowsMode &^= FOREGROUND_INTENSITY + + case ANSI_SGR_UNDERLINE: + windowsMode = windowsMode | COMMON_LVB_UNDERSCORE + + case ANSI_SGR_REVERSE: + inverted = true + + case ANSI_SGR_REVERSE_OFF: + inverted = false + + case ANSI_SGR_UNDERLINE_OFF: + windowsMode &^= COMMON_LVB_UNDERSCORE + + // Foreground colors + case ANSI_SGR_FOREGROUND_DEFAULT: + windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) + + case ANSI_SGR_FOREGROUND_BLACK: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) + + case ANSI_SGR_FOREGROUND_RED: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED + + case ANSI_SGR_FOREGROUND_GREEN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN + + case ANSI_SGR_FOREGROUND_YELLOW: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN + + case ANSI_SGR_FOREGROUND_BLUE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE + + case ANSI_SGR_FOREGROUND_MAGENTA: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE + + case ANSI_SGR_FOREGROUND_CYAN: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE + + case ANSI_SGR_FOREGROUND_WHITE: + windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + + // Background colors + case ANSI_SGR_BACKGROUND_DEFAULT: + // Black with no intensity + windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) + + case ANSI_SGR_BACKGROUND_BLACK: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) + + case ANSI_SGR_BACKGROUND_RED: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED + + case ANSI_SGR_BACKGROUND_GREEN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN + + case ANSI_SGR_BACKGROUND_YELLOW: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN + + case ANSI_SGR_BACKGROUND_BLUE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE + + case ANSI_SGR_BACKGROUND_MAGENTA: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE + + case ANSI_SGR_BACKGROUND_CYAN: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE + + case ANSI_SGR_BACKGROUND_WHITE: + windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE + } + + return windowsMode, inverted +} + +// invertAttributes inverts the foreground and background colors of a Windows attributes value +func invertAttributes(windowsMode WORD) WORD { + return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go new file mode 100644 index 000000000000..e4b1c255a463 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -0,0 +1,101 @@ +// +build windows + +package winterm + +const ( + Horizontal = iota + Vertical +) + +func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { + if h.originMode { + sr := h.effectiveSr(info.Window) + return SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + } else { + return SMALL_RECT{ + Top: info.Window.Top, + Bottom: info.Window.Bottom, + Left: 0, + Right: info.Size.X - 1, + } + } +} + +// setCursorPosition sets the cursor to the specified position, bounded to the screen size +func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { + position.X = ensureInRange(position.X, window.Left, window.Right) + position.Y = ensureInRange(position.Y, window.Top, window.Bottom) + err := SetConsoleCursorPosition(h.fd, position) + if err != nil { + return err + } + logger.Infof("Cursor position set: (%d, %d)", position.X, position.Y) + return err +} + +func (h *WindowsAnsiEventHandler) moveCursorVertical(param int) error { + return h.moveCursor(Vertical, param) +} + +func (h *WindowsAnsiEventHandler) moveCursorHorizontal(param int) error { + return h.moveCursor(Horizontal, param) +} + +func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + switch moveMode { + case Horizontal: + position.X += SHORT(param) + case Vertical: + position.Y += SHORT(param) + } + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = 0 + position.Y += SHORT(param) + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} + +func (h *WindowsAnsiEventHandler) moveCursorColumn(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + position := info.CursorPosition + position.X = SHORT(param) - 1 + + if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go new file mode 100644 index 000000000000..f02a5b261b54 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -0,0 +1,86 @@ +// +build windows + +package winterm + +import ( + . "github.com/Azure/go-ansiterm" +) + +func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, toCoord COORD) error { + // Ignore an invalid (negative area) request + if toCoord.Y < fromCoord.Y { + return nil + } + + var err error + + var coordStart = COORD{} + var coordEnd = COORD{} + + xCurrent, yCurrent := fromCoord.X, fromCoord.Y + xEnd, yEnd := toCoord.X, toCoord.Y + + // Clear any partial initial line + if xCurrent > 0 { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yCurrent + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent += 1 + } + + // Clear intervening rectangular section + if yCurrent < yEnd { + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd-1 + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + xCurrent = 0 + yCurrent = yEnd + } + + // Clear remaining partial ending line + coordStart.X, coordStart.Y = xCurrent, yCurrent + coordEnd.X, coordEnd.Y = xEnd, yEnd + + err = h.clearRect(attributes, coordStart, coordEnd) + if err != nil { + return err + } + + return nil +} + +func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, toCoord COORD) error { + region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} + width := toCoord.X - fromCoord.X + 1 + height := toCoord.Y - fromCoord.Y + 1 + size := uint32(width) * uint32(height) + + if size <= 0 { + return nil + } + + buffer := make([]CHAR_INFO, size) + + char := CHAR_INFO{WCHAR(FILL_CHARACTER), attributes} + for i := 0; i < int(size); i++ { + buffer[i] = char + } + + err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, ®ion) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go new file mode 100644 index 000000000000..ed1998245c07 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -0,0 +1,118 @@ +// +build windows + +package winterm + +// effectiveSr gets the current effective scroll region in buffer coordinates +func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { + top := AddInRange(window.Top, h.sr.top, window.Top, window.Bottom) + bottom := AddInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) + if top >= bottom { + top = window.Top + bottom = window.Bottom + } + return scrollRegion{top: top, bottom: bottom} +} + +func (h *WindowsAnsiEventHandler) scrollUp(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + return h.scroll(param, sr, info) +} + +func (h *WindowsAnsiEventHandler) scrollDown(param int) error { + return h.scrollUp(-param) +} + +func (h *WindowsAnsiEventHandler) deleteLines(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + start := info.CursorPosition.Y + sr := h.effectiveSr(info.Window) + // Lines cannot be inserted or deleted outside the scrolling region. + if start >= sr.top && start <= sr.bottom { + sr.top = start + return h.scroll(param, sr, info) + } else { + return nil + } +} + +func (h *WindowsAnsiEventHandler) insertLines(param int) error { + return h.deleteLines(-param) +} + +// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. +func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { + logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) + logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) + + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: sr.top, + Bottom: sr.bottom, + Left: 0, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: 0, + Y: sr.top - SHORT(param), + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} + +func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + return h.scrollLine(param, info.CursorPosition, info) +} + +func (h *WindowsAnsiEventHandler) insertCharacters(param int) error { + return h.deleteCharacters(-param) +} + +// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. +func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { + // Copy from and clip to the scroll region (full buffer width) + scrollRect := SMALL_RECT{ + Top: position.Y, + Bottom: position.Y, + Left: position.X, + Right: info.Size.X - 1, + } + + // Origin to which area should be copied + destOrigin := COORD{ + X: position.X - SHORT(columns), + Y: position.Y, + } + + char := CHAR_INFO{ + UnicodeChar: ' ', + Attributes: h.attributes, + } + + if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go new file mode 100644 index 000000000000..2f963ff132d1 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -0,0 +1,9 @@ +// +build windows + +package winterm + +// AddInRange increments a value by the passed quantity while ensuring the values +// always remain within the supplied min / max range. +func AddInRange(n SHORT, increment SHORT, min SHORT, max SHORT) SHORT { + return ensureInRange(n+increment, min, max) +} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go new file mode 100644 index 000000000000..2d492b32e422 --- /dev/null +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -0,0 +1,725 @@ +// +build windows + +package winterm + +import ( + "bytes" + "io/ioutil" + "os" + "strconv" + + . "github.com/Azure/go-ansiterm" + "github.com/Sirupsen/logrus" +) + +var logger *logrus.Logger + +type WindowsAnsiEventHandler struct { + fd uintptr + file *os.File + infoReset *CONSOLE_SCREEN_BUFFER_INFO + sr scrollRegion + buffer bytes.Buffer + attributes WORD + inverted bool + wrapNext bool + drewMarginByte bool + originMode bool + marginByte byte + curInfo *CONSOLE_SCREEN_BUFFER_INFO + curPos COORD +} + +func CreateWinEventHandler(fd uintptr, file *os.File) AnsiEventHandler { + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("winEventHandler.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.DebugLevel, + } + + infoReset, err := GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil + } + + return &WindowsAnsiEventHandler{ + fd: fd, + file: file, + infoReset: infoReset, + attributes: infoReset.Attributes, + } +} + +type scrollRegion struct { + top SHORT + bottom SHORT +} + +// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the +// current cursor position and scroll region settings, in which case it returns +// true. If no special handling is necessary, then it does nothing and returns +// false. +// +// In the false case, the caller should ensure that a carriage return +// and line feed are inserted or that the text is otherwise wrapped. +func (h *WindowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { + if h.wrapNext { + if err := h.Flush(); err != nil { + return false, err + } + h.clearWrap() + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return false, err + } + sr := h.effectiveSr(info.Window) + if pos.Y == sr.bottom { + // Scrolling is necessary. Let Windows automatically scroll if the scrolling region + // is the full window. + if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom { + if includeCR { + pos.X = 0 + h.updatePos(pos) + } + return false, nil + } else { + // A custom scroll region is active. Scroll the window manually to simulate + // the LF. + if err := h.Flush(); err != nil { + return false, err + } + logger.Info("Simulating LF inside scroll region") + if err := h.scrollUp(1); err != nil { + return false, err + } + if includeCR { + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + } + } else if pos.Y < info.Window.Bottom { + // Let Windows handle the LF. + pos.Y++ + if includeCR { + pos.X = 0 + } + h.updatePos(pos) + return false, nil + } else { + // The cursor is at the bottom of the screen but outside the scroll + // region. Skip the LF. + logger.Info("Simulating LF outside scroll region") + if includeCR { + if err := h.Flush(); err != nil { + return false, err + } + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return false, err + } + } + return true, nil + } +} + +// executeLF executes a LF without a CR. +func (h *WindowsAnsiEventHandler) executeLF() error { + handled, err := h.simulateLF(false) + if err != nil { + return err + } + if !handled { + // Windows LF will reset the cursor column position. Write the LF + // and restore the cursor position. + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + h.buffer.WriteByte(ANSI_LINE_FEED) + if pos.X != 0 { + if err := h.Flush(); err != nil { + return err + } + logger.Info("Resetting cursor position for LF without CR") + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + } + return nil +} + +func (h *WindowsAnsiEventHandler) Print(b byte) error { + if h.wrapNext { + h.buffer.WriteByte(h.marginByte) + h.clearWrap() + if _, err := h.simulateLF(true); err != nil { + return err + } + } + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X == info.Size.X-1 { + h.wrapNext = true + h.marginByte = b + } else { + pos.X++ + h.updatePos(pos) + h.buffer.WriteByte(b) + } + return nil +} + +func (h *WindowsAnsiEventHandler) Execute(b byte) error { + switch b { + case ANSI_TAB: + logger.Info("Execute(TAB)") + // Move to the next tab stop, but preserve auto-wrap if already set. + if !h.wrapNext { + pos, info, err := h.getCurrentInfo() + if err != nil { + return err + } + pos.X = (pos.X + 8) - pos.X%8 + if pos.X >= info.Size.X { + pos.X = info.Size.X - 1 + } + if err := h.Flush(); err != nil { + return err + } + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + } + return nil + + case ANSI_BEL: + h.buffer.WriteByte(ANSI_BEL) + return nil + + case ANSI_BACKSPACE: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X > 0 { + pos.X-- + h.updatePos(pos) + h.buffer.WriteByte(ANSI_BACKSPACE) + } + return nil + + case ANSI_VERTICAL_TAB, ANSI_FORM_FEED: + // Treat as true LF. + return h.executeLF() + + case ANSI_LINE_FEED: + // Simulate a CR and LF for now since there is no way in go-ansiterm + // to tell if the LF should include CR (and more things break when it's + // missing than when it's incorrectly added). + handled, err := h.simulateLF(true) + if handled || err != nil { + return err + } + return h.buffer.WriteByte(ANSI_LINE_FEED) + + case ANSI_CARRIAGE_RETURN: + if h.wrapNext { + if err := h.Flush(); err != nil { + return err + } + h.clearWrap() + } + pos, _, err := h.getCurrentInfo() + if err != nil { + return err + } + if pos.X != 0 { + pos.X = 0 + h.updatePos(pos) + h.buffer.WriteByte(ANSI_CARRIAGE_RETURN) + } + return nil + + default: + return nil + } +} + +func (h *WindowsAnsiEventHandler) CUU(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(-param) +} + +func (h *WindowsAnsiEventHandler) CUD(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorVertical(param) +} + +func (h *WindowsAnsiEventHandler) CUF(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUF: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(param) +} + +func (h *WindowsAnsiEventHandler) CUB(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUB: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorHorizontal(-param) +} + +func (h *WindowsAnsiEventHandler) CNL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CNL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(param) +} + +func (h *WindowsAnsiEventHandler) CPL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CPL: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorLine(-param) +} + +func (h *WindowsAnsiEventHandler) CHA(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CHA: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.moveCursorColumn(param) +} + +func (h *WindowsAnsiEventHandler) VPA(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("VPA: [[%d]]", param) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + window := h.getCursorWindow(info) + position := info.CursorPosition + position.Y = window.Top + SHORT(param) - 1 + return h.setCursorPosition(position, window) +} + +func (h *WindowsAnsiEventHandler) CUP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("CUP: [[%d %d]]", row, col) + h.clearWrap() + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + window := h.getCursorWindow(info) + position := COORD{window.Left + SHORT(col) - 1, window.Top + SHORT(row) - 1} + return h.setCursorPosition(position, window) +} + +func (h *WindowsAnsiEventHandler) HVP(row int, col int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("HVP: [[%d %d]]", row, col) + h.clearWrap() + return h.CUP(row, col) +} + +func (h *WindowsAnsiEventHandler) DECTCEM(visible bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECTCEM: [%v]", []string{strconv.FormatBool(visible)}) + h.clearWrap() + return nil +} + +func (h *WindowsAnsiEventHandler) DECOM(enable bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECOM: [%v]", []string{strconv.FormatBool(enable)}) + h.clearWrap() + h.originMode = enable + return h.CUP(1, 1) +} + +func (h *WindowsAnsiEventHandler) DECCOLM(use132 bool) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECCOLM: [%v]", []string{strconv.FormatBool(use132)}) + h.clearWrap() + if err := h.ED(2); err != nil { + return err + } + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + targetWidth := SHORT(80) + if use132 { + targetWidth = 132 + } + if info.Size.X < targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + logger.Info("set buffer failed:", err) + return err + } + } + window := info.Window + window.Left = 0 + window.Right = targetWidth - 1 + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + logger.Info("set window failed:", err) + return err + } + if info.Size.X > targetWidth { + if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { + logger.Info("set buffer failed:", err) + return err + } + } + return SetConsoleCursorPosition(h.fd, COORD{0, 0}) +} + +func (h *WindowsAnsiEventHandler) ED(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("ED: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + + // [J -- Erases from the cursor to the end of the screen, including the cursor position. + // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position. + // [2J -- Erases the complete display. The cursor does not move. + // Notes: + // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X - 1, info.Size.Y - 1} + + case 1: + start = COORD{0, 0} + end = info.CursorPosition + + case 2: + start = COORD{0, 0} + end = COORD{info.Size.X - 1, info.Size.Y - 1} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + // If the whole buffer was cleared, move the window to the top while preserving + // the window-relative cursor position. + if param == 2 { + pos := info.CursorPosition + window := info.Window + pos.Y -= window.Top + window.Bottom -= window.Top + window.Top = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { + return err + } + if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { + return err + } + } + + return nil +} + +func (h *WindowsAnsiEventHandler) EL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("EL: [%v]", strconv.Itoa(param)) + h.clearWrap() + + // [K -- Erases from the cursor to the end of the line, including the cursor position. + // [1K -- Erases from the beginning of the line to the cursor, including the cursor position. + // [2K -- Erases the complete line. + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + var start COORD + var end COORD + + switch param { + case 0: + start = info.CursorPosition + end = COORD{info.Size.X, info.CursorPosition.Y} + + case 1: + start = COORD{0, info.CursorPosition.Y} + end = info.CursorPosition + + case 2: + start = COORD{0, info.CursorPosition.Y} + end = COORD{info.Size.X, info.CursorPosition.Y} + } + + err = h.clearRange(h.attributes, start, end) + if err != nil { + return err + } + + return nil +} + +func (h *WindowsAnsiEventHandler) IL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("IL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertLines(param) +} + +func (h *WindowsAnsiEventHandler) DL(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DL: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteLines(param) +} + +func (h *WindowsAnsiEventHandler) ICH(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("ICH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.insertCharacters(param) +} + +func (h *WindowsAnsiEventHandler) DCH(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DCH: [%v]", strconv.Itoa(param)) + h.clearWrap() + return h.deleteCharacters(param) +} + +func (h *WindowsAnsiEventHandler) SGR(params []int) error { + if err := h.Flush(); err != nil { + return err + } + strings := []string{} + for _, v := range params { + strings = append(strings, strconv.Itoa(v)) + } + + logger.Infof("SGR: [%v]", strings) + + if len(params) <= 0 { + h.attributes = h.infoReset.Attributes + h.inverted = false + } else { + for _, attr := range params { + + if attr == ANSI_SGR_RESET { + h.attributes = h.infoReset.Attributes + h.inverted = false + continue + } + + h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, SHORT(attr)) + } + } + + attributes := h.attributes + if h.inverted { + attributes = invertAttributes(attributes) + } + err := SetConsoleTextAttribute(h.fd, attributes) + if err != nil { + return err + } + + return nil +} + +func (h *WindowsAnsiEventHandler) SU(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("SU: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollUp(param) +} + +func (h *WindowsAnsiEventHandler) SD(param int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("SD: [%v]", []string{strconv.Itoa(param)}) + h.clearWrap() + return h.scrollDown(param) +} + +func (h *WindowsAnsiEventHandler) DA(params []string) error { + logger.Infof("DA: [%v]", params) + // DA cannot be implemented because it must send data on the VT100 input stream, + // which is not available to go-ansiterm. + return nil +} + +func (h *WindowsAnsiEventHandler) DECSTBM(top int, bottom int) error { + if err := h.Flush(); err != nil { + return err + } + logger.Infof("DECSTBM: [%d, %d]", top, bottom) + + // Windows is 0 indexed, Linux is 1 indexed + h.sr.top = SHORT(top - 1) + h.sr.bottom = SHORT(bottom - 1) + + // This command also moves the cursor to the origin. + h.clearWrap() + return h.CUP(1, 1) +} + +func (h *WindowsAnsiEventHandler) RI() error { + if err := h.Flush(); err != nil { + return err + } + logger.Info("RI: []") + h.clearWrap() + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + sr := h.effectiveSr(info.Window) + if info.CursorPosition.Y == sr.top { + return h.scrollDown(1) + } else { + return h.moveCursorVertical(-1) + } +} + +func (h *WindowsAnsiEventHandler) IND() error { + logger.Info("IND: []") + return h.executeLF() +} + +func (h *WindowsAnsiEventHandler) Flush() error { + h.curInfo = nil + if h.buffer.Len() > 0 { + logger.Infof("Flush: [%s]", h.buffer.Bytes()) + if _, err := h.buffer.WriteTo(h.file); err != nil { + return err + } + } + + if h.wrapNext && !h.drewMarginByte { + logger.Infof("Flush: drawing margin byte '%c'", h.marginByte) + + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return err + } + + charInfo := []CHAR_INFO{{UnicodeChar: WCHAR(h.marginByte), Attributes: info.Attributes}} + size := COORD{1, 1} + position := COORD{0, 0} + region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} + if err := WriteConsoleOutput(h.fd, charInfo, size, position, ®ion); err != nil { + return err + } + h.drewMarginByte = true + } + return nil +} + +// cacheConsoleInfo ensures that the current console screen information has been queried +// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. +func (h *WindowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { + if h.curInfo == nil { + info, err := GetConsoleScreenBufferInfo(h.fd) + if err != nil { + return COORD{}, nil, err + } + h.curInfo = info + h.curPos = info.CursorPosition + } + return h.curPos, h.curInfo, nil +} + +func (h *WindowsAnsiEventHandler) updatePos(pos COORD) { + if h.curInfo == nil { + panic("failed to call getCurrentInfo before calling updatePos") + } + h.curPos = pos +} + +// clearWrap clears the state where the cursor is in the margin +// waiting for the next character before wrapping the line. This must +// be done before most operations that act on the cursor. +func (h *WindowsAnsiEventHandler) clearWrap() { + h.wrapNext = false + h.drewMarginByte = false +} diff --git a/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/LICENSE new file mode 100644 index 000000000000..b9d6a27ea92e --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + 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/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go new file mode 100644 index 000000000000..9804f401ef9f --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/autorest.go @@ -0,0 +1,114 @@ +/* +Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines +and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) +generated Go code. + +The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, +and Responding. A typical pattern is: + + req, err := Prepare(&http.Request{}, + token.WithAuthorization()) + + resp, err := Send(req, + WithLogging(logger), + DoErrorIfStatusCode(http.StatusInternalServerError), + DoCloseIfError(), + DoRetryForAttempts(5, time.Second)) + + err = Respond(resp, + ByClosing()) + +Each phase relies on decorators to modify and / or manage processing. Decorators may first modify +and then pass the data along, pass the data first and then modify the result, or wrap themselves +around passing the data (such as a logger might do). Decorators run in the order provided. For +example, the following: + + req, err := Prepare(&http.Request{}, + WithBaseURL("https://microsoft.com/"), + WithPath("a"), + WithPath("b"), + WithPath("c")) + +will set the URL to: + + https://microsoft.com/a/b/c + +Preparers and Responders may be shared and re-used (assuming the underlying decorators support +sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders +shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, +all bound together by means of input / output channels. + +Decorators hold their passed state within a closure (such as the path components in the example +above). Be careful to share Preparers and Responders only in a context where such held state +applies. For example, it may not make sense to share a Preparer that applies a query string from a +fixed set of values. Similarly, sharing a Responder that reads the response body into a passed +struct (e.g., ByUnmarshallingJson) is likely incorrect. + +Lastly, the Swagger specification (https://swagger.io) that drives AutoRest +(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The +github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure +correct parsing and formatting. + +Errors raised by autorest objects and methods will conform to the autorest.Error interface. + +See the included examples for more detail. For details on the suggested use of this package by +generated clients, see the Client described below. +*/ +package autorest + +import ( + "net/http" + "time" +) + +const ( + // HeaderLocation specifies the HTTP Location header. + HeaderLocation = "Location" + + // HeaderRetryAfter specifies the HTTP Retry-After header. + HeaderRetryAfter = "Retry-After" +) + +// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set +// and false otherwise. +func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { + return containsInt(codes, resp.StatusCode) +} + +// GetLocation retrieves the URL from the Location header of the passed response. +func GetLocation(resp *http.Response) string { + return resp.Header.Get(HeaderLocation) +} + +// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If +// the header is absent or is malformed, it will return the supplied default delay time.Duration. +func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { + retry := resp.Header.Get(HeaderRetryAfter) + if retry == "" { + return defaultDelay + } + + d, err := time.ParseDuration(retry + "s") + if err != nil { + return defaultDelay + } + + return d +} + +// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. +func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { + location := GetLocation(resp) + if location == "" { + return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") + } + + req, err := Prepare(&http.Request{Cancel: cancel}, + AsGet(), + WithBaseURL(location)) + if err != nil { + return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) + } + + return req, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go new file mode 100644 index 000000000000..280d32a61dde --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -0,0 +1,307 @@ +package azure + +import ( + "bytes" + "fmt" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "io/ioutil" + "net/http" + "strings" + "time" +) + +const ( + headerAsyncOperation = "Azure-AsyncOperation" +) + +const ( + methodDelete = "DELETE" + methodPatch = "PATCH" + methodPost = "POST" + methodPut = "PUT" + methodGet = "GET" + + operationInProgress string = "InProgress" + operationCanceled string = "Canceled" + operationFailed string = "Failed" + operationSucceeded string = "Succeeded" +) + +// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure +// long-running operation. It will delay between requests for the duration specified in the +// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by +// closing the optional channel on the http.Request. +func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator { + return func(s autorest.Sender) autorest.Sender { + return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + resp, err = s.Do(r) + if err != nil { + return resp, err + } + pollingCodes := []int{http.StatusAccepted, http.StatusCreated, http.StatusOK} + if !autorest.ResponseHasStatusCode(resp, pollingCodes...) { + return resp, nil + } + + ps := pollingState{} + for err == nil { + err = updatePollingState(resp, &ps) + if err != nil { + break + } + if ps.hasTerminated() { + if !ps.hasSucceeded() { + err = ps + } + break + } + + r, err = newPollingRequest(resp, ps) + if err != nil { + return resp, err + } + + delay = autorest.GetRetryAfter(resp, delay) + resp, err = autorest.SendWithSender(s, r, + autorest.AfterDelay(delay)) + } + + return resp, err + }) + } +} + +func getAsyncOperation(resp *http.Response) string { + return resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) +} + +func hasSucceeded(state string) bool { + return state == operationSucceeded +} + +func hasTerminated(state string) bool { + switch state { + case operationCanceled, operationFailed, operationSucceeded: + return true + default: + return false + } +} + +func hasFailed(state string) bool { + return state == operationFailed +} + +type provisioningTracker interface { + state() string + hasSucceeded() bool + hasTerminated() bool +} + +type operationResource struct { + // Note: + // The specification states services should return the "id" field. However some return it as + // "operationId". + ID string `json:"id"` + OperationID string `json:"operationId"` + Name string `json:"name"` + Status string `json:"status"` + Properties map[string]interface{} `json:"properties"` + OperationError ServiceError `json:"error"` + StartTime date.Time `json:"startTime"` + EndTime date.Time `json:"endTime"` + PercentComplete float64 `json:"percentComplete"` +} + +func (or operationResource) state() string { + return or.Status +} + +func (or operationResource) hasSucceeded() bool { + return hasSucceeded(or.state()) +} + +func (or operationResource) hasTerminated() bool { + return hasTerminated(or.state()) +} + +type provisioningProperties struct { + ProvisioningState string `json:"provisioningState"` +} + +type provisioningStatus struct { + Properties provisioningProperties `json:"properties,omitempty"` + ProvisioningError ServiceError `json:"error,omitempty"` +} + +func (ps provisioningStatus) state() string { + return ps.Properties.ProvisioningState +} + +func (ps provisioningStatus) hasSucceeded() bool { + return hasSucceeded(ps.state()) +} + +func (ps provisioningStatus) hasTerminated() bool { + return hasTerminated(ps.state()) +} + +func (ps provisioningStatus) hasProvisioningError() bool { + return ps.ProvisioningError != ServiceError{} +} + +type pollingResponseFormat string + +const ( + usesOperationResponse pollingResponseFormat = "OperationResponse" + usesProvisioningStatus pollingResponseFormat = "ProvisioningStatus" + formatIsUnknown pollingResponseFormat = "" +) + +type pollingState struct { + responseFormat pollingResponseFormat + uri string + state string + code string + message string +} + +func (ps pollingState) hasSucceeded() bool { + return hasSucceeded(ps.state) +} + +func (ps pollingState) hasTerminated() bool { + return hasTerminated(ps.state) +} + +func (ps pollingState) hasFailed() bool { + return hasFailed(ps.state) +} + +func (ps pollingState) Error() string { + return fmt.Sprintf("Long running operation terminated with status '%s': Code=%q Message=%q", ps.state, ps.code, ps.message) +} + +// updatePollingState maps the operation status -- retrieved from either a provisioningState +// field, the status field of an OperationResource, or inferred from the HTTP status code -- +// into a well-known states. Since the process begins from the initial request, the state +// always comes from either a the provisioningState returned or is inferred from the HTTP +// status code. Subsequent requests will read an Azure OperationResource object if the +// service initially returned the Azure-AsyncOperation header. The responseFormat field notes +// the expected response format. +func updatePollingState(resp *http.Response, ps *pollingState) error { + // Determine the response shape + // -- The first response will always be a provisioningStatus response; only the polling requests, + // depending on the header returned, may be something otherwise. + var pt provisioningTracker + if ps.responseFormat == usesOperationResponse { + pt = &operationResource{} + } else { + pt = &provisioningStatus{} + } + + // If this is the first request (that is, the polling response shape is unknown), determine how + // to poll and what to expect + if ps.responseFormat == formatIsUnknown { + req := resp.Request + if req == nil { + return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Original HTTP request is missing") + } + + // Prefer the Azure-AsyncOperation header + ps.uri = getAsyncOperation(resp) + if ps.uri != "" { + ps.responseFormat = usesOperationResponse + } else { + ps.responseFormat = usesProvisioningStatus + } + + // Else, use the Location header + if ps.uri == "" { + ps.uri = autorest.GetLocation(resp) + } + + // Lastly, requests against an existing resource, use the last request URI + if ps.uri == "" { + m := strings.ToUpper(req.Method) + if m == methodPatch || m == methodPut || m == methodGet { + ps.uri = req.URL.String() + } + } + } + + // Read and interpret the response (saving the Body in case no polling is necessary) + b := &bytes.Buffer{} + err := autorest.Respond(resp, + autorest.ByCopying(b), + autorest.ByUnmarshallingJSON(pt), + autorest.ByClosing()) + resp.Body = ioutil.NopCloser(b) + if err != nil { + return err + } + + // Interpret the results + // -- Terminal states apply regardless + // -- Unknown states are per-service inprogress states + // -- Otherwise, infer state from HTTP status code + if pt.hasTerminated() { + ps.state = pt.state() + } else if pt.state() != "" { + ps.state = operationInProgress + } else { + switch resp.StatusCode { + case http.StatusAccepted: + ps.state = operationInProgress + + case http.StatusNoContent, http.StatusCreated, http.StatusOK: + ps.state = operationSucceeded + + default: + ps.state = operationFailed + } + } + + if ps.state == operationInProgress && ps.uri == "" { + return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Unable to obtain polling URI for %s %s", resp.Request.Method, resp.Request.URL) + } + + // For failed operation, check for error code and message in + // -- Operation resource + // -- Response + // -- Otherwise, Unknown + if ps.hasFailed() { + if ps.responseFormat == usesOperationResponse { + or := pt.(*operationResource) + ps.code = or.OperationError.Code + ps.message = or.OperationError.Message + } else { + p := pt.(*provisioningStatus) + if p.hasProvisioningError() { + ps.code = p.ProvisioningError.Code + ps.message = p.ProvisioningError.Message + } else { + ps.code = "Unknown" + ps.message = "None" + } + } + } + return nil +} + +func newPollingRequest(resp *http.Response, ps pollingState) (*http.Request, error) { + req := resp.Request + if req == nil { + return nil, autorest.NewError("azure", "newPollingRequest", "Azure Polling Error - Original HTTP request is missing") + } + + reqPoll, err := autorest.Prepare(&http.Request{Cancel: req.Cancel}, + autorest.AsGet(), + autorest.WithBaseURL(ps.uri)) + if err != nil { + return nil, autorest.NewErrorWithError(err, "azure", "newPollingRequest", nil, "Failure creating poll request to %s", ps.uri) + } + + return reqPoll, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go new file mode 100644 index 000000000000..3f4d13421aac --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go @@ -0,0 +1,180 @@ +/* +Package azure provides Azure-specific implementations used with AutoRest. + +See the included examples for more detail. +*/ +package azure + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strconv" + + "github.com/Azure/go-autorest/autorest" +) + +const ( + // HeaderClientID is the Azure extension header to set a user-specified request ID. + HeaderClientID = "x-ms-client-request-id" + + // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID + // should be included in the response. + HeaderReturnClientID = "x-ms-return-client-request-id" + + // HeaderRequestID is the Azure extension header of the service generated request ID returned + // in the response. + HeaderRequestID = "x-ms-request-id" +) + +// ServiceError encapsulates the error response from an Azure service. +type ServiceError struct { + Code string `json:"code"` + Message string `json:"message"` + Details *[]interface{} `json:"details"` +} + +func (se ServiceError) Error() string { + if se.Details != nil { + d, err := json.Marshal(*(se.Details)) + if err != nil { + return fmt.Sprintf("Code=%q Message=%q Details=%v", se.Code, se.Message, *se.Details) + } + return fmt.Sprintf("Code=%q Message=%q Details=%v", se.Code, se.Message, string(d)) + } + return fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) +} + +// RequestError describes an error response returned by Azure service. +type RequestError struct { + autorest.DetailedError + + // The error returned by the Azure service. + ServiceError *ServiceError `json:"error"` + + // The request id (from the x-ms-request-id-header) of the request. + RequestID string +} + +// Error returns a human-friendly error message from service error. +func (e RequestError) Error() string { + return fmt.Sprintf("autorest/azure: Service returned an error. Status=%v %v", + e.StatusCode, e.ServiceError) +} + +// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. +func IsAzureError(e error) bool { + _, ok := e.(*RequestError) + return ok +} + +// NewErrorWithError creates a new Error conforming object from the +// passed packageType, method, statusCode of the given resp (UndefinedStatusCode +// if resp is nil), message, and original error. message is treated as a format +// string to which the optional args apply. +func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { + if v, ok := original.(*RequestError); ok { + return *v + } + + statusCode := autorest.UndefinedStatusCode + if resp != nil { + statusCode = resp.StatusCode + } + return RequestError{ + DetailedError: autorest.DetailedError{ + Original: original, + PackageType: packageType, + Method: method, + StatusCode: statusCode, + Message: fmt.Sprintf(message, args...), + }, + } +} + +// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., +// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id +// header to true such that UUID accompanies the http.Response. +func WithReturningClientID(uuid string) autorest.PrepareDecorator { + preparer := autorest.CreatePreparer( + WithClientID(uuid), + WithReturnClientID(true)) + + return func(p autorest.Preparer) autorest.Preparer { + return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err != nil { + return r, err + } + return preparer.Prepare(r) + }) + } +} + +// WithClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., +// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). +func WithClientID(uuid string) autorest.PrepareDecorator { + return autorest.WithHeader(HeaderClientID, uuid) +} + +// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-return-client-request-id whose boolean value indicates if the value of the +// x-ms-client-request-id header should be included in the http.Response. +func WithReturnClientID(b bool) autorest.PrepareDecorator { + return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) +} + +// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the +// http.Request sent to the service (and returned in the http.Response) +func ExtractClientID(resp *http.Response) string { + return autorest.ExtractHeaderValue(HeaderClientID, resp) +} + +// ExtractRequestID extracts the Azure server generated request identifier from the +// x-ms-request-id header. +func ExtractRequestID(resp *http.Response) string { + return autorest.ExtractHeaderValue(HeaderRequestID, resp) +} + +// WithErrorUnlessStatusCode returns a RespondDecorator that emits an +// azure.RequestError by reading the response body unless the response HTTP status code +// is among the set passed. +// +// If there is a chance service may return responses other than the Azure error +// format and the response cannot be parsed into an error, a decoding error will +// be returned containing the response body. In any case, the Responder will +// return an error if the status code is not satisfied. +// +// If this Responder returns an error, the response body will be replaced with +// an in-memory reader, which needs no further closing. +func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { + var e RequestError + defer resp.Body.Close() + + // Copy and replace the Body in case it does not contain an error object. + // This will leave the Body available to the caller. + b, decodeErr := autorest.CopyAndDecode(autorest.EncodedAsJSON, resp.Body, &e) + resp.Body = ioutil.NopCloser(&b) + if decodeErr != nil { + return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), decodeErr) + } else if e.ServiceError == nil { + e.ServiceError = &ServiceError{Code: "Unknown", Message: "Unknown service error"} + } + + e.RequestID = ExtractRequestID(resp) + if e.StatusCode == nil { + e.StatusCode = resp.StatusCode + } + err = &e + } + return err + }) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/config.go b/vendor/github.com/Azure/go-autorest/autorest/azure/config.go new file mode 100644 index 000000000000..bea30b0d67ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/config.go @@ -0,0 +1,13 @@ +package azure + +import ( + "net/url" +) + +// OAuthConfig represents the endpoints needed +// in OAuth operations +type OAuthConfig struct { + AuthorizeEndpoint url.URL + TokenEndpoint url.URL + DeviceCodeEndpoint url.URL +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go new file mode 100644 index 000000000000..e1d5498a80f1 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go @@ -0,0 +1,193 @@ +package azure + +/* + This file is largely based on rjw57/oauth2device's code, with the follow differences: + * scope -> resource, and only allow a single one + * receive "Message" in the DeviceCode struct and show it to users as the prompt + * azure-xplat-cli has the following behavior that this emulates: + - does not send client_secret during the token exchange + - sends resource again in the token exchange request +*/ + +import ( + "fmt" + "net/http" + "net/url" + "time" + + "github.com/Azure/go-autorest/autorest" +) + +const ( + logPrefix = "autorest/azure/devicetoken:" +) + +var ( + // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow + ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) + + // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow + ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) + + // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow + ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) + + // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow + ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) + + // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow + ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) + + errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" + errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" + errTokenSendingFails = "Error occurred while sending request with device code for a token" + errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" +) + +// DeviceCode is the object returned by the device auth endpoint +// It contains information to instruct the user to complete the auth flow +type DeviceCode struct { + DeviceCode *string `json:"device_code,omitempty"` + UserCode *string `json:"user_code,omitempty"` + VerificationURL *string `json:"verification_url,omitempty"` + ExpiresIn *int64 `json:"expires_in,string,omitempty"` + Interval *int64 `json:"interval,string,omitempty"` + + Message *string `json:"message"` // Azure specific + Resource string // store the following, stored when initiating, used when exchanging + OAuthConfig OAuthConfig + ClientID string +} + +// TokenError is the object returned by the token exchange endpoint +// when something is amiss +type TokenError struct { + Error *string `json:"error,omitempty"` + ErrorCodes []int `json:"error_codes,omitempty"` + ErrorDescription *string `json:"error_description,omitempty"` + Timestamp *string `json:"timestamp,omitempty"` + TraceID *string `json:"trace_id,omitempty"` +} + +// DeviceToken is the object return by the token exchange endpoint +// It can either look like a Token or an ErrorToken, so put both here +// and check for presence of "Error" to know if we are in error state +type deviceToken struct { + Token + TokenError +} + +// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode +// that can be used with CheckForUserCompletion or WaitForUserCompletion. +func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { + req, _ := autorest.Prepare( + &http.Request{}, + autorest.AsPost(), + autorest.AsFormURLEncoded(), + autorest.WithBaseURL(oauthConfig.DeviceCodeEndpoint.String()), + autorest.WithFormData(url.Values{ + "client_id": []string{clientID}, + "resource": []string{resource}, + }), + ) + + resp, err := autorest.SendWithSender(client, req) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err) + } + + var code DeviceCode + err = autorest.Respond( + resp, + autorest.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&code), + autorest.ByClosing()) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err) + } + + code.ClientID = clientID + code.Resource = resource + code.OAuthConfig = oauthConfig + + return &code, nil +} + +// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint +// to see if the device flow has: been completed, timed out, or otherwise failed +func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) { + req, _ := autorest.Prepare( + &http.Request{}, + autorest.AsPost(), + autorest.AsFormURLEncoded(), + autorest.WithBaseURL(code.OAuthConfig.TokenEndpoint.String()), + autorest.WithFormData(url.Values{ + "client_id": []string{code.ClientID}, + "code": []string{*code.DeviceCode}, + "grant_type": []string{OAuthGrantTypeDeviceCode}, + "resource": []string{code.Resource}, + }), + ) + + resp, err := autorest.SendWithSender(client, req) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err) + } + + var token deviceToken + err = autorest.Respond( + resp, + autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest), + autorest.ByUnmarshallingJSON(&token), + autorest.ByClosing()) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err) + } + + if token.Error == nil { + return &token.Token, nil + } + + switch *token.Error { + case "authorization_pending": + return nil, ErrDeviceAuthorizationPending + case "slow_down": + return nil, ErrDeviceSlowDown + case "access_denied": + return nil, ErrDeviceAccessDenied + case "code_expired": + return nil, ErrDeviceCodeExpired + default: + return nil, ErrDeviceGeneric + } +} + +// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. +// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. +func WaitForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) { + intervalDuration := time.Duration(*code.Interval) * time.Second + waitDuration := intervalDuration + + for { + token, err := CheckForUserCompletion(client, code) + + if err == nil { + return token, nil + } + + switch err { + case ErrDeviceSlowDown: + waitDuration += waitDuration + case ErrDeviceAuthorizationPending: + // noop + default: // everything else is "fatal" to us + return nil, err + } + + if waitDuration > (intervalDuration * 3) { + return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) + } + + time.Sleep(waitDuration) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go new file mode 100644 index 000000000000..ebf754eab4fb --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -0,0 +1,147 @@ +package azure + +import ( + "fmt" + "net/url" + "strings" +) + +const ( + activeDirectoryAPIVersion = "1.0" +) + +var environments = map[string]Environment{ + "AZURECHINACLOUD": ChinaCloud, + "AZUREGERMANCLOUD": GermanCloud, + "AZUREPUBLICCLOUD": PublicCloud, + "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, +} + +// Environment represents a set of endpoints for each of Azure's Clouds. +type Environment struct { + Name string `json:"name"` + ManagementPortalURL string `json:"managementPortalURL"` + PublishSettingsURL string `json:"publishSettingsURL"` + ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` + ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` + ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` + GalleryEndpoint string `json:"galleryEndpoint"` + KeyVaultEndpoint string `json:"keyVaultEndpoint"` + GraphEndpoint string `json:"graphEndpoint"` + StorageEndpointSuffix string `json:"storageEndpointSuffix"` + SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` + TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` + KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` + ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` +} + +var ( + // PublicCloud is the default public Azure cloud environment + PublicCloud = Environment{ + Name: "AzurePublicCloud", + ManagementPortalURL: "https://manage.windowsazure.com/", + PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.windows.net/", + ResourceManagerEndpoint: "https://management.azure.com/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.azure.com/", + KeyVaultEndpoint: "https://vault.azure.net/", + GraphEndpoint: "https://graph.windows.net/", + StorageEndpointSuffix: "core.windows.net", + SQLDatabaseDNSSuffix: "database.windows.net", + TrafficManagerDNSSuffix: "trafficmanager.net", + KeyVaultDNSSuffix: "vault.azure.net", + ServiceBusEndpointSuffix: "servicebus.azure.com", + } + + // USGovernmentCloud is the cloud environment for the US Government + USGovernmentCloud = Environment{ + Name: "AzureUSGovernmentCloud", + ManagementPortalURL: "https://manage.windowsazure.us/", + PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", + ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.usgovcloudapi.net/", + KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", + GraphEndpoint: "https://graph.usgovcloudapi.net/", + StorageEndpointSuffix: "core.usgovcloudapi.net", + SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", + TrafficManagerDNSSuffix: "usgovtrafficmanager.net", + KeyVaultDNSSuffix: "vault.usgovcloudapi.net", + ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", + } + + // ChinaCloud is the cloud environment operated in China + ChinaCloud = Environment{ + Name: "AzureChinaCloud", + ManagementPortalURL: "https://manage.chinacloudapi.com/", + PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", + ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", + ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/?api-version=1.0", + GalleryEndpoint: "https://gallery.chinacloudapi.cn/", + KeyVaultEndpoint: "https://vault.azure.cn/", + GraphEndpoint: "https://graph.chinacloudapi.cn/", + StorageEndpointSuffix: "core.chinacloudapi.cn", + SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", + TrafficManagerDNSSuffix: "trafficmanager.cn", + KeyVaultDNSSuffix: "vault.azure.cn", + ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", + } + + // GermanCloud is the cloud environment operated in Germany + GermanCloud = Environment{ + Name: "AzureGermanCloud", + ManagementPortalURL: "http://portal.microsoftazure.de/", + PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.cloudapi.de/", + ResourceManagerEndpoint: "https://management.microsoftazure.de/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", + GalleryEndpoint: "https://gallery.cloudapi.de/", + KeyVaultEndpoint: "https://vault.microsoftazure.de/", + GraphEndpoint: "https://graph.cloudapi.de/", + StorageEndpointSuffix: "core.cloudapi.de", + SQLDatabaseDNSSuffix: "database.cloudapi.de", + TrafficManagerDNSSuffix: "azuretrafficmanager.de", + KeyVaultDNSSuffix: "vault.microsoftazure.de", + ServiceBusEndpointSuffix: "servicebus.cloudapi.de", + } +) + +// EnvironmentFromName returns an Environment based on the common name specified +func EnvironmentFromName(name string) (Environment, error) { + name = strings.ToUpper(name) + env, ok := environments[name] + if !ok { + return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) + } + return env, nil +} + +// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls +func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error) { + template := "%s/oauth2/%s?api-version=%s" + u, err := url.Parse(env.ActiveDirectoryEndpoint) + if err != nil { + return nil, err + } + authorizeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "authorize", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + tokenURL, err := u.Parse(fmt.Sprintf(template, tenantID, "token", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + deviceCodeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "devicecode", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + + return &OAuthConfig{ + AuthorizeEndpoint: *authorizeURL, + TokenEndpoint: *tokenURL, + DeviceCodeEndpoint: *deviceCodeURL, + }, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go b/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go new file mode 100644 index 000000000000..d5cf62ddc7ba --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go @@ -0,0 +1,59 @@ +package azure + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" +) + +// LoadToken restores a Token object from a file located at 'path'. +func LoadToken(path string) (*Token, error) { + file, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) + } + defer file.Close() + + var token Token + + dec := json.NewDecoder(file) + if err = dec.Decode(&token); err != nil { + return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) + } + return &token, nil +} + +// SaveToken persists an oauth token at the given location on disk. +// It moves the new file into place so it can safely be used to replace an existing file +// that maybe accessed by multiple processes. +func SaveToken(path string, mode os.FileMode, token Token) error { + dir := filepath.Dir(path) + err := os.MkdirAll(dir, os.ModePerm) + if err != nil { + return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) + } + + newFile, err := ioutil.TempFile(dir, "token") + if err != nil { + return fmt.Errorf("failed to create the temp file to write the token: %v", err) + } + tempPath := newFile.Name() + + if err := json.NewEncoder(newFile).Encode(token); err != nil { + return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) + } + if err := newFile.Close(); err != nil { + return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) + } + + // Atomic replace to avoid multi-writer file corruptions + if err := os.Rename(tempPath, path); err != nil { + return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) + } + if err := os.Chmod(path, mode); err != nil { + return fmt.Errorf("failed to chmod the token file %s: %v", path, err) + } + return nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/token.go b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go new file mode 100644 index 000000000000..db9a8fa02aed --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go @@ -0,0 +1,363 @@ +package azure + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/x509" + "encoding/base64" + "fmt" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/Azure/go-autorest/autorest" + "github.com/dgrijalva/jwt-go" +) + +const ( + defaultRefresh = 5 * time.Minute + tokenBaseDate = "1970-01-01T00:00:00Z" + + // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow + OAuthGrantTypeDeviceCode = "device_code" + + // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows + OAuthGrantTypeClientCredentials = "client_credentials" + + // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows + OAuthGrantTypeRefreshToken = "refresh_token" +) + +var expirationBase time.Time + +func init() { + expirationBase, _ = time.Parse(time.RFC3339, tokenBaseDate) +} + +// TokenRefreshCallback is the type representing callbacks that will be called after +// a successful token refresh +type TokenRefreshCallback func(Token) error + +// Token encapsulates the access token used to authorize Azure requests. +type Token struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + + ExpiresIn string `json:"expires_in"` + ExpiresOn string `json:"expires_on"` + NotBefore string `json:"not_before"` + + Resource string `json:"resource"` + Type string `json:"token_type"` +} + +// Expires returns the time.Time when the Token expires. +func (t Token) Expires() time.Time { + s, err := strconv.Atoi(t.ExpiresOn) + if err != nil { + s = -3600 + } + return expirationBase.Add(time.Duration(s) * time.Second).UTC() +} + +// IsExpired returns true if the Token is expired, false otherwise. +func (t Token) IsExpired() bool { + return t.WillExpireIn(0) +} + +// WillExpireIn returns true if the Token will expire after the passed time.Duration interval +// from now, false otherwise. +func (t Token) WillExpireIn(d time.Duration) bool { + return !t.Expires().After(time.Now().Add(d)) +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose +// value is "Bearer " followed by the AccessToken of the Token. +func (t *Token) WithAuthorization() autorest.PrepareDecorator { + return func(p autorest.Preparer) autorest.Preparer { + return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { + return (autorest.WithBearerAuthorization(t.AccessToken)(p)).Prepare(r) + }) + } +} + +// ServicePrincipalNoSecret represents a secret type that contains no secret +// meaning it is not valid for fetching a fresh token. This is used by Manual +type ServicePrincipalNoSecret struct { +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret +// It only returns an error for the ServicePrincipalNoSecret type +func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token.") +} + +// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form +// that is submitted when acquiring an oAuth token. +type ServicePrincipalSecret interface { + SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error +} + +// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization. +type ServicePrincipalTokenSecret struct { + ClientSecret string +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. +// It will populate the form submitted during oAuth Token Acquisition using the client_secret. +func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + v.Set("client_secret", tokenSecret.ClientSecret) + return nil +} + +// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs. +type ServicePrincipalCertificateSecret struct { + Certificate *x509.Certificate + PrivateKey *rsa.PrivateKey +} + +// SignJwt returns the JWT signed with the certificate's private key. +func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { + hasher := sha1.New() + _, err := hasher.Write(secret.Certificate.Raw) + if err != nil { + return "", err + } + + thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) + + // The jti (JWT ID) claim provides a unique identifier for the JWT. + jti := make([]byte, 20) + _, err = rand.Read(jti) + if err != nil { + return "", err + } + + token := jwt.New(jwt.SigningMethodRS256) + token.Header["x5t"] = thumbprint + token.Claims = jwt.MapClaims{ + "aud": spt.oauthConfig.TokenEndpoint, + "iss": spt.clientID, + "sub": spt.clientID, + "jti": base64.URLEncoding.EncodeToString(jti), + "nbf": time.Now().Unix(), + "exp": time.Now().Add(time.Hour * 24).Unix(), + } + + signedString, err := token.SignedString(secret.PrivateKey) + return signedString, err +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. +// It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. +func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + jwt, err := secret.SignJwt(spt) + if err != nil { + return err + } + + v.Set("client_assertion", jwt) + v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") + return nil +} + +// ServicePrincipalToken encapsulates a Token created for a Service Principal. +type ServicePrincipalToken struct { + Token + + secret ServicePrincipalSecret + oauthConfig OAuthConfig + clientID string + resource string + autoRefresh bool + refreshWithin time.Duration + sender autorest.Sender + + refreshCallbacks []TokenRefreshCallback +} + +// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. +func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + spt := &ServicePrincipalToken{ + oauthConfig: oauthConfig, + secret: secret, + clientID: id, + resource: resource, + autoRefresh: true, + refreshWithin: defaultRefresh, + sender: &http.Client{}, + refreshCallbacks: callbacks, + } + return spt, nil +} + +// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token +func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + spt, err := NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalNoSecret{}, + callbacks...) + if err != nil { + return nil, err + } + + spt.Token = token + + return spt, nil +} + +// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal +// credentials scoped to the named resource. +func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + return NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalTokenSecret{ + ClientSecret: secret, + }, + callbacks..., + ) +} + +// NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes. +func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + return NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalCertificateSecret{ + PrivateKey: privateKey, + Certificate: certificate, + }, + callbacks..., + ) +} + +// EnsureFresh will refresh the token if it will expire within the refresh window (as set by +// RefreshWithin). +func (spt *ServicePrincipalToken) EnsureFresh() error { + if spt.WillExpireIn(spt.refreshWithin) { + return spt.Refresh() + } + return nil +} + +// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization +func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { + if spt.refreshCallbacks != nil { + for _, callback := range spt.refreshCallbacks { + err := callback(spt.Token) + if err != nil { + return autorest.NewErrorWithError(err, + "azure.ServicePrincipalToken", "InvokeRefreshCallbacks", nil, "A TokenRefreshCallback handler returned an error") + } + } + } + return nil +} + +// Refresh obtains a fresh token for the Service Principal. +func (spt *ServicePrincipalToken) Refresh() error { + return spt.refreshInternal(spt.resource) +} + +// RefreshExchange refreshes the token, but for a different resource. +func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { + return spt.refreshInternal(resource) +} + +func (spt *ServicePrincipalToken) refreshInternal(resource string) error { + v := url.Values{} + v.Set("client_id", spt.clientID) + v.Set("resource", resource) + + if spt.RefreshToken != "" { + v.Set("grant_type", OAuthGrantTypeRefreshToken) + v.Set("refresh_token", spt.RefreshToken) + } else { + v.Set("grant_type", OAuthGrantTypeClientCredentials) + err := spt.secret.SetAuthenticationValues(spt, &v) + if err != nil { + return err + } + } + + req, _ := autorest.Prepare(&http.Request{}, + autorest.AsPost(), + autorest.AsFormURLEncoded(), + autorest.WithBaseURL(spt.oauthConfig.TokenEndpoint.String()), + autorest.WithFormData(v)) + + resp, err := autorest.SendWithSender(spt.sender, req) + if err != nil { + return autorest.NewErrorWithError(err, + "azure.ServicePrincipalToken", "Refresh", resp, "Failure sending request for Service Principal %s", + spt.clientID) + } + + var newToken Token + err = autorest.Respond(resp, + autorest.WithErrorUnlessOK(), + autorest.ByUnmarshallingJSON(&newToken), + autorest.ByClosing()) + if err != nil { + return autorest.NewErrorWithError(err, + "azure.ServicePrincipalToken", "Refresh", resp, "Failure handling response to Service Principal %s request", + spt.clientID) + } + + spt.Token = newToken + + err = spt.InvokeRefreshCallbacks(newToken) + if err != nil { + // its already wrapped inside InvokeRefreshCallbacks + return err + } + + return nil +} + +// SetAutoRefresh enables or disables automatic refreshing of stale tokens. +func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) { + spt.autoRefresh = autoRefresh +} + +// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will +// refresh the token. +func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { + spt.refreshWithin = d + return +} + +// SetSender sets the autorest.Sender used when obtaining the Service Principal token. An +// undecorated http.Client is used by default. +func (spt *ServicePrincipalToken) SetSender(s autorest.Sender) { + spt.sender = s +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose +// value is "Bearer " followed by the AccessToken of the ServicePrincipalToken. +// +// By default, the token will automatically refresh if nearly expired (as determined by the +// RefreshWithin interval). Use the AutoRefresh method to enable or disable automatically refreshing +// tokens. +func (spt *ServicePrincipalToken) WithAuthorization() autorest.PrepareDecorator { + return func(p autorest.Preparer) autorest.Preparer { + return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { + if spt.autoRefresh { + err := spt.EnsureFresh() + if err != nil { + return r, autorest.NewErrorWithError(err, + "azure.ServicePrincipalToken", "WithAuthorization", nil, "Failed to refresh Service Principal Token for request to %s", + r.URL) + } + } + return (autorest.WithBearerAuthorization(spt.AccessToken)(p)).Prepare(r) + }) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go new file mode 100644 index 000000000000..95e9a203d880 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -0,0 +1,211 @@ +package autorest + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/http/cookiejar" + "time" +) + +const ( + // DefaultPollingDelay is a reasonable delay between polling requests. + DefaultPollingDelay = 60 * time.Second + + // DefaultPollingDuration is a reasonable total polling duration. + DefaultPollingDuration = 15 * time.Minute + + // DefaultRetryAttempts is number of attempts for retry status codes (5xx). + DefaultRetryAttempts = 3 + + // DefaultRetryDuration is a resonable delay for retry. + defaultRetryInterval = 30 * time.Second +) + +var statusCodesForRetry = []int{ + http.StatusRequestTimeout, // 408 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 +} + +const ( + requestFormat = `HTTP Request Begin =================================================== +%s +===================================================== HTTP Request End +` + responseFormat = `HTTP Response Begin =================================================== +%s +===================================================== HTTP Response End +` +) + +// Response serves as the base for all responses from generated clients. It provides access to the +// last http.Response. +type Response struct { + *http.Response `json:"-"` +} + +// LoggingInspector implements request and response inspectors that log the full request and +// response to a supplied log. +type LoggingInspector struct { + Logger *log.Logger +} + +// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The +// body is restored after being emitted. +// +// Note: Since it reads the entire Body, this decorator should not be used where body streaming is +// important. It is best used to trace JSON or similar body values. +func (li LoggingInspector) WithInspection() PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + var body, b bytes.Buffer + + defer r.Body.Close() + + r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) + if err := r.Write(&b); err != nil { + return nil, fmt.Errorf("Failed to write response: %v", err) + } + + li.Logger.Printf(requestFormat, b.String()) + + r.Body = ioutil.NopCloser(&body) + return p.Prepare(r) + }) + } +} + +// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The +// body is restored after being emitted. +// +// Note: Since it reads the entire Body, this decorator should not be used where body streaming is +// important. It is best used to trace JSON or similar body values. +func (li LoggingInspector) ByInspecting() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + var body, b bytes.Buffer + defer resp.Body.Close() + resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) + if err := resp.Write(&b); err != nil { + return fmt.Errorf("Failed to write response: %v", err) + } + + li.Logger.Printf(responseFormat, b.String()) + + resp.Body = ioutil.NopCloser(&body) + return r.Respond(resp) + }) + } +} + +// Client is the base for autorest generated clients. It provides default, "do nothing" +// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the +// standard, undecorated http.Client as a default Sender. +// +// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and +// return responses that compose with Response. +// +// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom +// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit +// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence +// sending the request by providing a decorated Sender. +type Client struct { + Authorizer Authorizer + Sender Sender + RequestInspector PrepareDecorator + ResponseInspector RespondDecorator + + // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header + PollingDelay time.Duration + + // PollingDuration sets the maximum polling time after which an error is returned. + PollingDuration time.Duration + + // RetryAttempts sets the default number of retry attempts for client. + RetryAttempts int + + // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent + // through the Do method. + UserAgent string + + Jar http.CookieJar +} + +// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed +// string. +func NewClientWithUserAgent(ua string) Client { + return Client{ + PollingDelay: DefaultPollingDelay, + PollingDuration: DefaultPollingDuration, + RetryAttempts: DefaultRetryAttempts, + UserAgent: ua, + } +} + +// Do implements the Sender interface by invoking the active Sender after applying authorization. +// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent +// is set, apply set the User-Agent header. +func (c Client) Do(r *http.Request) (*http.Response, error) { + if r.UserAgent() == "" { + r, _ = Prepare(r, + WithUserAgent(c.UserAgent)) + } + r, err := Prepare(r, + c.WithInspection(), + c.WithAuthorization()) + if err != nil { + return nil, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") + } + resp, err := SendWithSender(c.sender(), r, + DoRetryForStatusCodes(c.RetryAttempts, defaultRetryInterval, statusCodesForRetry...)) + Respond(resp, + c.ByInspecting()) + return resp, err +} + +// sender returns the Sender to which to send requests. +func (c Client) sender() Sender { + if c.Sender == nil { + j, _ := cookiejar.New(nil) + return &http.Client{Jar: j} + } + return c.Sender +} + +// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator +// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. +func (c Client) WithAuthorization() PrepareDecorator { + return c.authorizer().WithAuthorization() +} + +// authorizer returns the Authorizer to use. +func (c Client) authorizer() Authorizer { + if c.Authorizer == nil { + return NullAuthorizer{} + } + return c.Authorizer +} + +// WithInspection is a convenience method that passes the request to the supplied RequestInspector, +// if present, or returns the WithNothing PrepareDecorator otherwise. +func (c Client) WithInspection() PrepareDecorator { + if c.RequestInspector == nil { + return WithNothing() + } + return c.RequestInspector +} + +// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, +// if present, or returns the ByIgnoring RespondDecorator otherwise. +func (c Client) ByInspecting() RespondDecorator { + if c.ResponseInspector == nil { + return ByIgnoring() + } + return c.ResponseInspector +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/Azure/go-autorest/autorest/date/date.go new file mode 100644 index 000000000000..80ca60e9b08a --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/date.go @@ -0,0 +1,82 @@ +/* +Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/) +defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of +time.Time types. And both convert to time.Time through a ToTime method. +*/ +package date + +import ( + "fmt" + "time" +) + +const ( + fullDate = "2006-01-02" + fullDateJSON = `"2006-01-02"` + dateFormat = "%04d-%02d-%02d" + jsonFormat = `"%04d-%02d-%02d"` +) + +// Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., +// 2006-01-02). +type Date struct { + time.Time +} + +// ParseDate create a new Date from the passed string. +func ParseDate(date string) (d Date, err error) { + return parseDate(date, fullDate) +} + +func parseDate(date string, format string) (Date, error) { + d, err := time.Parse(format, date) + return Date{Time: d}, err +} + +// MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d Date) MarshalBinary() ([]byte, error) { + return d.MarshalText() +} + +// UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d *Date) UnmarshalBinary(data []byte) error { + return d.UnmarshalText(data) +} + +// MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d Date) MarshalJSON() (json []byte, err error) { + return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil +} + +// UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d *Date) UnmarshalJSON(data []byte) (err error) { + d.Time, err = time.Parse(fullDateJSON, string(data)) + return err +} + +// MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d Date) MarshalText() (text []byte, err error) { + return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil +} + +// UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., +// 2006-01-02). +func (d *Date) UnmarshalText(data []byte) (err error) { + d.Time, err = time.Parse(fullDate, string(data)) + return err +} + +// String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). +func (d Date) String() string { + return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day()) +} + +// ToTime returns a Date as a time.Time +func (d Date) ToTime() time.Time { + return d.Time +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/Azure/go-autorest/autorest/date/time.go new file mode 100644 index 000000000000..fd3c5854e79d --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/time.go @@ -0,0 +1,70 @@ +package date + +import ( + "time" +) + +const ( + rfc3339JSON = `"` + time.RFC3339Nano + `"` + rfc3339 = time.RFC3339Nano +) + +// Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., +// 2006-01-02T15:04:05Z). +type Time struct { + time.Time +} + +// MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., +// 2006-01-02T15:04:05Z). +func (t Time) MarshalBinary() ([]byte, error) { + return t.Time.MarshalText() +} + +// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time +// (i.e., 2006-01-02T15:04:05Z). +func (t *Time) UnmarshalBinary(data []byte) error { + return t.UnmarshalText(data) +} + +// MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., +// 2006-01-02T15:04:05Z). +func (t Time) MarshalJSON() (json []byte, err error) { + return t.Time.MarshalJSON() +} + +// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time +// (i.e., 2006-01-02T15:04:05Z). +func (t *Time) UnmarshalJSON(data []byte) (err error) { + t.Time, err = ParseTime(rfc3339JSON, string(data)) + return err +} + +// MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., +// 2006-01-02T15:04:05Z). +func (t Time) MarshalText() (text []byte, err error) { + return t.Time.MarshalText() +} + +// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time +// (i.e., 2006-01-02T15:04:05Z). +func (t *Time) UnmarshalText(data []byte) (err error) { + t.Time, err = ParseTime(rfc3339, string(data)) + return err +} + +// String returns the Time formatted as an RFC3339 date-time string (i.e., +// 2006-01-02T15:04:05Z). +func (t Time) String() string { + // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. + b, err := t.MarshalText() + if err != nil { + return "" + } + return string(b) +} + +// ToTime returns a Time as a time.Time +func (t Time) ToTime() time.Time { + return t.Time +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go new file mode 100644 index 000000000000..11995fb9f2c5 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go @@ -0,0 +1,86 @@ +package date + +import ( + "errors" + "time" +) + +const ( + rfc1123JSON = `"` + time.RFC1123 + `"` + rfc1123 = time.RFC1123 +) + +// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +type TimeRFC1123 struct { + time.Time +} + +// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { + t.Time, err = ParseTime(rfc1123JSON, string(data)) + if err != nil { + return err + } + return nil +} + +// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalJSON() ([]byte, error) { + if y := t.Year(); y < 0 || y >= 10000 { + return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") + } + b := []byte(t.Format(rfc1123JSON)) + return b, nil +} + +// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalText() ([]byte, error) { + if y := t.Year(); y < 0 || y >= 10000 { + return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") + } + + b := []byte(t.Format(rfc1123)) + return b, nil +} + +// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { + t.Time, err = ParseTime(rfc1123, string(data)) + if err != nil { + return err + } + return nil +} + +// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalBinary() ([]byte, error) { + return t.MarshalText() +} + +// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { + return t.UnmarshalText(data) +} + +// ToTime returns a Time as a time.Time +func (t TimeRFC1123) ToTime() time.Time { + return t.Time +} + +// String returns the Time formatted as an RFC1123 date-time string (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) String() string { + // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. + b, err := t.MarshalText() + if err != nil { + return "" + } + return string(b) +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go new file mode 100644 index 000000000000..207b1a240a3a --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go @@ -0,0 +1,11 @@ +package date + +import ( + "strings" + "time" +) + +// ParseTime to parse Time string to specified format. +func ParseTime(format string, t string) (d time.Time, err error) { + return time.Parse(format, strings.ToUpper(t)) +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go new file mode 100644 index 000000000000..2e4fc79c10c0 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/error.go @@ -0,0 +1,77 @@ +package autorest + +import ( + "fmt" + "net/http" +) + +const ( + // UndefinedStatusCode is used when HTTP status code is not available for an error. + UndefinedStatusCode = 0 +) + +// DetailedError encloses a error with details of the package, method, and associated HTTP +// status code (if any). +type DetailedError struct { + Original error + + // PackageType is the package type of the object emitting the error. For types, the value + // matches that produced the the '%T' format specifier of the fmt package. For other elements, + // such as functions, it is just the package name (e.g., "autorest"). + PackageType string + + // Method is the name of the method raising the error. + Method string + + // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. + StatusCode interface{} + + // Message is the error message. + Message string +} + +// NewError creates a new Error conforming object from the passed packageType, method, and +// message. message is treated as a format string to which the optional args apply. +func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { + return NewErrorWithError(nil, packageType, method, nil, message, args...) +} + +// NewErrorWithResponse creates a new Error conforming object from the passed +// packageType, method, statusCode of the given resp (UndefinedStatusCode if +// resp is nil), and message. message is treated as a format string to which the +// optional args apply. +func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { + return NewErrorWithError(nil, packageType, method, resp, message, args...) +} + +// NewErrorWithError creates a new Error conforming object from the +// passed packageType, method, statusCode of the given resp (UndefinedStatusCode +// if resp is nil), message, and original error. message is treated as a format +// string to which the optional args apply. +func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { + if v, ok := original.(DetailedError); ok { + return v + } + + statusCode := UndefinedStatusCode + if resp != nil { + statusCode = resp.StatusCode + } + + return DetailedError{ + Original: original, + PackageType: packageType, + Method: method, + StatusCode: statusCode, + Message: fmt.Sprintf(message, args...), + } +} + +// Error returns a formatted containing all available details (i.e., PackageType, Method, +// StatusCode, Message, and original error (if any)). +func (e DetailedError) Error() string { + if e.Original == nil { + return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) + } + return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go new file mode 100644 index 000000000000..0f18c2aced86 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -0,0 +1,373 @@ +package autorest + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +const ( + mimeTypeJSON = "application/json" + mimeTypeFormPost = "application/x-www-form-urlencoded" + + headerAuthorization = "Authorization" + headerContentType = "Content-Type" + headerUserAgent = "User-Agent" +) + +// Preparer is the interface that wraps the Prepare method. +// +// Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations +// must ensure to not share or hold per-invocation state since Preparers may be shared and re-used. +type Preparer interface { + Prepare(*http.Request) (*http.Request, error) +} + +// PreparerFunc is a method that implements the Preparer interface. +type PreparerFunc func(*http.Request) (*http.Request, error) + +// Prepare implements the Preparer interface on PreparerFunc. +func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { + return pf(r) +} + +// PrepareDecorator takes and possibly decorates, by wrapping, a Preparer. Decorators may affect the +// http.Request and pass it along or, first, pass the http.Request along then affect the result. +type PrepareDecorator func(Preparer) Preparer + +// CreatePreparer creates, decorates, and returns a Preparer. +// Without decorators, the returned Preparer returns the passed http.Request unmodified. +// Preparers are safe to share and re-use. +func CreatePreparer(decorators ...PrepareDecorator) Preparer { + return DecoratePreparer( + Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), + decorators...) +} + +// DecoratePreparer accepts a Preparer and a, possibly empty, set of PrepareDecorators, which it +// applies to the Preparer. Decorators are applied in the order received, but their affect upon the +// request depends on whether they are a pre-decorator (change the http.Request and then pass it +// along) or a post-decorator (pass the http.Request along and alter it on return). +func DecoratePreparer(p Preparer, decorators ...PrepareDecorator) Preparer { + for _, decorate := range decorators { + p = decorate(p) + } + return p +} + +// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. +// It creates a Preparer from the decorators which it then applies to the passed http.Request. +func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { + if r == nil { + return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") + } + return CreatePreparer(decorators...).Prepare(r) +} + +// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed +// http.Request. +func WithNothing() PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + return p.Prepare(r) + }) + } +} + +// WithHeader returns a PrepareDecorator that sets the specified HTTP header of the http.Request to +// the passed value. It canonicalizes the passed header name (via http.CanonicalHeaderKey) before +// adding the header. +func WithHeader(header string, value string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.Header == nil { + r.Header = make(http.Header) + } + r.Header.Set(http.CanonicalHeaderKey(header), value) + } + return r, err + }) + } +} + +// WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose +// value is "Bearer " followed by the supplied token. +func WithBearerAuthorization(token string) PrepareDecorator { + return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", token)) +} + +// AsContentType returns a PrepareDecorator that adds an HTTP Content-Type header whose value +// is the passed contentType. +func AsContentType(contentType string) PrepareDecorator { + return WithHeader(headerContentType, contentType) +} + +// WithUserAgent returns a PrepareDecorator that adds an HTTP User-Agent header whose value is the +// passed string. +func WithUserAgent(ua string) PrepareDecorator { + return WithHeader(headerUserAgent, ua) +} + +// AsFormURLEncoded returns a PrepareDecorator that adds an HTTP Content-Type header whose value is +// "application/x-www-form-urlencoded". +func AsFormURLEncoded() PrepareDecorator { + return AsContentType(mimeTypeFormPost) +} + +// AsJSON returns a PrepareDecorator that adds an HTTP Content-Type header whose value is +// "application/json". +func AsJSON() PrepareDecorator { + return AsContentType(mimeTypeJSON) +} + +// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The +// decorator does not validate that the passed method string is a known HTTP method. +func WithMethod(method string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r.Method = method + return p.Prepare(r) + }) + } +} + +// AsDelete returns a PrepareDecorator that sets the HTTP method to DELETE. +func AsDelete() PrepareDecorator { return WithMethod("DELETE") } + +// AsGet returns a PrepareDecorator that sets the HTTP method to GET. +func AsGet() PrepareDecorator { return WithMethod("GET") } + +// AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. +func AsHead() PrepareDecorator { return WithMethod("HEAD") } + +// AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. +func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } + +// AsPatch returns a PrepareDecorator that sets the HTTP method to PATCH. +func AsPatch() PrepareDecorator { return WithMethod("PATCH") } + +// AsPost returns a PrepareDecorator that sets the HTTP method to POST. +func AsPost() PrepareDecorator { return WithMethod("POST") } + +// AsPut returns a PrepareDecorator that sets the HTTP method to PUT. +func AsPut() PrepareDecorator { return WithMethod("PUT") } + +// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed +// from the supplied baseUrl. +func WithBaseURL(baseURL string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + var u *url.URL + if u, err = url.Parse(baseURL); err != nil { + return r, err + } + if u.Scheme == "" { + err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) + } + if err == nil { + r.URL = u + } + } + return r, err + }) + } +} + +// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the +// http.Request body. +func WithFormData(v url.Values) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + s := v.Encode() + r.ContentLength = int64(len(s)) + r.Body = ioutil.NopCloser(strings.NewReader(s)) + } + return r, err + }) + } +} + +// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request +// and sets the Content-Length header. +func WithBool(v bool) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the +// request and sets the Content-Length header. +func WithFloat32(v float32) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the +// request and sets the Content-Length header. +func WithFloat64(v float64) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request +// and sets the Content-Length header. +func WithInt32(v int32) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request +// and sets the Content-Length header. +func WithInt64(v int64) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithString returns a PrepareDecorator that encodes the passed string into the body of the request +// and sets the Content-Length header. +func WithString(v string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + r.ContentLength = int64(len(v)) + r.Body = ioutil.NopCloser(strings.NewReader(v)) + } + return r, err + }) + } +} + +// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the +// request and sets the Content-Length header. +func WithJSON(v interface{}) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + b, err := json.Marshal(v) + if err == nil { + r.ContentLength = int64(len(b)) + r.Body = ioutil.NopCloser(bytes.NewReader(b)) + } + } + return r, err + }) + } +} + +// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path +// is absolute (that is, it begins with a "/"), it replaces the existing path. +func WithPath(path string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.URL == nil { + return r, NewError("autorest", "WithPath", "Invoked with a nil URL") + } + if r.URL, err = parseURL(r.URL, path); err != nil { + return r, err + } + } + return r, err + }) + } +} + +// WithEscapedPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the +// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. The +// values will be escaped (aka URL encoded) before insertion into the path. +func WithEscapedPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { + parameters := escapeValueStrings(ensureValueStrings(pathParameters)) + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.URL == nil { + return r, NewError("autorest", "WithEscapedPathParameters", "Invoked with a nil URL") + } + for key, value := range parameters { + path = strings.Replace(path, "{"+key+"}", value, -1) + } + if r.URL, err = parseURL(r.URL, path); err != nil { + return r, err + } + } + return r, err + }) + } +} + +// WithPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the +// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. +func WithPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { + parameters := ensureValueStrings(pathParameters) + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.URL == nil { + return r, NewError("autorest", "WithPathParameters", "Invoked with a nil URL") + } + for key, value := range parameters { + path = strings.Replace(path, "{"+key+"}", value, -1) + } + + if r.URL, err = parseURL(r.URL, path); err != nil { + return r, err + } + } + return r, err + }) + } +} + +func parseURL(u *url.URL, path string) (*url.URL, error) { + p := strings.TrimRight(u.String(), "/") + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + return url.Parse(p + path) +} + +// WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters +// given in the supplied map (i.e., key=value). +func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { + parameters := ensureValueStrings(queryParameters) + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.URL == nil { + return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") + } + v := r.URL.Query() + for key, value := range parameters { + v.Add(key, value) + } + r.URL.RawQuery = createQuery(v) + } + return r, err + }) + } +} + +// Authorizer is the interface that provides a PrepareDecorator used to supply request +// authorization. Most often, the Authorizer decorator runs last so it has access to the full +// state of the formed HTTP request. +type Authorizer interface { + WithAuthorization() PrepareDecorator +} + +// NullAuthorizer implements a default, "do nothing" Authorizer. +type NullAuthorizer struct{} + +// WithAuthorization returns a PrepareDecorator that does nothing. +func (na NullAuthorizer) WithAuthorization() PrepareDecorator { + return WithNothing() +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go new file mode 100644 index 000000000000..e377ad48afef --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/responder.go @@ -0,0 +1,208 @@ +package autorest + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "io/ioutil" + "net/http" + "strings" +) + +// Responder is the interface that wraps the Respond method. +// +// Respond accepts and reacts to an http.Response. Implementations must ensure to not share or hold +// state since Responders may be shared and re-used. +type Responder interface { + Respond(*http.Response) error +} + +// ResponderFunc is a method that implements the Responder interface. +type ResponderFunc func(*http.Response) error + +// Respond implements the Responder interface on ResponderFunc. +func (rf ResponderFunc) Respond(r *http.Response) error { + return rf(r) +} + +// RespondDecorator takes and possibly decorates, by wrapping, a Responder. Decorators may react to +// the http.Response and pass it along or, first, pass the http.Response along then react. +type RespondDecorator func(Responder) Responder + +// CreateResponder creates, decorates, and returns a Responder. Without decorators, the returned +// Responder returns the passed http.Response unmodified. Responders may or may not be safe to share +// and re-used: It depends on the applied decorators. For example, a standard decorator that closes +// the response body is fine to share whereas a decorator that reads the body into a passed struct +// is not. +// +// To prevent memory leaks, ensure that at least one Responder closes the response body. +func CreateResponder(decorators ...RespondDecorator) Responder { + return DecorateResponder( + Responder(ResponderFunc(func(r *http.Response) error { return nil })), + decorators...) +} + +// DecorateResponder accepts a Responder and a, possibly empty, set of RespondDecorators, which it +// applies to the Responder. Decorators are applied in the order received, but their affect upon the +// request depends on whether they are a pre-decorator (react to the http.Response and then pass it +// along) or a post-decorator (pass the http.Response along and then react). +func DecorateResponder(r Responder, decorators ...RespondDecorator) Responder { + for _, decorate := range decorators { + r = decorate(r) + } + return r +} + +// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. +// It creates a Responder from the decorators it then applies to the passed http.Response. +func Respond(r *http.Response, decorators ...RespondDecorator) error { + if r == nil { + return nil + } + return CreateResponder(decorators...).Respond(r) +} + +// ByIgnoring returns a RespondDecorator that ignores the passed http.Response passing it unexamined +// to the next RespondDecorator. +func ByIgnoring() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + return r.Respond(resp) + }) + } +} + +// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as +// the Body is read. +func ByCopying(b *bytes.Buffer) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && resp != nil && resp.Body != nil { + resp.Body = TeeReadCloser(resp.Body, b) + } + return err + }) + } +} + +// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it +// closes the response body. Since the passed Responder is invoked prior to closing the response +// body, the decorator may occur anywhere within the set. +func ByClosing() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if resp != nil && resp.Body != nil { + if err := resp.Body.Close(); err != nil { + return fmt.Errorf("Error closing the response body: %v", err) + } + } + return err + }) + } +} + +// ByClosingIfError returns a RespondDecorator that first invokes the passed Responder after which +// it closes the response if the passed Responder returns an error and the response body exists. +func ByClosingIfError() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err != nil && resp != nil && resp.Body != nil { + if err := resp.Body.Close(); err != nil { + return fmt.Errorf("Error closing the response body: %v", err) + } + } + return err + }) + } +} + +// ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the +// response Body into the value pointed to by v. +func ByUnmarshallingJSON(v interface{}) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil { + b, errInner := ioutil.ReadAll(resp.Body) + if errInner != nil { + err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) + } else if len(strings.Trim(string(b), " ")) > 0 { + errInner = json.Unmarshal(b, v) + if errInner != nil { + err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) + } + } + } + return err + }) + } +} + +// ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the +// response Body into the value pointed to by v. +func ByUnmarshallingXML(v interface{}) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil { + b, errInner := ioutil.ReadAll(resp.Body) + if errInner != nil { + err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) + } else { + errInner = xml.Unmarshal(b, v) + if errInner != nil { + err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) + } + } + } + return err + }) + } +} + +// WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response +// StatusCode is among the set passed. Since these are artificial errors, the response body +// may still require closing. +func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && !ResponseHasStatusCode(resp, codes...) { + err = NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", + resp.Request.Method, + resp.Request.URL, + resp.Status) + } + return err + }) + } +} + +// WithErrorUnlessOK returns a RespondDecorator that emits an error if the response StatusCode is +// anything other than HTTP 200. +func WithErrorUnlessOK() RespondDecorator { + return WithErrorUnlessStatusCode(http.StatusOK) +} + +// ExtractHeader extracts all values of the specified header from the http.Response. It returns an +// empty string slice if the passed http.Response is nil or the header does not exist. +func ExtractHeader(header string, resp *http.Response) []string { + if resp != nil && resp.Header != nil { + return resp.Header[http.CanonicalHeaderKey(header)] + } + return nil +} + +// ExtractHeaderValue extracts the first value of the specified header from the http.Response. It +// returns an empty string if the passed http.Response is nil or the header does not exist. +func ExtractHeaderValue(header string, resp *http.Response) string { + h := ExtractHeader(header, resp) + if len(h) > 0 { + return h[0] + } + return "" +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go new file mode 100644 index 000000000000..93e6489e9cee --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -0,0 +1,267 @@ +package autorest + +import ( + "bytes" + "fmt" + "io/ioutil" + "log" + "math" + "net/http" + "time" +) + +// Sender is the interface that wraps the Do method to send HTTP requests. +// +// The standard http.Client conforms to this interface. +type Sender interface { + Do(*http.Request) (*http.Response, error) +} + +// SenderFunc is a method that implements the Sender interface. +type SenderFunc func(*http.Request) (*http.Response, error) + +// Do implements the Sender interface on SenderFunc. +func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { + return sf(r) +} + +// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the +// http.Request and pass it along or, first, pass the http.Request along then react to the +// http.Response result. +type SendDecorator func(Sender) Sender + +// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. +func CreateSender(decorators ...SendDecorator) Sender { + return DecorateSender(&http.Client{}, decorators...) +} + +// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to +// the Sender. Decorators are applied in the order received, but their affect upon the request +// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a +// post-decorator (pass the http.Request along and react to the results in http.Response). +func DecorateSender(s Sender, decorators ...SendDecorator) Sender { + for _, decorate := range decorators { + s = decorate(s) + } + return s +} + +// Send sends, by means of the default http.Client, the passed http.Request, returning the +// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which +// it will apply the http.Client before invoking the Do method. +// +// Send is a convenience method and not recommended for production. Advanced users should use +// SendWithSender, passing and sharing their own Sender (e.g., instance of http.Client). +// +// Send will not poll or retry requests. +func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { + return SendWithSender(&http.Client{}, r, decorators...) +} + +// SendWithSender sends the passed http.Request, through the provided Sender, returning the +// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which +// it will apply the http.Client before invoking the Do method. +// +// SendWithSender will not poll or retry requests. +func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { + return DecorateSender(s, decorators...).Do(r) +} + +// AfterDelay returns a SendDecorator that delays for the passed time.Duration before +// invoking the Sender. The delay may be terminated by closing the optional channel on the +// http.Request. If canceled, no further Senders are invoked. +func AfterDelay(d time.Duration) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + if !DelayForBackoff(d, 1, r.Cancel) { + return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") + } + return s.Do(r) + }) + } +} + +// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. +func AsIs() SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + return s.Do(r) + }) + } +} + +// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which +// it closes the response if the passed Sender returns an error and the response body exists. +func DoCloseIfError() SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + resp, err := s.Do(r) + if err != nil { + Respond(resp, ByClosing()) + } + return resp, err + }) + } +} + +// DoErrorIfStatusCode returns a SendDecorator that emits an error if the response StatusCode is +// among the set passed. Since these are artificial errors, the response body may still require +// closing. +func DoErrorIfStatusCode(codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + resp, err := s.Do(r) + if err == nil && ResponseHasStatusCode(resp, codes...) { + err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", + resp.Request.Method, + resp.Request.URL, + resp.Status) + } + return resp, err + }) + } +} + +// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response +// StatusCode is among the set passed. Since these are artificial errors, the response body +// may still require closing. +func DoErrorUnlessStatusCode(codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + resp, err := s.Do(r) + if err == nil && !ResponseHasStatusCode(resp, codes...) { + err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", + resp.Request.Method, + resp.Request.URL, + resp.Status) + } + return resp, err + }) + } +} + +// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the +// passed status codes. It expects the http.Response to contain a Location header providing the +// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than +// the supplied duration. It will delay between requests for the duration specified in the +// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by +// closing the optional channel on the http.Request. +func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + resp, err = s.Do(r) + + if err == nil && ResponseHasStatusCode(resp, codes...) { + r, err = NewPollingRequest(resp, r.Cancel) + + for err == nil && ResponseHasStatusCode(resp, codes...) { + Respond(resp, + ByClosing()) + resp, err = SendWithSender(s, r, + AfterDelay(GetRetryAfter(resp, delay))) + } + } + + return resp, err + }) + } +} + +// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified +// number of attempts, exponentially backing off between requests using the supplied backoff +// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on +// the http.Request. +func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + for attempt := 0; attempt < attempts; attempt++ { + resp, err = s.Do(r) + if err == nil { + return resp, err + } + DelayForBackoff(backoff, attempt, r.Cancel) + } + return resp, err + }) + } +} + +// DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified +// number of attempts, exponentially backing off between requests using the supplied backoff +// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on +// the http.Request. +func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + b := []byte{} + if r.Body != nil { + b, err = ioutil.ReadAll(r.Body) + if err != nil { + return resp, err + } + } + + // Increment to add the first call (attempts denotes number of retries) + attempts++ + for attempt := 0; attempt < attempts; attempt++ { + r.Body = ioutil.NopCloser(bytes.NewBuffer(b)) + resp, err = s.Do(r) + if err != nil || !ResponseHasStatusCode(resp, codes...) { + return resp, err + } + DelayForBackoff(backoff, attempt, r.Cancel) + } + return resp, err + }) + } +} + +// DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal +// to or greater than the specified duration, exponentially backing off between requests using the +// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the +// optional channel on the http.Request. +func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + end := time.Now().Add(d) + for attempt := 0; time.Now().Before(end); attempt++ { + resp, err = s.Do(r) + if err == nil { + return resp, err + } + DelayForBackoff(backoff, attempt, r.Cancel) + } + return resp, err + }) + } +} + +// WithLogging returns a SendDecorator that implements simple before and after logging of the +// request. +func WithLogging(logger *log.Logger) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + logger.Printf("Sending %s %s", r.Method, r.URL) + resp, err := s.Do(r) + if err != nil { + logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) + } else { + logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) + } + return resp, err + }) + } +} + +// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of +// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set +// to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, +// returns false. +func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { + select { + case <-time.After(time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second): + return true + case <-cancel: + return false + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go new file mode 100644 index 000000000000..7b180b866b90 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go @@ -0,0 +1,133 @@ +/* +Package to provides helpers to ease working with pointer values of marshalled structures. +*/ +package to + +// String returns a string value for the passed string pointer. It returns the empty string if the +// pointer is nil. +func String(s *string) string { + if s != nil { + return *s + } + return "" +} + +// StringPtr returns a pointer to the passed string. +func StringPtr(s string) *string { + return &s +} + +// StringSlice returns a string slice value for the passed string slice pointer. It returns a nil +// slice if the pointer is nil. +func StringSlice(s *[]string) []string { + if s != nil { + return *s + } + return nil +} + +// StringSlicePtr returns a pointer to the passed string slice. +func StringSlicePtr(s []string) *[]string { + return &s +} + +// StringMap returns a map of strings built from the map of string pointers. The empty string is +// used for nil pointers. +func StringMap(msp map[string]*string) map[string]string { + ms := make(map[string]string, len(msp)) + for k, sp := range msp { + if sp != nil { + ms[k] = *sp + } else { + ms[k] = "" + } + } + return ms +} + +// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. +func StringMapPtr(ms map[string]string) *map[string]*string { + msp := make(map[string]*string, len(ms)) + for k, s := range ms { + msp[k] = StringPtr(s) + } + return &msp +} + +// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. +func Bool(b *bool) bool { + if b != nil { + return *b + } + return false +} + +// BoolPtr returns a pointer to the passed bool. +func BoolPtr(b bool) *bool { + return &b +} + +// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. +func Int(i *int) int { + if i != nil { + return *i + } + return 0 +} + +// IntPtr returns a pointer to the passed int. +func IntPtr(i int) *int { + return &i +} + +// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. +func Int32(i *int32) int32 { + if i != nil { + return *i + } + return 0 +} + +// Int32Ptr returns a pointer to the passed int32. +func Int32Ptr(i int32) *int32 { + return &i +} + +// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. +func Int64(i *int64) int64 { + if i != nil { + return *i + } + return 0 +} + +// Int64Ptr returns a pointer to the passed int64. +func Int64Ptr(i int64) *int64 { + return &i +} + +// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. +func Float32(i *float32) float32 { + if i != nil { + return *i + } + return 0.0 +} + +// Float32Ptr returns a pointer to the passed float32. +func Float32Ptr(i float32) *float32 { + return &i +} + +// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. +func Float64(i *float64) float64 { + if i != nil { + return *i + } + return 0.0 +} + +// Float64Ptr returns a pointer to the passed float64. +func Float64Ptr(i float64) *float64 { + return &i +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go new file mode 100644 index 000000000000..b7f4a723b1c8 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/utility.go @@ -0,0 +1,161 @@ +package autorest + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/url" + "sort" + "strings" +) + +// EncodedAs is a series of constants specifying various data encodings +type EncodedAs string + +const ( + // EncodedAsJSON states that data is encoded as JSON + EncodedAsJSON EncodedAs = "JSON" + + // EncodedAsXML states that data is encoded as Xml + EncodedAsXML EncodedAs = "XML" +) + +// Decoder defines the decoding method json.Decoder and xml.Decoder share +type Decoder interface { + Decode(v interface{}) error +} + +// NewDecoder creates a new decoder appropriate to the passed encoding. +// encodedAs specifies the type of encoding and r supplies the io.Reader containing the +// encoded data. +func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { + if encodedAs == EncodedAsJSON { + return json.NewDecoder(r) + } else if encodedAs == EncodedAsXML { + return xml.NewDecoder(r) + } + return nil +} + +// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy +// is especially useful if there is a chance the data will fail to decode. +// encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v +// is the decoding destination. +func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { + b := bytes.Buffer{} + return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) +} + +// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. +// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. +// Further, when it is closed, it ensures that rc is closed as well. +func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { + return &teeReadCloser{rc, io.TeeReader(rc, w)} +} + +type teeReadCloser struct { + rc io.ReadCloser + r io.Reader +} + +func (t *teeReadCloser) Read(p []byte) (int, error) { + return t.r.Read(p) +} + +func (t *teeReadCloser) Close() error { + return t.rc.Close() +} + +func containsInt(ints []int, n int) bool { + for _, i := range ints { + if i == n { + return true + } + } + return false +} + +func escapeValueStrings(m map[string]string) map[string]string { + for key, value := range m { + m[key] = url.QueryEscape(value) + } + return m +} + +func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { + mapOfStrings := make(map[string]string) + for key, value := range mapOfInterface { + mapOfStrings[key] = ensureValueString(value) + } + return mapOfStrings +} + +func ensureValueString(value interface{}) string { + if value == nil { + return "" + } + switch v := value.(type) { + case string: + return v + case []byte: + return string(v) + default: + return fmt.Sprintf("%v", v) + } +} + +// String method converts interface v to string. If interface is a list, it +// joins list elements using separator. +func String(v interface{}, sep ...string) string { + if len(sep) > 0 { + return ensureValueString(strings.Join(v.([]string), sep[0])) + } + return ensureValueString(v) +} + +// Encode method encodes url path and query parameters. +func Encode(location string, v interface{}, sep ...string) string { + s := String(v, sep...) + switch strings.ToLower(location) { + case "path": + return pathEscape(s) + case "query": + return queryEscape(s) + default: + return s + } +} + +func pathEscape(s string) string { + return strings.Replace(url.QueryEscape(s), "+", "%20", -1) +} + +func queryEscape(s string) string { + return url.QueryEscape(s) +} + +// This method is same as Encode() method of "net/url" go package, +// except it does not encode the query parameters because they +// already come encoded. It formats values map in query format (bar=foo&a=b). +func createQuery(v url.Values) string { + var buf bytes.Buffer + keys := make([]string, 0, len(v)) + for k := range v { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + vs := v[k] + prefix := url.QueryEscape(k) + "=" + for _, v := range vs { + if buf.Len() > 0 { + buf.WriteByte('&') + } + buf.WriteString(prefix) + buf.WriteString(v) + } + } + return buf.String() +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go new file mode 100644 index 000000000000..8031a332cd2d --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -0,0 +1,18 @@ +package autorest + +import ( + "fmt" +) + +const ( + major = "7" + minor = "0" + patch = "0" + tag = "" + semVerFormat = "%s.%s.%s%s" +) + +// Version returns the semantic version (see http://semver.org). +func Version() string { + return fmt.Sprintf(semVerFormat, major, minor, patch, tag) +} diff --git a/vendor/github.com/cloudflare/cfssl/LICENSE b/vendor/github.com/cloudflare/cfssl/LICENSE new file mode 100644 index 000000000000..bc5841fa5597 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2014 CloudFlare Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/cloudflare/cfssl/auth/auth.go b/vendor/github.com/cloudflare/cfssl/auth/auth.go new file mode 100644 index 000000000000..ecd5e5fefdaf --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/auth/auth.go @@ -0,0 +1,94 @@ +// Package auth implements an interface for providing CFSSL +// authentication. This is meant to authenticate a client CFSSL to a +// remote CFSSL in order to prevent unauthorised use of the signature +// capabilities. This package provides both the interface and a +// standard HMAC-based implementation. +package auth + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "io/ioutil" + "os" + "strings" +) + +// An AuthenticatedRequest contains a request and authentication +// token. The Provider may determine whether to validate the timestamp +// and remote address. +type AuthenticatedRequest struct { + // An Authenticator decides whether to use this field. + Timestamp int64 `json:"timestamp,omitempty"` + RemoteAddress []byte `json:"remote_address,omitempty"` + Token []byte `json:"token"` + Request []byte `json:"request"` +} + +// A Provider can generate tokens from a request and verify a +// request. The handling of additional authentication data (such as +// the IP address) is handled by the concrete type, as is any +// serialisation and state-keeping. +type Provider interface { + Token(req []byte) (token []byte, err error) + Verify(aReq *AuthenticatedRequest) bool +} + +// Standard implements an HMAC-SHA-256 authentication provider. It may +// be supplied additional data at creation time that will be used as +// request || additional-data with the HMAC. +type Standard struct { + key []byte + ad []byte +} + +// New generates a new standard authentication provider from the key +// and additional data. The additional data will be used when +// generating a new token. +func New(key string, ad []byte) (*Standard, error) { + if splitKey := strings.SplitN(key, ":", 2); len(splitKey) == 2 { + switch splitKey[0] { + case "env": + key = os.Getenv(splitKey[1]) + case "file": + data, err := ioutil.ReadFile(splitKey[1]) + if err != nil { + return nil, err + } + key = string(data) + default: + return nil, fmt.Errorf("unknown key prefix: %s", splitKey[0]) + } + } + + keyBytes, err := hex.DecodeString(key) + if err != nil { + return nil, err + } + + return &Standard{keyBytes, ad}, nil +} + +// Token generates a new authentication token from the request. +func (p Standard) Token(req []byte) (token []byte, err error) { + h := hmac.New(sha256.New, p.key) + h.Write(req) + h.Write(p.ad) + return h.Sum(nil), nil +} + +// Verify determines whether an authenticated request is valid. +func (p Standard) Verify(ad *AuthenticatedRequest) bool { + if ad == nil { + return false + } + + // Standard token generation returns no error. + token, _ := p.Token(ad.Request) + if len(ad.Token) != len(token) { + return false + } + + return hmac.Equal(token, ad.Token) +} diff --git a/vendor/github.com/cloudflare/cfssl/certdb/README.md b/vendor/github.com/cloudflare/cfssl/certdb/README.md new file mode 100644 index 000000000000..18c6a2803095 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/certdb/README.md @@ -0,0 +1,58 @@ +# certdb usage + +Using a database enables additional functionality for existing commands when a +db config is provided: + + - `sign` and `gencert` add a certificate to the certdb after signing it + - `serve` enables database functionality for the sign and revoke endpoints + +A database is required for the following: + + - `revoke` marks certificates revoked in the database with an optional reason + - `ocsprefresh` refreshes the table of cached OCSP responses + - `ocspdump` outputs cached OCSP responses in a concatenated base64-encoded format + +## Setup/Migration + +This directory stores [goose](https://bitbucket.org/liamstask/goose/) db migration scripts for various DB backends. +Currently supported: + - SQLite in sqlite + - PostgreSQL in pg + +### Get goose + + go get https://bitbucket.org/liamstask/goose/ + +### Use goose to start and terminate a SQLite DB +To start a SQLite DB using goose: + + goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/sqlite up' + +To tear down a SQLite DB using goose + + goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/sqlite down + +### Use goose to start and terminate a PostgreSQL DB +To start a PostgreSQL using goose: + + goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/pg up + +To tear down a PostgreSQL DB using goose + + goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/pg down + +Note: the administration of PostgreSQL DB is not included. We assume +the databases being connected to are already created and access control +are properly handled. + +## CFSSL Configuration + +Several cfssl commands take a -db-config flag. Create a file with a +JSON dictionary: + + {"driver":"sqlite3","data_source":"certs.db"} + +or + + {"driver":"postgres","data_source":"postgres://user:password@host/db"} + diff --git a/vendor/github.com/cloudflare/cfssl/certdb/certdb.go b/vendor/github.com/cloudflare/cfssl/certdb/certdb.go new file mode 100644 index 000000000000..96694f768596 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/certdb/certdb.go @@ -0,0 +1,40 @@ +package certdb + +import ( + "time" +) + +// CertificateRecord encodes a certificate and its metadata +// that will be recorded in a database. +type CertificateRecord struct { + Serial string `db:"serial_number"` + AKI string `db:"authority_key_identifier"` + CALabel string `db:"ca_label"` + Status string `db:"status"` + Reason int `db:"reason"` + Expiry time.Time `db:"expiry"` + RevokedAt time.Time `db:"revoked_at"` + PEM string `db:"pem"` +} + +// OCSPRecord encodes a OCSP response body and its metadata +// that will be recorded in a database. +type OCSPRecord struct { + Serial string `db:"serial_number"` + AKI string `db:"authority_key_identifier"` + Body string `db:"body"` + Expiry time.Time `db:"expiry"` +} + +// Accessor abstracts the CRUD of certdb objects from a DB. +type Accessor interface { + InsertCertificate(cr CertificateRecord) error + GetCertificate(serial, aki string) ([]CertificateRecord, error) + GetUnexpiredCertificates() ([]CertificateRecord, error) + RevokeCertificate(serial, aki string, reasonCode int) error + InsertOCSP(rr OCSPRecord) error + GetOCSP(serial, aki string) ([]OCSPRecord, error) + GetUnexpiredOCSPs() ([]OCSPRecord, error) + UpdateOCSP(serial, aki, body string, expiry time.Time) error + UpsertOCSP(serial, aki, body string, expiry time.Time) error +} diff --git a/vendor/github.com/cloudflare/cfssl/config/config.go b/vendor/github.com/cloudflare/cfssl/config/config.go new file mode 100644 index 000000000000..a6837eb0db76 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/config/config.go @@ -0,0 +1,563 @@ +// Package config contains the configuration logic for CFSSL. +package config + +import ( + "crypto/x509" + "encoding/asn1" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "regexp" + "strconv" + "strings" + "time" + + "github.com/cloudflare/cfssl/auth" + cferr "github.com/cloudflare/cfssl/errors" + "github.com/cloudflare/cfssl/helpers" + "github.com/cloudflare/cfssl/log" + ocspConfig "github.com/cloudflare/cfssl/ocsp/config" +) + +// A CSRWhitelist stores booleans for fields in the CSR. If a CSRWhitelist is +// not present in a SigningProfile, all of these fields may be copied from the +// CSR into the signed certificate. If a CSRWhitelist *is* present in a +// SigningProfile, only those fields with a `true` value in the CSRWhitelist may +// be copied from the CSR to the signed certificate. Note that some of these +// fields, like Subject, can be provided or partially provided through the API. +// Since API clients are expected to be trusted, but CSRs are not, fields +// provided through the API are not subject to whitelisting through this +// mechanism. +type CSRWhitelist struct { + Subject, PublicKeyAlgorithm, PublicKey, SignatureAlgorithm bool + DNSNames, IPAddresses, EmailAddresses bool +} + +// OID is our own version of asn1's ObjectIdentifier, so we can define a custom +// JSON marshal / unmarshal. +type OID asn1.ObjectIdentifier + +// CertificatePolicy represents the ASN.1 PolicyInformation structure from +// https://tools.ietf.org/html/rfc3280.html#page-106. +// Valid values of Type are "id-qt-unotice" and "id-qt-cps" +type CertificatePolicy struct { + ID OID + Qualifiers []CertificatePolicyQualifier +} + +// CertificatePolicyQualifier represents a single qualifier from an ASN.1 +// PolicyInformation structure. +type CertificatePolicyQualifier struct { + Type string + Value string +} + +// AuthRemote is an authenticated remote signer. +type AuthRemote struct { + RemoteName string `json:"remote"` + AuthKeyName string `json:"auth_key"` +} + +// A SigningProfile stores information that the CA needs to store +// signature policy. +type SigningProfile struct { + Usage []string `json:"usages"` + IssuerURL []string `json:"issuer_urls"` + OCSP string `json:"ocsp_url"` + CRL string `json:"crl_url"` + CA bool `json:"is_ca"` + OCSPNoCheck bool `json:"ocsp_no_check"` + ExpiryString string `json:"expiry"` + BackdateString string `json:"backdate"` + AuthKeyName string `json:"auth_key"` + RemoteName string `json:"remote"` + NotBefore time.Time `json:"not_before"` + NotAfter time.Time `json:"not_after"` + NameWhitelistString string `json:"name_whitelist"` + AuthRemote AuthRemote `json:"auth_remote"` + CTLogServers []string `json:"ct_log_servers"` + AllowedExtensions []OID `json:"allowed_extensions"` + CertStore string `json:"cert_store"` + + Policies []CertificatePolicy + Expiry time.Duration + Backdate time.Duration + Provider auth.Provider + RemoteProvider auth.Provider + RemoteServer string + CSRWhitelist *CSRWhitelist + NameWhitelist *regexp.Regexp + ExtensionWhitelist map[string]bool + ClientProvidesSerialNumbers bool +} + +// UnmarshalJSON unmarshals a JSON string into an OID. +func (oid *OID) UnmarshalJSON(data []byte) (err error) { + if data[0] != '"' || data[len(data)-1] != '"' { + return errors.New("OID JSON string not wrapped in quotes." + string(data)) + } + data = data[1 : len(data)-1] + parsedOid, err := parseObjectIdentifier(string(data)) + if err != nil { + return err + } + *oid = OID(parsedOid) + return +} + +// MarshalJSON marshals an oid into a JSON string. +func (oid OID) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%v"`, asn1.ObjectIdentifier(oid))), nil +} + +func parseObjectIdentifier(oidString string) (oid asn1.ObjectIdentifier, err error) { + validOID, err := regexp.MatchString("\\d(\\.\\d+)*", oidString) + if err != nil { + return + } + if !validOID { + err = errors.New("Invalid OID") + return + } + + segments := strings.Split(oidString, ".") + oid = make(asn1.ObjectIdentifier, len(segments)) + for i, intString := range segments { + oid[i], err = strconv.Atoi(intString) + if err != nil { + return + } + } + return +} + +const timeFormat = "2006-01-02T15:04:05" + +// populate is used to fill in the fields that are not in JSON +// +// First, the ExpiryString parameter is needed to parse +// expiration timestamps from JSON. The JSON decoder is not able to +// decode a string time duration to a time.Duration, so this is called +// when loading the configuration to properly parse and fill out the +// Expiry parameter. +// This function is also used to create references to the auth key +// and default remote for the profile. +// It returns true if ExpiryString is a valid representation of a +// time.Duration, and the AuthKeyString and RemoteName point to +// valid objects. It returns false otherwise. +func (p *SigningProfile) populate(cfg *Config) error { + if p == nil { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("can't parse nil profile")) + } + + var err error + if p.RemoteName == "" && p.AuthRemote.RemoteName == "" { + log.Debugf("parse expiry in profile") + if p.ExpiryString == "" { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("empty expiry string")) + } + + dur, err := time.ParseDuration(p.ExpiryString) + if err != nil { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err) + } + + log.Debugf("expiry is valid") + p.Expiry = dur + + if p.BackdateString != "" { + dur, err = time.ParseDuration(p.BackdateString) + if err != nil { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err) + } + + p.Backdate = dur + } + + if !p.NotBefore.IsZero() && !p.NotAfter.IsZero() && p.NotAfter.Before(p.NotBefore) { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err) + } + + if len(p.Policies) > 0 { + for _, policy := range p.Policies { + for _, qualifier := range policy.Qualifiers { + if qualifier.Type != "" && qualifier.Type != "id-qt-unotice" && qualifier.Type != "id-qt-cps" { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("invalid policy qualifier type")) + } + } + } + } + } else if p.RemoteName != "" { + log.Debug("match remote in profile to remotes section") + if p.AuthRemote.RemoteName != "" { + log.Error("profile has both a remote and an auth remote specified") + return cferr.New(cferr.PolicyError, cferr.InvalidPolicy) + } + if remote := cfg.Remotes[p.RemoteName]; remote != "" { + if err := p.updateRemote(remote); err != nil { + return err + } + } else { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to find remote in remotes section")) + } + } else { + log.Debug("match auth remote in profile to remotes section") + if remote := cfg.Remotes[p.AuthRemote.RemoteName]; remote != "" { + if err := p.updateRemote(remote); err != nil { + return err + } + } else { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to find remote in remotes section")) + } + } + + if p.AuthKeyName != "" { + log.Debug("match auth key in profile to auth_keys section") + if key, ok := cfg.AuthKeys[p.AuthKeyName]; ok == true { + if key.Type == "standard" { + p.Provider, err = auth.New(key.Key, nil) + if err != nil { + log.Debugf("failed to create new standard auth provider: %v", err) + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to create new standard auth provider")) + } + } else { + log.Debugf("unknown authentication type %v", key.Type) + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("unknown authentication type")) + } + } else { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to find auth_key in auth_keys section")) + } + } + + if p.AuthRemote.AuthKeyName != "" { + log.Debug("match auth remote key in profile to auth_keys section") + if key, ok := cfg.AuthKeys[p.AuthRemote.AuthKeyName]; ok == true { + if key.Type == "standard" { + p.RemoteProvider, err = auth.New(key.Key, nil) + if err != nil { + log.Debugf("failed to create new standard auth provider: %v", err) + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to create new standard auth provider")) + } + } else { + log.Debugf("unknown authentication type %v", key.Type) + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("unknown authentication type")) + } + } else { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to find auth_remote's auth_key in auth_keys section")) + } + } + + if p.NameWhitelistString != "" { + log.Debug("compiling whitelist regular expression") + rule, err := regexp.Compile(p.NameWhitelistString) + if err != nil { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to compile name whitelist section")) + } + p.NameWhitelist = rule + } + + p.ExtensionWhitelist = map[string]bool{} + for _, oid := range p.AllowedExtensions { + p.ExtensionWhitelist[asn1.ObjectIdentifier(oid).String()] = true + } + + return nil +} + +// updateRemote takes a signing profile and initializes the remote server object +// to the hostname:port combination sent by remote. +func (p *SigningProfile) updateRemote(remote string) error { + if remote != "" { + p.RemoteServer = remote + } + return nil +} + +// OverrideRemotes takes a signing configuration and updates the remote server object +// to the hostname:port combination sent by remote +func (p *Signing) OverrideRemotes(remote string) error { + if remote != "" { + var err error + for _, profile := range p.Profiles { + err = profile.updateRemote(remote) + if err != nil { + return err + } + } + err = p.Default.updateRemote(remote) + if err != nil { + return err + } + } + return nil +} + +// NeedsRemoteSigner returns true if one of the profiles has a remote set +func (p *Signing) NeedsRemoteSigner() bool { + for _, profile := range p.Profiles { + if profile.RemoteServer != "" { + return true + } + } + + if p.Default.RemoteServer != "" { + return true + } + + return false +} + +// NeedsLocalSigner returns true if one of the profiles doe not have a remote set +func (p *Signing) NeedsLocalSigner() bool { + for _, profile := range p.Profiles { + if profile.RemoteServer == "" { + return true + } + } + + if p.Default.RemoteServer == "" { + return true + } + + return false +} + +// Usages parses the list of key uses in the profile, translating them +// to a list of X.509 key usages and extended key usages. The unknown +// uses are collected into a slice that is also returned. +func (p *SigningProfile) Usages() (ku x509.KeyUsage, eku []x509.ExtKeyUsage, unk []string) { + for _, keyUse := range p.Usage { + if kuse, ok := KeyUsage[keyUse]; ok { + ku |= kuse + } else if ekuse, ok := ExtKeyUsage[keyUse]; ok { + eku = append(eku, ekuse) + } else { + unk = append(unk, keyUse) + } + } + return +} + +// A valid profile must be a valid local profile or a valid remote profile. +// A valid local profile has defined at least key usages to be used, and a +// valid local default profile has defined at least a default expiration. +// A valid remote profile (default or not) has remote signer initialized. +// In addition, a remote profile must has a valid auth provider if auth +// key defined. +func (p *SigningProfile) validProfile(isDefault bool) bool { + if p == nil { + return false + } + + if p.RemoteName != "" { + log.Debugf("validate remote profile") + + if p.RemoteServer == "" { + log.Debugf("invalid remote profile: no remote signer specified") + return false + } + + if p.AuthKeyName != "" && p.Provider == nil { + log.Debugf("invalid remote profile: auth key name is defined but no auth provider is set") + return false + } + + if p.AuthRemote.RemoteName != "" { + log.Debugf("invalid remote profile: auth remote is also specified") + } + } else if p.AuthRemote.RemoteName != "" { + log.Debugf("validate auth remote profile") + if p.RemoteServer == "" { + log.Debugf("invalid auth remote profile: no remote signer specified") + return false + } + + if p.AuthRemote.AuthKeyName == "" || p.RemoteProvider == nil { + log.Debugf("invalid auth remote profile: no auth key is defined") + return false + } + } else { + log.Debugf("validate local profile") + if !isDefault { + if len(p.Usage) == 0 { + log.Debugf("invalid local profile: no usages specified") + return false + } else if _, _, unk := p.Usages(); len(unk) == len(p.Usage) { + log.Debugf("invalid local profile: no valid usages") + return false + } + } else { + if p.Expiry == 0 { + log.Debugf("invalid local profile: no expiry set") + return false + } + } + } + + log.Debugf("profile is valid") + return true +} + +// Signing codifies the signature configuration policy for a CA. +type Signing struct { + Profiles map[string]*SigningProfile `json:"profiles"` + Default *SigningProfile `json:"default"` +} + +// Config stores configuration information for the CA. +type Config struct { + Signing *Signing `json:"signing"` + OCSP *ocspConfig.Config `json:"ocsp"` + AuthKeys map[string]AuthKey `json:"auth_keys,omitempty"` + Remotes map[string]string `json:"remotes,omitempty"` +} + +// Valid ensures that Config is a valid configuration. It should be +// called immediately after parsing a configuration file. +func (c *Config) Valid() bool { + return c.Signing.Valid() +} + +// Valid checks the signature policies, ensuring they are valid +// policies. A policy is valid if it has defined at least key usages +// to be used, and a valid default profile has defined at least a +// default expiration. +func (p *Signing) Valid() bool { + if p == nil { + return false + } + + log.Debugf("validating configuration") + if !p.Default.validProfile(true) { + log.Debugf("default profile is invalid") + return false + } + + for _, sp := range p.Profiles { + if !sp.validProfile(false) { + log.Debugf("invalid profile") + return false + } + } + return true +} + +// KeyUsage contains a mapping of string names to key usages. +var KeyUsage = map[string]x509.KeyUsage{ + "signing": x509.KeyUsageDigitalSignature, + "digital signature": x509.KeyUsageDigitalSignature, + "content committment": x509.KeyUsageContentCommitment, + "key encipherment": x509.KeyUsageKeyEncipherment, + "key agreement": x509.KeyUsageKeyAgreement, + "data encipherment": x509.KeyUsageDataEncipherment, + "cert sign": x509.KeyUsageCertSign, + "crl sign": x509.KeyUsageCRLSign, + "encipher only": x509.KeyUsageEncipherOnly, + "decipher only": x509.KeyUsageDecipherOnly, +} + +// ExtKeyUsage contains a mapping of string names to extended key +// usages. +var ExtKeyUsage = map[string]x509.ExtKeyUsage{ + "any": x509.ExtKeyUsageAny, + "server auth": x509.ExtKeyUsageServerAuth, + "client auth": x509.ExtKeyUsageClientAuth, + "code signing": x509.ExtKeyUsageCodeSigning, + "email protection": x509.ExtKeyUsageEmailProtection, + "s/mime": x509.ExtKeyUsageEmailProtection, + "ipsec end system": x509.ExtKeyUsageIPSECEndSystem, + "ipsec tunnel": x509.ExtKeyUsageIPSECTunnel, + "ipsec user": x509.ExtKeyUsageIPSECUser, + "timestamping": x509.ExtKeyUsageTimeStamping, + "ocsp signing": x509.ExtKeyUsageOCSPSigning, + "microsoft sgc": x509.ExtKeyUsageMicrosoftServerGatedCrypto, + "netscape sgc": x509.ExtKeyUsageNetscapeServerGatedCrypto, +} + +// An AuthKey contains an entry for a key used for authentication. +type AuthKey struct { + // Type contains information needed to select the appropriate + // constructor. For example, "standard" for HMAC-SHA-256, + // "standard-ip" for HMAC-SHA-256 incorporating the client's + // IP. + Type string `json:"type"` + // Key contains the key information, such as a hex-encoded + // HMAC key. + Key string `json:"key"` +} + +// DefaultConfig returns a default configuration specifying basic key +// usage and a 1 year expiration time. The key usages chosen are +// signing, key encipherment, client auth and server auth. +func DefaultConfig() *SigningProfile { + d := helpers.OneYear + return &SigningProfile{ + Usage: []string{"signing", "key encipherment", "server auth", "client auth"}, + Expiry: d, + ExpiryString: "8760h", + } +} + +// LoadFile attempts to load the configuration file stored at the path +// and returns the configuration. On error, it returns nil. +func LoadFile(path string) (*Config, error) { + log.Debugf("loading configuration file from %s", path) + if path == "" { + return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid path")) + } + + body, err := ioutil.ReadFile(path) + if err != nil { + return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("could not read configuration file")) + } + + return LoadConfig(body) +} + +// LoadConfig attempts to load the configuration from a byte slice. +// On error, it returns nil. +func LoadConfig(config []byte) (*Config, error) { + var cfg = &Config{} + err := json.Unmarshal(config, &cfg) + if err != nil { + return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, + errors.New("failed to unmarshal configuration: "+err.Error())) + } + + if cfg.Signing == nil { + return nil, errors.New("No \"signing\" field present") + } + + if cfg.Signing.Default == nil { + log.Debugf("no default given: using default config") + cfg.Signing.Default = DefaultConfig() + } else { + if err := cfg.Signing.Default.populate(cfg); err != nil { + return nil, err + } + } + + for k := range cfg.Signing.Profiles { + if err := cfg.Signing.Profiles[k].populate(cfg); err != nil { + return nil, err + } + } + + if !cfg.Valid() { + return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid configuration")) + } + + log.Debugf("configuration ok") + return cfg, nil +} diff --git a/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go b/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go new file mode 100644 index 000000000000..8db547fce597 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go @@ -0,0 +1,188 @@ +// Package pkcs7 implements the subset of the CMS PKCS #7 datatype that is typically +// used to package certificates and CRLs. Using openssl, every certificate converted +// to PKCS #7 format from another encoding such as PEM conforms to this implementation. +// reference: https://www.openssl.org/docs/apps/crl2pkcs7.html +// +// PKCS #7 Data type, reference: https://tools.ietf.org/html/rfc2315 +// +// The full pkcs#7 cryptographic message syntax allows for cryptographic enhancements, +// for example data can be encrypted and signed and then packaged through pkcs#7 to be +// sent over a network and then verified and decrypted. It is asn1, and the type of +// PKCS #7 ContentInfo, which comprises the PKCS #7 structure, is: +// +// ContentInfo ::= SEQUENCE { +// contentType ContentType, +// content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL +// } +// +// There are 6 possible ContentTypes, data, signedData, envelopedData, +// signedAndEnvelopedData, digestedData, and encryptedData. Here signedData, Data, and encrypted +// Data are implemented, as the degenerate case of signedData without a signature is the typical +// format for transferring certificates and CRLS, and Data and encryptedData are used in PKCS #12 +// formats. +// The ContentType signedData has the form: +// +// +// signedData ::= SEQUENCE { +// version Version, +// digestAlgorithms DigestAlgorithmIdentifiers, +// contentInfo ContentInfo, +// certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL +// crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, +// signerInfos SignerInfos +// } +// +// As of yet signerInfos and digestAlgorithms are not parsed, as they are not relevant to +// this system's use of PKCS #7 data. Version is an integer type, note that PKCS #7 is +// recursive, this second layer of ContentInfo is similar ignored for our degenerate +// usage. The ExtendedCertificatesAndCertificates type consists of a sequence of choices +// between PKCS #6 extended certificates and x509 certificates. Any sequence consisting +// of any number of extended certificates is not yet supported in this implementation. +// +// The ContentType Data is simply a raw octet string and is parsed directly into a Go []byte slice. +// +// The ContentType encryptedData is the most complicated and its form can be gathered by +// the go type below. It essentially contains a raw octet string of encrypted data and an +// algorithm identifier for use in decrypting this data. +package pkcs7 + +import ( + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "errors" + + cferr "github.com/cloudflare/cfssl/errors" +) + +// Types used for asn1 Unmarshaling. + +type signedData struct { + Version int + DigestAlgorithms asn1.RawValue + ContentInfo asn1.RawValue + Certificates asn1.RawValue `asn1:"optional" asn1:"tag:0"` + Crls asn1.RawValue `asn1:"optional"` + SignerInfos asn1.RawValue +} + +type initPKCS7 struct { + Raw asn1.RawContent + ContentType asn1.ObjectIdentifier + Content asn1.RawValue `asn1:"tag:0,explicit,optional"` +} + +// Object identifier strings of the three implemented PKCS7 types. +const ( + ObjIDData = "1.2.840.113549.1.7.1" + ObjIDSignedData = "1.2.840.113549.1.7.2" + ObjIDEncryptedData = "1.2.840.113549.1.7.6" +) + +// PKCS7 represents the ASN1 PKCS #7 Content type. It contains one of three +// possible types of Content objects, as denoted by the object identifier in +// the ContentInfo field, the other two being nil. SignedData +// is the degenerate SignedData Content info without signature used +// to hold certificates and crls. Data is raw bytes, and EncryptedData +// is as defined in PKCS #7 standard. +type PKCS7 struct { + Raw asn1.RawContent + ContentInfo string + Content Content +} + +// Content implements three of the six possible PKCS7 data types. Only one is non-nil. +type Content struct { + Data []byte + SignedData SignedData + EncryptedData EncryptedData +} + +// SignedData defines the typical carrier of certificates and crls. +type SignedData struct { + Raw asn1.RawContent + Version int + Certificates []*x509.Certificate + Crl *pkix.CertificateList +} + +// Data contains raw bytes. Used as a subtype in PKCS12. +type Data struct { + Bytes []byte +} + +// EncryptedData contains encrypted data. Used as a subtype in PKCS12. +type EncryptedData struct { + Raw asn1.RawContent + Version int + EncryptedContentInfo EncryptedContentInfo +} + +// EncryptedContentInfo is a subtype of PKCS7EncryptedData. +type EncryptedContentInfo struct { + Raw asn1.RawContent + ContentType asn1.ObjectIdentifier + ContentEncryptionAlgorithm pkix.AlgorithmIdentifier + EncryptedContent []byte `asn1:"tag:0,optional"` +} + +// ParsePKCS7 attempts to parse the DER encoded bytes of a +// PKCS7 structure. +func ParsePKCS7(raw []byte) (msg *PKCS7, err error) { + + var pkcs7 initPKCS7 + _, err = asn1.Unmarshal(raw, &pkcs7) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + + msg = new(PKCS7) + msg.Raw = pkcs7.Raw + msg.ContentInfo = pkcs7.ContentType.String() + switch { + case msg.ContentInfo == ObjIDData: + msg.ContentInfo = "Data" + _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &msg.Content.Data) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + case msg.ContentInfo == ObjIDSignedData: + msg.ContentInfo = "SignedData" + var signedData signedData + _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &signedData) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + if len(signedData.Certificates.Bytes) != 0 { + msg.Content.SignedData.Certificates, err = x509.ParseCertificates(signedData.Certificates.Bytes) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + } + if len(signedData.Crls.Bytes) != 0 { + msg.Content.SignedData.Crl, err = x509.ParseDERCRL(signedData.Crls.Bytes) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + } + msg.Content.SignedData.Version = signedData.Version + msg.Content.SignedData.Raw = pkcs7.Content.Bytes + case msg.ContentInfo == ObjIDEncryptedData: + msg.ContentInfo = "EncryptedData" + var encryptedData EncryptedData + _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &encryptedData) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + if encryptedData.Version != 0 { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Only support for PKCS #7 encryptedData version 0")) + } + msg.Content.EncryptedData = encryptedData + + default: + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Attempt to parse PKCS# 7 Content not of type data, signed data or encrypted data")) + } + + return msg, nil + +} diff --git a/vendor/github.com/cloudflare/cfssl/csr/csr.go b/vendor/github.com/cloudflare/cfssl/csr/csr.go new file mode 100644 index 000000000000..6e3653fba642 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/csr/csr.go @@ -0,0 +1,414 @@ +// Package csr implements certificate requests for CFSSL. +package csr + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "net" + "net/mail" + "strings" + + cferr "github.com/cloudflare/cfssl/errors" + "github.com/cloudflare/cfssl/helpers" + "github.com/cloudflare/cfssl/log" +) + +const ( + curveP256 = 256 + curveP384 = 384 + curveP521 = 521 +) + +// A Name contains the SubjectInfo fields. +type Name struct { + C string // Country + ST string // State + L string // Locality + O string // OrganisationName + OU string // OrganisationalUnitName + SerialNumber string +} + +// A KeyRequest is a generic request for a new key. +type KeyRequest interface { + Algo() string + Size() int + Generate() (crypto.PrivateKey, error) + SigAlgo() x509.SignatureAlgorithm +} + +// A BasicKeyRequest contains the algorithm and key size for a new private key. +type BasicKeyRequest struct { + A string `json:"algo"` + S int `json:"size"` +} + +// NewBasicKeyRequest returns a default BasicKeyRequest. +func NewBasicKeyRequest() *BasicKeyRequest { + return &BasicKeyRequest{"ecdsa", curveP256} +} + +// Algo returns the requested key algorithm represented as a string. +func (kr *BasicKeyRequest) Algo() string { + return kr.A +} + +// Size returns the requested key size. +func (kr *BasicKeyRequest) Size() int { + return kr.S +} + +// Generate generates a key as specified in the request. Currently, +// only ECDSA and RSA are supported. +func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) { + log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size()) + switch kr.Algo() { + case "rsa": + if kr.Size() < 2048 { + return nil, errors.New("RSA key is too weak") + } + if kr.Size() > 8192 { + return nil, errors.New("RSA key size too large") + } + return rsa.GenerateKey(rand.Reader, kr.Size()) + case "ecdsa": + var curve elliptic.Curve + switch kr.Size() { + case curveP256: + curve = elliptic.P256() + case curveP384: + curve = elliptic.P384() + case curveP521: + curve = elliptic.P521() + default: + return nil, errors.New("invalid curve") + } + return ecdsa.GenerateKey(curve, rand.Reader) + default: + return nil, errors.New("invalid algorithm") + } +} + +// SigAlgo returns an appropriate X.509 signature algorithm given the +// key request's type and size. +func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm { + switch kr.Algo() { + case "rsa": + switch { + case kr.Size() >= 4096: + return x509.SHA512WithRSA + case kr.Size() >= 3072: + return x509.SHA384WithRSA + case kr.Size() >= 2048: + return x509.SHA256WithRSA + default: + return x509.SHA1WithRSA + } + case "ecdsa": + switch kr.Size() { + case curveP521: + return x509.ECDSAWithSHA512 + case curveP384: + return x509.ECDSAWithSHA384 + case curveP256: + return x509.ECDSAWithSHA256 + default: + return x509.ECDSAWithSHA1 + } + default: + return x509.UnknownSignatureAlgorithm + } +} + +// CAConfig is a section used in the requests initialising a new CA. +type CAConfig struct { + PathLength int `json:"pathlen"` + Expiry string `json:"expiry"` +} + +// A CertificateRequest encapsulates the API interface to the +// certificate request functionality. +type CertificateRequest struct { + CN string + Names []Name `json:"names"` + Hosts []string `json:"hosts"` + KeyRequest KeyRequest `json:"key,omitempty"` + CA *CAConfig `json:"ca,omitempty"` + SerialNumber string `json:"serialnumber,omitempty"` +} + +// New returns a new, empty CertificateRequest with a +// BasicKeyRequest. +func New() *CertificateRequest { + return &CertificateRequest{ + KeyRequest: NewBasicKeyRequest(), + } +} + +// appendIf appends to a if s is not an empty string. +func appendIf(s string, a *[]string) { + if s != "" { + *a = append(*a, s) + } +} + +// Name returns the PKIX name for the request. +func (cr *CertificateRequest) Name() pkix.Name { + var name pkix.Name + name.CommonName = cr.CN + + for _, n := range cr.Names { + appendIf(n.C, &name.Country) + appendIf(n.ST, &name.Province) + appendIf(n.L, &name.Locality) + appendIf(n.O, &name.Organization) + appendIf(n.OU, &name.OrganizationalUnit) + } + name.SerialNumber = cr.SerialNumber + return name +} + +// ParseRequest takes a certificate request and generates a key and +// CSR from it. It does no validation -- caveat emptor. It will, +// however, fail if the key request is not valid (i.e., an unsupported +// curve or RSA key size). The lack of validation was specifically +// chosen to allow the end user to define a policy and validate the +// request appropriately before calling this function. +func ParseRequest(req *CertificateRequest) (csr, key []byte, err error) { + log.Info("received CSR") + if req.KeyRequest == nil { + req.KeyRequest = NewBasicKeyRequest() + } + + log.Infof("generating key: %s-%d", req.KeyRequest.Algo(), req.KeyRequest.Size()) + priv, err := req.KeyRequest.Generate() + if err != nil { + err = cferr.Wrap(cferr.PrivateKeyError, cferr.GenerationFailed, err) + return + } + + switch priv := priv.(type) { + case *rsa.PrivateKey: + key = x509.MarshalPKCS1PrivateKey(priv) + block := pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: key, + } + key = pem.EncodeToMemory(&block) + case *ecdsa.PrivateKey: + key, err = x509.MarshalECPrivateKey(priv) + if err != nil { + err = cferr.Wrap(cferr.PrivateKeyError, cferr.Unknown, err) + return + } + block := pem.Block{ + Type: "EC PRIVATE KEY", + Bytes: key, + } + key = pem.EncodeToMemory(&block) + default: + panic("Generate should have failed to produce a valid key.") + } + + var tpl = x509.CertificateRequest{ + Subject: req.Name(), + SignatureAlgorithm: req.KeyRequest.SigAlgo(), + } + + for i := range req.Hosts { + if ip := net.ParseIP(req.Hosts[i]); ip != nil { + tpl.IPAddresses = append(tpl.IPAddresses, ip) + } else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil { + tpl.EmailAddresses = append(tpl.EmailAddresses, req.Hosts[i]) + } else { + tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i]) + } + } + + csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv) + if err != nil { + log.Errorf("failed to generate a CSR: %v", err) + err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err) + return + } + block := pem.Block{ + Type: "CERTIFICATE REQUEST", + Bytes: csr, + } + + log.Info("encoded CSR") + csr = pem.EncodeToMemory(&block) + return +} + +// ExtractCertificateRequest extracts a CertificateRequest from +// x509.Certificate. It is aimed to used for generating a new certificate +// from an existing certificate. For a root certificate, the CA expiry +// length is calculated as the duration between cert.NotAfter and cert.NotBefore. +func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest { + req := New() + req.CN = cert.Subject.CommonName + req.Names = getNames(cert.Subject) + req.Hosts = getHosts(cert) + req.SerialNumber = cert.Subject.SerialNumber + + if cert.IsCA { + req.CA = new(CAConfig) + // CA expiry length is calculated based on the input cert + // issue date and expiry date. + req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String() + req.CA.PathLength = cert.MaxPathLen + } + + return req +} + +func getHosts(cert *x509.Certificate) []string { + var hosts []string + for _, ip := range cert.IPAddresses { + hosts = append(hosts, ip.String()) + } + for _, dns := range cert.DNSNames { + hosts = append(hosts, dns) + } + for _, email := range cert.EmailAddresses { + hosts = append(hosts, email) + } + + return hosts +} + +// getNames returns an array of Names from the certificate +// It onnly cares about Country, Organization, OrganizationalUnit, Locality, Province +func getNames(sub pkix.Name) []Name { + // anonymous func for finding the max of a list of interger + max := func(v1 int, vn ...int) (max int) { + max = v1 + for i := 0; i < len(vn); i++ { + if vn[i] > max { + max = vn[i] + } + } + return max + } + + nc := len(sub.Country) + norg := len(sub.Organization) + nou := len(sub.OrganizationalUnit) + nl := len(sub.Locality) + np := len(sub.Province) + + n := max(nc, norg, nou, nl, np) + + names := make([]Name, n) + for i := range names { + if i < nc { + names[i].C = sub.Country[i] + } + if i < norg { + names[i].O = sub.Organization[i] + } + if i < nou { + names[i].OU = sub.OrganizationalUnit[i] + } + if i < nl { + names[i].L = sub.Locality[i] + } + if i < np { + names[i].ST = sub.Province[i] + } + } + return names +} + +// A Generator is responsible for validating certificate requests. +type Generator struct { + Validator func(*CertificateRequest) error +} + +// ProcessRequest validates and processes the incoming request. It is +// a wrapper around a validator and the ParseRequest function. +func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) { + + log.Info("generate received request") + err = g.Validator(req) + if err != nil { + log.Warningf("invalid request: %v", err) + return + } + + csr, key, err = ParseRequest(req) + if err != nil { + return nil, nil, err + } + return +} + +// IsNameEmpty returns true if the name has no identifying information in it. +func IsNameEmpty(n Name) bool { + empty := func(s string) bool { return strings.TrimSpace(s) == "" } + + if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) { + return true + } + return false +} + +// Regenerate uses the provided CSR as a template for signing a new +// CSR using priv. +func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) { + req, extra, err := helpers.ParseCSR(csr) + if err != nil { + return nil, err + } else if len(extra) > 0 { + return nil, errors.New("csr: trailing data in certificate request") + } + + return x509.CreateCertificateRequest(rand.Reader, req, priv) +} + +// Generate creates a new CSR from a CertificateRequest structure and +// an existing key. The KeyRequest field is ignored. +func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) { + sigAlgo := helpers.SignerAlgo(priv, crypto.SHA256) + if sigAlgo == x509.UnknownSignatureAlgorithm { + return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable) + } + + var tpl = x509.CertificateRequest{ + Subject: req.Name(), + SignatureAlgorithm: sigAlgo, + } + + for i := range req.Hosts { + if ip := net.ParseIP(req.Hosts[i]); ip != nil { + tpl.IPAddresses = append(tpl.IPAddresses, ip) + } else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil { + tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address) + } else { + tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i]) + } + } + + csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv) + if err != nil { + log.Errorf("failed to generate a CSR: %v", err) + err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err) + return + } + block := pem.Block{ + Type: "CERTIFICATE REQUEST", + Bytes: csr, + } + + log.Info("encoded CSR") + csr = pem.EncodeToMemory(&block) + return +} diff --git a/vendor/github.com/cloudflare/cfssl/errors/doc.go b/vendor/github.com/cloudflare/cfssl/errors/doc.go new file mode 100644 index 000000000000..1910e2662f93 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/errors/doc.go @@ -0,0 +1,46 @@ +/* +Package errors provides error types returned in CF SSL. + +1. Type Error is intended for errors produced by CF SSL packages. +It formats to a json object that consists of an error message and a 4-digit code for error reasoning. + +Example: {"code":1002, "message": "Failed to decode certificate"} + +The index of codes are listed below: + 1XXX: CertificateError + 1000: Unknown + 1001: ReadFailed + 1002: DecodeFailed + 1003: ParseFailed + 1100: SelfSigned + 12XX: VerifyFailed + 121X: CertificateInvalid + 1210: NotAuthorizedToSign + 1211: Expired + 1212: CANotAuthorizedForThisName + 1213: TooManyIntermediates + 1214: IncompatibleUsage + 1220: UnknownAuthority + 2XXX: PrivatekeyError + 2000: Unknown + 2001: ReadFailed + 2002: DecodeFailed + 2003: ParseFailed + 2100: Encrypted + 2200: NotRSA + 2300: KeyMismatch + 2400: GenerationFailed + 2500: Unavailable + 3XXX: IntermediatesError + 4XXX: RootError + 5XXX: PolicyError + 5100: NoKeyUsages + 5200: InvalidPolicy + 5300: InvalidRequest + 5400: UnknownProfile + 6XXX: DialError + +2. Type HttpError is intended for CF SSL API to consume. It contains a HTTP status code that will be read and returned +by the API server. +*/ +package errors diff --git a/vendor/github.com/cloudflare/cfssl/errors/error.go b/vendor/github.com/cloudflare/cfssl/errors/error.go new file mode 100644 index 000000000000..88663b2c67ef --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/errors/error.go @@ -0,0 +1,420 @@ +package errors + +import ( + "crypto/x509" + "encoding/json" + "fmt" +) + +// Error is the error type usually returned by functions in CF SSL package. +// It contains a 4-digit error code where the most significant digit +// describes the category where the error occurred and the rest 3 digits +// describe the specific error reason. +type Error struct { + ErrorCode int `json:"code"` + Message string `json:"message"` +} + +// Category is the most significant digit of the error code. +type Category int + +// Reason is the last 3 digits of the error code. +type Reason int + +const ( + // Success indicates no error occurred. + Success Category = 1000 * iota // 0XXX + + // CertificateError indicates a fault in a certificate. + CertificateError // 1XXX + + // PrivateKeyError indicates a fault in a private key. + PrivateKeyError // 2XXX + + // IntermediatesError indicates a fault in an intermediate. + IntermediatesError // 3XXX + + // RootError indicates a fault in a root. + RootError // 4XXX + + // PolicyError indicates an error arising from a malformed or + // non-existent policy, or a breach of policy. + PolicyError // 5XXX + + // DialError indicates a network fault. + DialError // 6XXX + + // APIClientError indicates a problem with the API client. + APIClientError // 7XXX + + // OCSPError indicates a problem with OCSP signing + OCSPError // 8XXX + + // CSRError indicates a problem with CSR parsing + CSRError // 9XXX + + // CTError indicates a problem with the certificate transparency process + CTError // 10XXX + + // CertStoreError indicates a problem with the certificate store + CertStoreError // 11XXX +) + +// None is a non-specified error. +const ( + None Reason = iota +) + +// Warning code for a success +const ( + BundleExpiringBit int = 1 << iota // 0x01 + BundleNotUbiquitousBit // 0x02 +) + +// Parsing errors +const ( + Unknown Reason = iota // X000 + ReadFailed // X001 + DecodeFailed // X002 + ParseFailed // X003 +) + +// The following represent certificate non-parsing errors, and must be +// specified along with CertificateError. +const ( + // SelfSigned indicates that a certificate is self-signed and + // cannot be used in the manner being attempted. + SelfSigned Reason = 100 * (iota + 1) // Code 11XX + + // VerifyFailed is an X.509 verification failure. The least two + // significant digits of 12XX is determined as the actual x509 + // error is examined. + VerifyFailed // Code 12XX + + // BadRequest indicates that the certificate request is invalid. + BadRequest // Code 13XX + + // MissingSerial indicates that the profile specified + // 'ClientProvidesSerialNumbers', but the SignRequest did not include a serial + // number. + MissingSerial // Code 14XX +) + +const ( + certificateInvalid = 10 * (iota + 1) //121X + unknownAuthority //122x +) + +// The following represent private-key non-parsing errors, and must be +// specified with PrivateKeyError. +const ( + // Encrypted indicates that the private key is a PKCS #8 encrypted + // private key. At this time, CFSSL does not support decrypting + // these keys. + Encrypted Reason = 100 * (iota + 1) //21XX + + // NotRSAOrECC indicates that they key is not an RSA or ECC + // private key; these are the only two private key types supported + // at this time by CFSSL. + NotRSAOrECC //22XX + + // KeyMismatch indicates that the private key does not match + // the public key or certificate being presented with the key. + KeyMismatch //23XX + + // GenerationFailed indicates that a private key could not + // be generated. + GenerationFailed //24XX + + // Unavailable indicates that a private key mechanism (such as + // PKCS #11) was requested but support for that mechanism is + // not available. + Unavailable +) + +// The following are policy-related non-parsing errors, and must be +// specified along with PolicyError. +const ( + // NoKeyUsages indicates that the profile does not permit any + // key usages for the certificate. + NoKeyUsages Reason = 100 * (iota + 1) // 51XX + + // InvalidPolicy indicates that policy being requested is not + // a valid policy or does not exist. + InvalidPolicy // 52XX + + // InvalidRequest indicates a certificate request violated the + // constraints of the policy being applied to the request. + InvalidRequest // 53XX + + // UnknownProfile indicates that the profile does not exist. + UnknownProfile // 54XX +) + +// The following are API client related errors, and should be +// specified with APIClientError. +const ( + // AuthenticationFailure occurs when the client is unable + // to obtain an authentication token for the request. + AuthenticationFailure Reason = 100 * (iota + 1) + + // JSONError wraps an encoding/json error. + JSONError + + // IOError wraps an io/ioutil error. + IOError + + // ClientHTTPError wraps a net/http error. + ClientHTTPError + + // ServerRequestFailed covers any other failures from the API + // client. + ServerRequestFailed +) + +// The following are OCSP related errors, and should be +// specified with OCSPError +const ( + // IssuerMismatch ocurs when the certificate in the OCSP signing + // request was not issued by the CA that this responder responds for. + IssuerMismatch Reason = 100 * (iota + 1) // 81XX + + // InvalidStatus occurs when the OCSP signing requests includes an + // invalid value for the certificate status. + InvalidStatus +) + +// Certificate transparency related errors specified with CTError +const ( + // PrecertSubmissionFailed occurs when submitting a precertificate to + // a log server fails + PrecertSubmissionFailed = 100 * (iota + 1) +) + +// Certificate persistence related errors specified with CertStoreError +const ( + // InsertionFailed occurs when a SQL insert query failes to complete. + InsertionFailed = 100 * (iota + 1) + // RecordNotFound occurs when a SQL query targeting on one unique + // record failes to update the specified row in the table. + RecordNotFound +) + +// The error interface implementation, which formats to a JSON object string. +func (e *Error) Error() string { + marshaled, err := json.Marshal(e) + if err != nil { + panic(err) + } + return string(marshaled) + +} + +// New returns an error that contains an error code and message derived from +// the given category, reason. Currently, to avoid confusion, it is not +// allowed to create an error of category Success +func New(category Category, reason Reason) *Error { + errorCode := int(category) + int(reason) + var msg string + switch category { + case OCSPError: + switch reason { + case ReadFailed: + msg = "No certificate provided" + case IssuerMismatch: + msg = "Certificate not issued by this issuer" + case InvalidStatus: + msg = "Invalid revocation status" + } + case CertificateError: + switch reason { + case Unknown: + msg = "Unknown certificate error" + case ReadFailed: + msg = "Failed to read certificate" + case DecodeFailed: + msg = "Failed to decode certificate" + case ParseFailed: + msg = "Failed to parse certificate" + case SelfSigned: + msg = "Certificate is self signed" + case VerifyFailed: + msg = "Unable to verify certificate" + case BadRequest: + msg = "Invalid certificate request" + case MissingSerial: + msg = "Missing serial number in request" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category CertificateError.", + reason)) + + } + case PrivateKeyError: + switch reason { + case Unknown: + msg = "Unknown private key error" + case ReadFailed: + msg = "Failed to read private key" + case DecodeFailed: + msg = "Failed to decode private key" + case ParseFailed: + msg = "Failed to parse private key" + case Encrypted: + msg = "Private key is encrypted." + case NotRSAOrECC: + msg = "Private key algorithm is not RSA or ECC" + case KeyMismatch: + msg = "Private key does not match public key" + case GenerationFailed: + msg = "Failed to new private key" + case Unavailable: + msg = "Private key is unavailable" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category PrivateKeyError.", + reason)) + } + case IntermediatesError: + switch reason { + case Unknown: + msg = "Unknown intermediate certificate error" + case ReadFailed: + msg = "Failed to read intermediate certificate" + case DecodeFailed: + msg = "Failed to decode intermediate certificate" + case ParseFailed: + msg = "Failed to parse intermediate certificate" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category IntermediatesError.", + reason)) + } + case RootError: + switch reason { + case Unknown: + msg = "Unknown root certificate error" + case ReadFailed: + msg = "Failed to read root certificate" + case DecodeFailed: + msg = "Failed to decode root certificate" + case ParseFailed: + msg = "Failed to parse root certificate" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category RootError.", + reason)) + } + case PolicyError: + switch reason { + case Unknown: + msg = "Unknown policy error" + case NoKeyUsages: + msg = "Invalid policy: no key usage available" + case InvalidPolicy: + msg = "Invalid or unknown policy" + case InvalidRequest: + msg = "Policy violation request" + case UnknownProfile: + msg = "Unknown policy profile" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category PolicyError.", + reason)) + } + case DialError: + switch reason { + case Unknown: + msg = "Failed to dial remote server" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category DialError.", + reason)) + } + case APIClientError: + switch reason { + case AuthenticationFailure: + msg = "API client authentication failure" + case JSONError: + msg = "API client JSON config error" + case ClientHTTPError: + msg = "API client HTTP error" + case IOError: + msg = "API client IO error" + case ServerRequestFailed: + msg = "API client error: Server request failed" + default: + panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category APIClientError.", + reason)) + } + case CSRError: + switch reason { + case Unknown: + msg = "CSR parsing failed due to unknown error" + case ReadFailed: + msg = "CSR file read failed" + case ParseFailed: + msg = "CSR Parsing failed" + case DecodeFailed: + msg = "CSR Decode failed" + case BadRequest: + msg = "CSR Bad request" + default: + panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category APIClientError.", reason)) + } + case CTError: + switch reason { + case Unknown: + msg = "Certificate transparency parsing failed due to unknown error" + case PrecertSubmissionFailed: + msg = "Certificate transparency precertificate submission failed" + default: + panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category CTError.", reason)) + } + case CertStoreError: + switch reason { + case Unknown: + msg = "Certificate store action failed due to unknown error" + default: + panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category CertStoreError.", reason)) + } + + default: + panic(fmt.Sprintf("Unsupported CFSSL error type: %d.", + category)) + } + return &Error{ErrorCode: errorCode, Message: msg} +} + +// Wrap returns an error that contains the given error and an error code derived from +// the given category, reason and the error. Currently, to avoid confusion, it is not +// allowed to create an error of category Success +func Wrap(category Category, reason Reason, err error) *Error { + errorCode := int(category) + int(reason) + if err == nil { + panic("Wrap needs a supplied error to initialize.") + } + + // do not double wrap a error + switch err.(type) { + case *Error: + panic("Unable to wrap a wrapped error.") + } + + switch category { + case CertificateError: + // given VerifyFailed , report the status with more detailed status code + // for some certificate errors we care. + if reason == VerifyFailed { + switch errorType := err.(type) { + case x509.CertificateInvalidError: + errorCode += certificateInvalid + int(errorType.Reason) + case x509.UnknownAuthorityError: + errorCode += unknownAuthority + } + } + case PrivateKeyError, IntermediatesError, RootError, PolicyError, DialError, + APIClientError, CSRError, CTError, CertStoreError: + // no-op, just use the error + default: + panic(fmt.Sprintf("Unsupported CFSSL error type: %d.", + category)) + } + + return &Error{ErrorCode: errorCode, Message: err.Error()} + +} diff --git a/vendor/github.com/cloudflare/cfssl/errors/http.go b/vendor/github.com/cloudflare/cfssl/errors/http.go new file mode 100644 index 000000000000..c9c0a39c7031 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/errors/http.go @@ -0,0 +1,47 @@ +package errors + +import ( + "errors" + "net/http" +) + +// HTTPError is an augmented error with a HTTP status code. +type HTTPError struct { + StatusCode int + error +} + +// Error implements the error interface. +func (e *HTTPError) Error() string { + return e.error.Error() +} + +// NewMethodNotAllowed returns an appropriate error in the case that +// an HTTP client uses an invalid method (i.e. a GET in place of a POST) +// on an API endpoint. +func NewMethodNotAllowed(method string) *HTTPError { + return &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:"` + method + `"`)} +} + +// NewBadRequest creates a HttpError with the given error and error code 400. +func NewBadRequest(err error) *HTTPError { + return &HTTPError{http.StatusBadRequest, err} +} + +// NewBadRequestString returns a HttpError with the supplied message +// and error code 400. +func NewBadRequestString(s string) *HTTPError { + return NewBadRequest(errors.New(s)) +} + +// NewBadRequestMissingParameter returns a 400 HttpError as a required +// parameter is missing in the HTTP request. +func NewBadRequestMissingParameter(s string) *HTTPError { + return NewBadRequestString(`Missing parameter "` + s + `"`) +} + +// NewBadRequestUnwantedParameter returns a 400 HttpError as a unnecessary +// parameter is present in the HTTP request. +func NewBadRequestUnwantedParameter(s string) *HTTPError { + return NewBadRequestString(`Unwanted parameter "` + s + `"`) +} diff --git a/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go b/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go new file mode 100644 index 000000000000..bcc74185085b --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go @@ -0,0 +1,42 @@ +// Package derhelpers implements common functionality +// on DER encoded data +package derhelpers + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rsa" + "crypto/x509" + + cferr "github.com/cloudflare/cfssl/errors" +) + +// ParsePrivateKeyDER parses a PKCS #1, PKCS #8, or elliptic curve +// DER-encoded private key. The key must not be in PEM format. +func ParsePrivateKeyDER(keyDER []byte) (key crypto.Signer, err error) { + generalKey, err := x509.ParsePKCS8PrivateKey(keyDER) + if err != nil { + generalKey, err = x509.ParsePKCS1PrivateKey(keyDER) + if err != nil { + generalKey, err = x509.ParseECPrivateKey(keyDER) + if err != nil { + // We don't include the actual error into + // the final error. The reason might be + // we don't want to leak any info about + // the private key. + return nil, cferr.New(cferr.PrivateKeyError, + cferr.ParseFailed) + } + } + } + + switch generalKey.(type) { + case *rsa.PrivateKey: + return generalKey.(*rsa.PrivateKey), nil + case *ecdsa.PrivateKey: + return generalKey.(*ecdsa.PrivateKey), nil + } + + // should never reach here + return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed) +} diff --git a/vendor/github.com/cloudflare/cfssl/helpers/helpers.go b/vendor/github.com/cloudflare/cfssl/helpers/helpers.go new file mode 100644 index 000000000000..74d768134ac5 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/helpers/helpers.go @@ -0,0 +1,478 @@ +// Package helpers implements utility functionality common to many +// CFSSL packages. +package helpers + +import ( + "bytes" + "crypto" + "crypto/ecdsa" + "crypto/rsa" + "crypto/x509" + "encoding/asn1" + "encoding/pem" + "errors" + "io/ioutil" + "math/big" + + "strings" + "time" + + "github.com/cloudflare/cfssl/crypto/pkcs7" + cferr "github.com/cloudflare/cfssl/errors" + "github.com/cloudflare/cfssl/helpers/derhelpers" + "github.com/cloudflare/cfssl/log" + "golang.org/x/crypto/pkcs12" +) + +// OneYear is a time.Duration representing a year's worth of seconds. +const OneYear = 8760 * time.Hour + +// OneDay is a time.Duration representing a day's worth of seconds. +const OneDay = 24 * time.Hour + +// InclusiveDate returns the time.Time representation of a date - 1 +// nanosecond. This allows time.After to be used inclusively. +func InclusiveDate(year int, month time.Month, day int) time.Time { + return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond) +} + +// Jul2012 is the July 2012 CAB Forum deadline for when CAs must stop +// issuing certificates valid for more than 5 years. +var Jul2012 = InclusiveDate(2012, time.July, 01) + +// Apr2015 is the April 2015 CAB Forum deadline for when CAs must stop +// issuing certificates valid for more than 39 months. +var Apr2015 = InclusiveDate(2015, time.April, 01) + +// KeyLength returns the bit size of ECDSA or RSA PublicKey +func KeyLength(key interface{}) int { + if key == nil { + return 0 + } + if ecdsaKey, ok := key.(*ecdsa.PublicKey); ok { + return ecdsaKey.Curve.Params().BitSize + } else if rsaKey, ok := key.(*rsa.PublicKey); ok { + return rsaKey.N.BitLen() + } + + return 0 +} + +// ExpiryTime returns the time when the certificate chain is expired. +func ExpiryTime(chain []*x509.Certificate) (notAfter time.Time) { + if len(chain) == 0 { + return + } + + notAfter = chain[0].NotAfter + for _, cert := range chain { + if notAfter.After(cert.NotAfter) { + notAfter = cert.NotAfter + } + } + return +} + +// MonthsValid returns the number of months for which a certificate is valid. +func MonthsValid(c *x509.Certificate) int { + issued := c.NotBefore + expiry := c.NotAfter + years := (expiry.Year() - issued.Year()) + months := years*12 + int(expiry.Month()) - int(issued.Month()) + + // Round up if valid for less than a full month + if expiry.Day() > issued.Day() { + months++ + } + return months +} + +// ValidExpiry determines if a certificate is valid for an acceptable +// length of time per the CA/Browser Forum baseline requirements. +// See https://cabforum.org/wp-content/uploads/CAB-Forum-BR-1.3.0.pdf +func ValidExpiry(c *x509.Certificate) bool { + issued := c.NotBefore + + var maxMonths int + switch { + case issued.After(Apr2015): + maxMonths = 39 + case issued.After(Jul2012): + maxMonths = 60 + case issued.Before(Jul2012): + maxMonths = 120 + } + + if MonthsValid(c) > maxMonths { + return false + } + return true +} + +// SignatureString returns the TLS signature string corresponding to +// an X509 signature algorithm. +func SignatureString(alg x509.SignatureAlgorithm) string { + switch alg { + case x509.MD2WithRSA: + return "MD2WithRSA" + case x509.MD5WithRSA: + return "MD5WithRSA" + case x509.SHA1WithRSA: + return "SHA1WithRSA" + case x509.SHA256WithRSA: + return "SHA256WithRSA" + case x509.SHA384WithRSA: + return "SHA384WithRSA" + case x509.SHA512WithRSA: + return "SHA512WithRSA" + case x509.DSAWithSHA1: + return "DSAWithSHA1" + case x509.DSAWithSHA256: + return "DSAWithSHA256" + case x509.ECDSAWithSHA1: + return "ECDSAWithSHA1" + case x509.ECDSAWithSHA256: + return "ECDSAWithSHA256" + case x509.ECDSAWithSHA384: + return "ECDSAWithSHA384" + case x509.ECDSAWithSHA512: + return "ECDSAWithSHA512" + default: + return "Unknown Signature" + } +} + +// HashAlgoString returns the hash algorithm name contains in the signature +// method. +func HashAlgoString(alg x509.SignatureAlgorithm) string { + switch alg { + case x509.MD2WithRSA: + return "MD2" + case x509.MD5WithRSA: + return "MD5" + case x509.SHA1WithRSA: + return "SHA1" + case x509.SHA256WithRSA: + return "SHA256" + case x509.SHA384WithRSA: + return "SHA384" + case x509.SHA512WithRSA: + return "SHA512" + case x509.DSAWithSHA1: + return "SHA1" + case x509.DSAWithSHA256: + return "SHA256" + case x509.ECDSAWithSHA1: + return "SHA1" + case x509.ECDSAWithSHA256: + return "SHA256" + case x509.ECDSAWithSHA384: + return "SHA384" + case x509.ECDSAWithSHA512: + return "SHA512" + default: + return "Unknown Hash Algorithm" + } +} + +// EncodeCertificatesPEM encodes a number of x509 certficates to PEM +func EncodeCertificatesPEM(certs []*x509.Certificate) []byte { + var buffer bytes.Buffer + for _, cert := range certs { + pem.Encode(&buffer, &pem.Block{ + Type: "CERTIFICATE", + Bytes: cert.Raw, + }) + } + + return buffer.Bytes() +} + +// EncodeCertificatePEM encodes a single x509 certficates to PEM +func EncodeCertificatePEM(cert *x509.Certificate) []byte { + return EncodeCertificatesPEM([]*x509.Certificate{cert}) +} + +// ParseCertificatesPEM parses a sequence of PEM-encoded certificate and returns them, +// can handle PEM encoded PKCS #7 structures. +func ParseCertificatesPEM(certsPEM []byte) ([]*x509.Certificate, error) { + var certs []*x509.Certificate + var err error + certsPEM = bytes.TrimSpace(certsPEM) + for len(certsPEM) > 0 { + var cert []*x509.Certificate + cert, certsPEM, err = ParseOneCertificateFromPEM(certsPEM) + if err != nil { + + return nil, cferr.New(cferr.CertificateError, cferr.ParseFailed) + } else if cert == nil { + break + } + + certs = append(certs, cert...) + } + if len(certsPEM) > 0 { + return nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed) + } + return certs, nil +} + +// ParseCertificatesDER parses a DER encoding of a certificate object and possibly private key, +// either PKCS #7, PKCS #12, or raw x509. +func ParseCertificatesDER(certsDER []byte, password string) (certs []*x509.Certificate, key crypto.Signer, err error) { + certsDER = bytes.TrimSpace(certsDER) + pkcs7data, err := pkcs7.ParsePKCS7(certsDER) + if err != nil { + var pkcs12data interface{} + certs = make([]*x509.Certificate, 1) + pkcs12data, certs[0], err = pkcs12.Decode(certsDER, password) + if err != nil { + certs, err = x509.ParseCertificates(certsDER) + if err != nil { + return nil, nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed) + } + } else { + key = pkcs12data.(crypto.Signer) + } + } else { + if pkcs7data.ContentInfo != "SignedData" { + return nil, nil, cferr.Wrap(cferr.CertificateError, cferr.DecodeFailed, errors.New("can only extract certificates from signed data content info")) + } + certs = pkcs7data.Content.SignedData.Certificates + } + if certs == nil { + return nil, key, cferr.New(cferr.CertificateError, cferr.DecodeFailed) + } + return certs, key, nil +} + +// ParseSelfSignedCertificatePEM parses a PEM-encoded certificate and check if it is self-signed. +func ParseSelfSignedCertificatePEM(certPEM []byte) (*x509.Certificate, error) { + cert, err := ParseCertificatePEM(certPEM) + if err != nil { + return nil, err + } + + if err := cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature); err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.VerifyFailed, err) + } + return cert, nil +} + +// ParseCertificatePEM parses and returns a PEM-encoded certificate, +// can handle PEM encoded PKCS #7 structures. +func ParseCertificatePEM(certPEM []byte) (*x509.Certificate, error) { + certPEM = bytes.TrimSpace(certPEM) + cert, rest, err := ParseOneCertificateFromPEM(certPEM) + if err != nil { + // Log the actual parsing error but throw a default parse error message. + log.Debugf("Certificate parsing error: %v", err) + return nil, cferr.New(cferr.CertificateError, cferr.ParseFailed) + } else if cert == nil { + return nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed) + } else if len(rest) > 0 { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PEM file should contain only one object")) + } else if len(cert) > 1 { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PKCS7 object in the PEM file should contain only one certificate")) + } + return cert[0], nil +} + +// ParseOneCertificateFromPEM attempts to parse one PEM encoded certificate object, +// either a raw x509 certificate or a PKCS #7 structure possibly containing +// multiple certificates, from the top of certsPEM, which itself may +// contain multiple PEM encoded certificate objects. +func ParseOneCertificateFromPEM(certsPEM []byte) ([]*x509.Certificate, []byte, error) { + + block, rest := pem.Decode(certsPEM) + if block == nil { + return nil, rest, nil + } + + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + pkcs7data, err := pkcs7.ParsePKCS7(block.Bytes) + if err != nil { + return nil, rest, err + } + if pkcs7data.ContentInfo != "SignedData" { + return nil, rest, errors.New("only PKCS #7 Signed Data Content Info supported for certificate parsing") + } + certs := pkcs7data.Content.SignedData.Certificates + if certs == nil { + return nil, rest, errors.New("PKCS #7 structure contains no certificates") + } + return certs, rest, nil + } + var certs = []*x509.Certificate{cert} + return certs, rest, nil +} + +// LoadPEMCertPool loads a pool of PEM certificates from file. +func LoadPEMCertPool(certsFile string) (*x509.CertPool, error) { + pemCerts, err := ioutil.ReadFile(certsFile) + if err != nil { + return nil, err + } + + certPool := x509.NewCertPool() + if !certPool.AppendCertsFromPEM(pemCerts) { + return nil, errors.New("failed to load cert pool") + } + + return certPool, nil +} + +// ParsePrivateKeyPEM parses and returns a PEM-encoded private +// key. The private key may be either an unencrypted PKCS#8, PKCS#1, +// or elliptic private key. +func ParsePrivateKeyPEM(keyPEM []byte) (key crypto.Signer, err error) { + return ParsePrivateKeyPEMWithPassword(keyPEM, nil) +} + +// ParsePrivateKeyPEMWithPassword parses and returns a PEM-encoded private +// key. The private key may be a potentially encrypted PKCS#8, PKCS#1, +// or elliptic private key. +func ParsePrivateKeyPEMWithPassword(keyPEM []byte, password []byte) (key crypto.Signer, err error) { + keyDER, err := GetKeyDERFromPEM(keyPEM, password) + if err != nil { + return nil, err + } + + return derhelpers.ParsePrivateKeyDER(keyDER) +} + +// GetKeyDERFromPEM parses a PEM-encoded private key and returns DER-format key bytes. +func GetKeyDERFromPEM(in []byte, password []byte) ([]byte, error) { + keyDER, _ := pem.Decode(in) + if keyDER != nil { + if procType, ok := keyDER.Headers["Proc-Type"]; ok { + if strings.Contains(procType, "ENCRYPTED") { + if password != nil { + return x509.DecryptPEMBlock(keyDER, password) + } + return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted) + } + } + return keyDER.Bytes, nil + } + + return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed) +} + +// CheckSignature verifies a signature made by the key on a CSR, such +// as on the CSR itself. +func CheckSignature(csr *x509.CertificateRequest, algo x509.SignatureAlgorithm, signed, signature []byte) error { + var hashType crypto.Hash + + switch algo { + case x509.SHA1WithRSA, x509.ECDSAWithSHA1: + hashType = crypto.SHA1 + case x509.SHA256WithRSA, x509.ECDSAWithSHA256: + hashType = crypto.SHA256 + case x509.SHA384WithRSA, x509.ECDSAWithSHA384: + hashType = crypto.SHA384 + case x509.SHA512WithRSA, x509.ECDSAWithSHA512: + hashType = crypto.SHA512 + default: + return x509.ErrUnsupportedAlgorithm + } + + if !hashType.Available() { + return x509.ErrUnsupportedAlgorithm + } + h := hashType.New() + + h.Write(signed) + digest := h.Sum(nil) + + switch pub := csr.PublicKey.(type) { + case *rsa.PublicKey: + return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) + case *ecdsa.PublicKey: + ecdsaSig := new(struct{ R, S *big.Int }) + if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { + return err + } + if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { + return errors.New("x509: ECDSA signature contained zero or negative values") + } + if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { + return errors.New("x509: ECDSA verification failure") + } + return nil + } + return x509.ErrUnsupportedAlgorithm +} + +// ParseCSR parses a PEM- or DER-encoded PKCS #10 certificate signing request. +func ParseCSR(in []byte) (csr *x509.CertificateRequest, rest []byte, err error) { + in = bytes.TrimSpace(in) + p, rest := pem.Decode(in) + if p != nil { + if p.Type != "CERTIFICATE REQUEST" { + return nil, rest, cferr.New(cferr.CSRError, cferr.BadRequest) + } + + csr, err = x509.ParseCertificateRequest(p.Bytes) + } else { + csr, err = x509.ParseCertificateRequest(in) + } + + if err != nil { + return nil, rest, err + } + + err = CheckSignature(csr, csr.SignatureAlgorithm, csr.RawTBSCertificateRequest, csr.Signature) + if err != nil { + return nil, rest, err + } + + return csr, rest, nil +} + +// ParseCSRPEM parses a PEM-encoded certificiate signing request. +// It does not check the signature. This is useful for dumping data from a CSR +// locally. +func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) { + block, _ := pem.Decode([]byte(csrPEM)) + der := block.Bytes + csrObject, err := x509.ParseCertificateRequest(der) + + if err != nil { + return nil, err + } + + return csrObject, nil +} + +// SignerAlgo returns an X.509 signature algorithm corresponding to +// the crypto.Hash provided from a crypto.Signer. +func SignerAlgo(priv crypto.Signer, h crypto.Hash) x509.SignatureAlgorithm { + switch priv.Public().(type) { + case *rsa.PublicKey: + switch h { + case crypto.SHA512: + return x509.SHA512WithRSA + case crypto.SHA384: + return x509.SHA384WithRSA + case crypto.SHA256: + return x509.SHA256WithRSA + default: + return x509.SHA1WithRSA + } + case *ecdsa.PublicKey: + switch h { + case crypto.SHA512: + return x509.ECDSAWithSHA512 + case crypto.SHA384: + return x509.ECDSAWithSHA384 + case crypto.SHA256: + return x509.ECDSAWithSHA256 + default: + return x509.ECDSAWithSHA1 + } + default: + return x509.UnknownSignatureAlgorithm + } +} diff --git a/vendor/github.com/cloudflare/cfssl/info/info.go b/vendor/github.com/cloudflare/cfssl/info/info.go new file mode 100644 index 000000000000..926a411ffbbb --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/info/info.go @@ -0,0 +1,15 @@ +// Package info contains the definitions for the info endpoint +package info + +// Req is the request struct for an info API request. +type Req struct { + Label string `json:"label"` + Profile string `json:"profile"` +} + +// Resp is the response for an Info API request. +type Resp struct { + Certificate string `json:"certificate"` + Usage []string `json:"usages"` + ExpiryString string `json:"expiry"` +} diff --git a/vendor/github.com/cloudflare/cfssl/log/log.go b/vendor/github.com/cloudflare/cfssl/log/log.go new file mode 100644 index 000000000000..b517c44eea47 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/log/log.go @@ -0,0 +1,174 @@ +// Package log implements a wrapper around the Go standard library's +// logging package. Clients should set the current log level; only +// messages below that level will actually be logged. For example, if +// Level is set to LevelWarning, only log messages at the Warning, +// Error, and Critical levels will be logged. +package log + +import ( + "flag" + "fmt" + "log" + "os" +) + +// The following constants represent logging levels in increasing levels of seriousness. +const ( + // LevelDebug is the log level for Debug statements. + LevelDebug = iota + // LevelInfo is the log level for Info statements. + LevelInfo + // LevelWarning is the log level for Warning statements. + LevelWarning + // LevelError is the log level for Error statements. + LevelError + // LevelCritical is the log level for Critical statements. + LevelCritical + // LevelFatal is the log level for Fatal statements. + LevelFatal +) + +var levelPrefix = [...]string{ + LevelDebug: "DEBUG", + LevelInfo: "INFO", + LevelWarning: "WARNING", + LevelError: "ERROR", + LevelCritical: "CRITICAL", + LevelFatal: "FATAL", +} + +// Level stores the current logging level. +var Level = LevelInfo + +// SyslogWriter specifies the necessary methods for an alternate output +// destination passed in via SetLogger. +// +// SyslogWriter is satisfied by *syslog.Writer. +type SyslogWriter interface { + Debug(string) error + Info(string) error + Warning(string) error + Err(string) error + Crit(string) error + Emerg(string) error +} + +// syslogWriter stores the SetLogger() parameter. +var syslogWriter SyslogWriter + +// SetLogger sets the output used for output by this package. +// A *syslog.Writer is a good choice for the logger parameter. +// Call with a nil parameter to revert to default behavior. +func SetLogger(logger SyslogWriter) { + syslogWriter = logger +} + +func init() { + // Only define loglevel flag once. + if flag.Lookup("loglevel") == nil { + flag.IntVar(&Level, "loglevel", LevelInfo, "Log level (0 = DEBUG, 5 = FATAL)") + } +} + +func print(l int, msg string) { + if l >= Level { + if syslogWriter != nil { + var err error + switch l { + case LevelDebug: + err = syslogWriter.Debug(msg) + case LevelInfo: + err = syslogWriter.Info(msg) + case LevelWarning: + err = syslogWriter.Warning(msg) + case LevelError: + err = syslogWriter.Err(msg) + case LevelCritical: + err = syslogWriter.Crit(msg) + case LevelFatal: + err = syslogWriter.Emerg(msg) + } + if err != nil { + log.Printf("Unable to write syslog: %v for msg: %s\n", err, msg) + } + } else { + log.Printf("[%s] %s", levelPrefix[l], msg) + } + } +} + +func outputf(l int, format string, v []interface{}) { + print(l, fmt.Sprintf(format, v...)) +} + +func output(l int, v []interface{}) { + print(l, fmt.Sprint(v...)) +} + +// Fatalf logs a formatted message at the "fatal" level and then exits. The +// arguments are handled in the same manner as fmt.Printf. +func Fatalf(format string, v ...interface{}) { + outputf(LevelFatal, format, v) + os.Exit(1) +} + +// Fatal logs its arguments at the "fatal" level and then exits. +func Fatal(v ...interface{}) { + output(LevelFatal, v) + os.Exit(1) +} + +// Criticalf logs a formatted message at the "critical" level. The +// arguments are handled in the same manner as fmt.Printf. +func Criticalf(format string, v ...interface{}) { + outputf(LevelCritical, format, v) +} + +// Critical logs its arguments at the "critical" level. +func Critical(v ...interface{}) { + output(LevelCritical, v) +} + +// Errorf logs a formatted message at the "error" level. The arguments +// are handled in the same manner as fmt.Printf. +func Errorf(format string, v ...interface{}) { + outputf(LevelError, format, v) +} + +// Error logs its arguments at the "error" level. +func Error(v ...interface{}) { + output(LevelError, v) +} + +// Warningf logs a formatted message at the "warning" level. The +// arguments are handled in the same manner as fmt.Printf. +func Warningf(format string, v ...interface{}) { + outputf(LevelWarning, format, v) +} + +// Warning logs its arguments at the "warning" level. +func Warning(v ...interface{}) { + output(LevelWarning, v) +} + +// Infof logs a formatted message at the "info" level. The arguments +// are handled in the same manner as fmt.Printf. +func Infof(format string, v ...interface{}) { + outputf(LevelInfo, format, v) +} + +// Info logs its arguments at the "info" level. +func Info(v ...interface{}) { + output(LevelInfo, v) +} + +// Debugf logs a formatted message at the "debug" level. The arguments +// are handled in the same manner as fmt.Printf. +func Debugf(format string, v ...interface{}) { + outputf(LevelDebug, format, v) +} + +// Debug logs its arguments at the "debug" level. +func Debug(v ...interface{}) { + output(LevelDebug, v) +} diff --git a/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go b/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go new file mode 100644 index 000000000000..a19b113d4e53 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go @@ -0,0 +1,13 @@ +// Package config in the ocsp directory provides configuration data for an OCSP +// signer. +package config + +import "time" + +// Config contains configuration information required to set up an OCSP signer. +type Config struct { + CACertFile string + ResponderCertFile string + KeyFile string + Interval time.Duration +} diff --git a/vendor/github.com/cloudflare/cfssl/signer/local/local.go b/vendor/github.com/cloudflare/cfssl/signer/local/local.go new file mode 100644 index 000000000000..ac16ae4a9e61 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/signer/local/local.go @@ -0,0 +1,447 @@ +// Package local implements certificate signature functionality for CFSSL. +package local + +import ( + "bytes" + "crypto" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/binary" + "encoding/hex" + "encoding/pem" + "errors" + "io" + "io/ioutil" + "math/big" + "net" + "net/mail" + "os" + + "github.com/cloudflare/cfssl/certdb" + "github.com/cloudflare/cfssl/config" + cferr "github.com/cloudflare/cfssl/errors" + "github.com/cloudflare/cfssl/helpers" + "github.com/cloudflare/cfssl/info" + "github.com/cloudflare/cfssl/log" + "github.com/cloudflare/cfssl/signer" + "github.com/google/certificate-transparency/go" + "github.com/google/certificate-transparency/go/client" +) + +// Signer contains a signer that uses the standard library to +// support both ECDSA and RSA CA keys. +type Signer struct { + ca *x509.Certificate + priv crypto.Signer + policy *config.Signing + sigAlgo x509.SignatureAlgorithm + dbAccessor certdb.Accessor +} + +// NewSigner creates a new Signer directly from a +// private key and certificate, with optional policy. +func NewSigner(priv crypto.Signer, cert *x509.Certificate, sigAlgo x509.SignatureAlgorithm, policy *config.Signing) (*Signer, error) { + if policy == nil { + policy = &config.Signing{ + Profiles: map[string]*config.SigningProfile{}, + Default: config.DefaultConfig()} + } + + if !policy.Valid() { + return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy) + } + + return &Signer{ + ca: cert, + priv: priv, + sigAlgo: sigAlgo, + policy: policy, + }, nil +} + +// NewSignerFromFile generates a new local signer from a caFile +// and a caKey file, both PEM encoded. +func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) { + log.Debug("Loading CA: ", caFile) + ca, err := ioutil.ReadFile(caFile) + if err != nil { + return nil, err + } + log.Debug("Loading CA key: ", caKeyFile) + cakey, err := ioutil.ReadFile(caKeyFile) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err) + } + + parsedCa, err := helpers.ParseCertificatePEM(ca) + if err != nil { + return nil, err + } + + strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD") + password := []byte(strPassword) + if strPassword == "" { + password = nil + } + + priv, err := helpers.ParsePrivateKeyPEMWithPassword(cakey, password) + if err != nil { + log.Debug("Malformed private key %v", err) + return nil, err + } + + return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy) +} + +func (s *Signer) sign(template *x509.Certificate, profile *config.SigningProfile) (cert []byte, err error) { + err = signer.FillTemplate(template, s.policy.Default, profile) + if err != nil { + return + } + + var initRoot bool + if s.ca == nil { + if !template.IsCA { + err = cferr.New(cferr.PolicyError, cferr.InvalidRequest) + return + } + template.DNSNames = nil + template.EmailAddresses = nil + s.ca = template + initRoot = true + template.MaxPathLen = signer.MaxPathLen + } else if template.IsCA { + template.MaxPathLen = 1 + template.DNSNames = nil + template.EmailAddresses = nil + } + + derBytes, err := x509.CreateCertificate(rand.Reader, template, s.ca, template.PublicKey, s.priv) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err) + } + if initRoot { + s.ca, err = x509.ParseCertificate(derBytes) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err) + } + } + + cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) + log.Infof("signed certificate with serial number %d", template.SerialNumber) + return +} + +// replaceSliceIfEmpty replaces the contents of replaced with newContents if +// the slice referenced by replaced is empty +func replaceSliceIfEmpty(replaced, newContents *[]string) { + if len(*replaced) == 0 { + *replaced = *newContents + } +} + +// PopulateSubjectFromCSR has functionality similar to Name, except +// it fills the fields of the resulting pkix.Name with req's if the +// subject's corresponding fields are empty +func PopulateSubjectFromCSR(s *signer.Subject, req pkix.Name) pkix.Name { + // if no subject, use req + if s == nil { + return req + } + + name := s.Name() + + if name.CommonName == "" { + name.CommonName = req.CommonName + } + + replaceSliceIfEmpty(&name.Country, &req.Country) + replaceSliceIfEmpty(&name.Province, &req.Province) + replaceSliceIfEmpty(&name.Locality, &req.Locality) + replaceSliceIfEmpty(&name.Organization, &req.Organization) + replaceSliceIfEmpty(&name.OrganizationalUnit, &req.OrganizationalUnit) + if name.SerialNumber == "" { + name.SerialNumber = req.SerialNumber + } + return name +} + +// OverrideHosts fills template's IPAddresses, EmailAddresses, and DNSNames with the +// content of hosts, if it is not nil. +func OverrideHosts(template *x509.Certificate, hosts []string) { + if hosts != nil { + template.IPAddresses = []net.IP{} + template.EmailAddresses = []string{} + template.DNSNames = []string{} + } + + for i := range hosts { + if ip := net.ParseIP(hosts[i]); ip != nil { + template.IPAddresses = append(template.IPAddresses, ip) + } else if email, err := mail.ParseAddress(hosts[i]); err == nil && email != nil { + template.EmailAddresses = append(template.EmailAddresses, email.Address) + } else { + template.DNSNames = append(template.DNSNames, hosts[i]) + } + } + +} + +// Sign signs a new certificate based on the PEM-encoded client +// certificate or certificate request with the signing profile, +// specified by profileName. +func (s *Signer) Sign(req signer.SignRequest) (cert []byte, err error) { + profile, err := signer.Profile(s, req.Profile) + if err != nil { + return + } + + block, _ := pem.Decode([]byte(req.Request)) + if block == nil { + return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed) + } + + if block.Type != "CERTIFICATE REQUEST" { + return nil, cferr.Wrap(cferr.CSRError, + cferr.BadRequest, errors.New("not a certificate or csr")) + } + + csrTemplate, err := signer.ParseCertificateRequest(s, block.Bytes) + if err != nil { + return nil, err + } + + // Copy out only the fields from the CSR authorized by policy. + safeTemplate := x509.Certificate{} + // If the profile contains no explicit whitelist, assume that all fields + // should be copied from the CSR. + if profile.CSRWhitelist == nil { + safeTemplate = *csrTemplate + } else { + if profile.CSRWhitelist.Subject { + safeTemplate.Subject = csrTemplate.Subject + } + if profile.CSRWhitelist.PublicKeyAlgorithm { + safeTemplate.PublicKeyAlgorithm = csrTemplate.PublicKeyAlgorithm + } + if profile.CSRWhitelist.PublicKey { + safeTemplate.PublicKey = csrTemplate.PublicKey + } + if profile.CSRWhitelist.SignatureAlgorithm { + safeTemplate.SignatureAlgorithm = csrTemplate.SignatureAlgorithm + } + if profile.CSRWhitelist.DNSNames { + safeTemplate.DNSNames = csrTemplate.DNSNames + } + if profile.CSRWhitelist.IPAddresses { + safeTemplate.IPAddresses = csrTemplate.IPAddresses + } + if profile.CSRWhitelist.EmailAddresses { + safeTemplate.EmailAddresses = csrTemplate.EmailAddresses + } + } + + OverrideHosts(&safeTemplate, req.Hosts) + safeTemplate.Subject = PopulateSubjectFromCSR(req.Subject, safeTemplate.Subject) + + // If there is a whitelist, ensure that both the Common Name and SAN DNSNames match + if profile.NameWhitelist != nil { + if safeTemplate.Subject.CommonName != "" { + if profile.NameWhitelist.Find([]byte(safeTemplate.Subject.CommonName)) == nil { + return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy) + } + } + for _, name := range safeTemplate.DNSNames { + if profile.NameWhitelist.Find([]byte(name)) == nil { + return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy) + } + } + for _, name := range safeTemplate.EmailAddresses { + if profile.NameWhitelist.Find([]byte(name)) == nil { + return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy) + } + } + } + + if profile.ClientProvidesSerialNumbers { + if req.Serial == nil { + return nil, cferr.New(cferr.CertificateError, cferr.MissingSerial) + } + safeTemplate.SerialNumber = req.Serial + } else { + // RFC 5280 4.1.2.2: + // Certificate users MUST be able to handle serialNumber + // values up to 20 octets. Conforming CAs MUST NOT use + // serialNumber values longer than 20 octets. + // + // If CFSSL is providing the serial numbers, it makes + // sense to use the max supported size. + serialNumber := make([]byte, 20) + _, err = io.ReadFull(rand.Reader, serialNumber) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err) + } + + // SetBytes interprets buf as the bytes of a big-endian + // unsigned integer. The leading byte should be masked + // off to ensure it isn't negative. + serialNumber[0] &= 0x7F + + safeTemplate.SerialNumber = new(big.Int).SetBytes(serialNumber) + } + + if len(req.Extensions) > 0 { + for _, ext := range req.Extensions { + oid := asn1.ObjectIdentifier(ext.ID) + if !profile.ExtensionWhitelist[oid.String()] { + return nil, cferr.New(cferr.CertificateError, cferr.InvalidRequest) + } + + rawValue, err := hex.DecodeString(ext.Value) + if err != nil { + return nil, cferr.Wrap(cferr.CertificateError, cferr.InvalidRequest, err) + } + + safeTemplate.ExtraExtensions = append(safeTemplate.ExtraExtensions, pkix.Extension{ + Id: oid, + Critical: ext.Critical, + Value: rawValue, + }) + } + } + + var certTBS = safeTemplate + + if len(profile.CTLogServers) > 0 { + // Add a poison extension which prevents validation + var poisonExtension = pkix.Extension{Id: signer.CTPoisonOID, Critical: true, Value: []byte{0x05, 0x00}} + var poisonedPreCert = certTBS + poisonedPreCert.ExtraExtensions = append(safeTemplate.ExtraExtensions, poisonExtension) + cert, err = s.sign(&poisonedPreCert, profile) + if err != nil { + return + } + + derCert, _ := pem.Decode(cert) + prechain := []ct.ASN1Cert{derCert.Bytes, s.ca.Raw} + var sctList []ct.SignedCertificateTimestamp + + for _, server := range profile.CTLogServers { + log.Infof("submitting poisoned precertificate to %s", server) + var ctclient = client.New(server) + var resp *ct.SignedCertificateTimestamp + resp, err = ctclient.AddPreChain(prechain) + if err != nil { + return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err) + } + sctList = append(sctList, *resp) + } + + var serializedSCTList []byte + serializedSCTList, err = serializeSCTList(sctList) + if err != nil { + return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err) + } + + // Serialize again as an octet string before embedding + serializedSCTList, err = asn1.Marshal(serializedSCTList) + if err != nil { + return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err) + } + + var SCTListExtension = pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedSCTList} + certTBS.ExtraExtensions = append(certTBS.ExtraExtensions, SCTListExtension) + } + var signedCert []byte + signedCert, err = s.sign(&certTBS, profile) + if err != nil { + return nil, err + } + + if s.dbAccessor != nil { + var certRecord = certdb.CertificateRecord{ + Serial: certTBS.SerialNumber.String(), + // this relies on the specific behavior of x509.CreateCertificate + // which updates certTBS AuthorityKeyId from the signer's SubjectKeyId + AKI: hex.EncodeToString(certTBS.AuthorityKeyId), + CALabel: req.Label, + Status: "good", + Expiry: certTBS.NotAfter, + PEM: string(signedCert), + } + + err = s.dbAccessor.InsertCertificate(certRecord) + if err != nil { + return nil, err + } + log.Debug("saved certificate with serial number ", certTBS.SerialNumber) + } + + return signedCert, nil +} + +func serializeSCTList(sctList []ct.SignedCertificateTimestamp) ([]byte, error) { + var buf bytes.Buffer + for _, sct := range sctList { + sct, err := ct.SerializeSCT(sct) + if err != nil { + return nil, err + } + binary.Write(&buf, binary.BigEndian, uint16(len(sct))) + buf.Write(sct) + } + + var sctListLengthField = make([]byte, 2) + binary.BigEndian.PutUint16(sctListLengthField, uint16(buf.Len())) + return bytes.Join([][]byte{sctListLengthField, buf.Bytes()}, nil), nil +} + +// Info return a populated info.Resp struct or an error. +func (s *Signer) Info(req info.Req) (resp *info.Resp, err error) { + cert, err := s.Certificate(req.Label, req.Profile) + if err != nil { + return + } + + profile, err := signer.Profile(s, req.Profile) + if err != nil { + return + } + + resp = new(info.Resp) + if cert.Raw != nil { + resp.Certificate = string(bytes.TrimSpace(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}))) + } + resp.Usage = profile.Usage + resp.ExpiryString = profile.ExpiryString + + return +} + +// SigAlgo returns the RSA signer's signature algorithm. +func (s *Signer) SigAlgo() x509.SignatureAlgorithm { + return s.sigAlgo +} + +// Certificate returns the signer's certificate. +func (s *Signer) Certificate(label, profile string) (*x509.Certificate, error) { + cert := *s.ca + return &cert, nil +} + +// SetPolicy sets the signer's signature policy. +func (s *Signer) SetPolicy(policy *config.Signing) { + s.policy = policy +} + +// SetDBAccessor sets the signers' cert db accessor +func (s *Signer) SetDBAccessor(dba certdb.Accessor) { + s.dbAccessor = dba +} + +// Policy returns the signer's policy. +func (s *Signer) Policy() *config.Signing { + return s.policy +} diff --git a/vendor/github.com/cloudflare/cfssl/signer/signer.go b/vendor/github.com/cloudflare/cfssl/signer/signer.go new file mode 100644 index 000000000000..2911cfc28542 --- /dev/null +++ b/vendor/github.com/cloudflare/cfssl/signer/signer.go @@ -0,0 +1,385 @@ +// Package signer implements certificate signature functionality for CFSSL. +package signer + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rsa" + "crypto/sha1" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "errors" + "math/big" + "strings" + "time" + + "github.com/cloudflare/cfssl/certdb" + "github.com/cloudflare/cfssl/config" + "github.com/cloudflare/cfssl/csr" + cferr "github.com/cloudflare/cfssl/errors" + "github.com/cloudflare/cfssl/helpers" + "github.com/cloudflare/cfssl/info" +) + +// MaxPathLen is the default path length for a new CA certificate. +var MaxPathLen = 2 + +// Subject contains the information that should be used to override the +// subject information when signing a certificate. +type Subject struct { + CN string + Names []csr.Name `json:"names"` + SerialNumber string +} + +// Extension represents a raw extension to be included in the certificate. The +// "value" field must be hex encoded. +type Extension struct { + ID config.OID `json:"id"` + Critical bool `json:"critical"` + Value string `json:"value"` +} + +// SignRequest stores a signature request, which contains the hostname, +// the CSR, optional subject information, and the signature profile. +// +// Extensions provided in the signRequest are copied into the certificate, as +// long as they are in the ExtensionWhitelist for the signer's policy. +// Extensions requested in the CSR are ignored, except for those processed by +// ParseCertificateRequest (mainly subjectAltName). +type SignRequest struct { + Hosts []string `json:"hosts"` + Request string `json:"certificate_request"` + Subject *Subject `json:"subject,omitempty"` + Profile string `json:"profile"` + Label string `json:"label"` + Serial *big.Int `json:"serial,omitempty"` + Extensions []Extension `json:"extensions,omitempty"` +} + +// appendIf appends to a if s is not an empty string. +func appendIf(s string, a *[]string) { + if s != "" { + *a = append(*a, s) + } +} + +// Name returns the PKIX name for the subject. +func (s *Subject) Name() pkix.Name { + var name pkix.Name + name.CommonName = s.CN + + for _, n := range s.Names { + appendIf(n.C, &name.Country) + appendIf(n.ST, &name.Province) + appendIf(n.L, &name.Locality) + appendIf(n.O, &name.Organization) + appendIf(n.OU, &name.OrganizationalUnit) + } + name.SerialNumber = s.SerialNumber + return name +} + +// SplitHosts takes a comma-spearated list of hosts and returns a slice +// with the hosts split +func SplitHosts(hostList string) []string { + if hostList == "" { + return nil + } + + return strings.Split(hostList, ",") +} + +// A Signer contains a CA's certificate and private key for signing +// certificates, a Signing policy to refer to and a SignatureAlgorithm. +type Signer interface { + Info(info.Req) (*info.Resp, error) + Policy() *config.Signing + SetDBAccessor(certdb.Accessor) + SetPolicy(*config.Signing) + SigAlgo() x509.SignatureAlgorithm + Sign(req SignRequest) (cert []byte, err error) +} + +// Profile gets the specific profile from the signer +func Profile(s Signer, profile string) (*config.SigningProfile, error) { + var p *config.SigningProfile + policy := s.Policy() + if policy != nil && policy.Profiles != nil && profile != "" { + p = policy.Profiles[profile] + } + + if p == nil && policy != nil { + p = policy.Default + } + + if p == nil { + return nil, cferr.Wrap(cferr.APIClientError, cferr.ClientHTTPError, errors.New("profile must not be nil")) + } + return p, nil +} + +// DefaultSigAlgo returns an appropriate X.509 signature algorithm given +// the CA's private key. +func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm { + pub := priv.Public() + switch pub := pub.(type) { + case *rsa.PublicKey: + keySize := pub.N.BitLen() + switch { + case keySize >= 4096: + return x509.SHA512WithRSA + case keySize >= 3072: + return x509.SHA384WithRSA + case keySize >= 2048: + return x509.SHA256WithRSA + default: + return x509.SHA1WithRSA + } + case *ecdsa.PublicKey: + switch pub.Curve { + case elliptic.P256(): + return x509.ECDSAWithSHA256 + case elliptic.P384(): + return x509.ECDSAWithSHA384 + case elliptic.P521(): + return x509.ECDSAWithSHA512 + default: + return x509.ECDSAWithSHA1 + } + default: + return x509.UnknownSignatureAlgorithm + } +} + +// ParseCertificateRequest takes an incoming certificate request and +// builds a certificate template from it. +func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) { + csr, err := x509.ParseCertificateRequest(csrBytes) + if err != nil { + err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err) + return + } + + err = helpers.CheckSignature(csr, csr.SignatureAlgorithm, csr.RawTBSCertificateRequest, csr.Signature) + if err != nil { + err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err) + return + } + + template = &x509.Certificate{ + Subject: csr.Subject, + PublicKeyAlgorithm: csr.PublicKeyAlgorithm, + PublicKey: csr.PublicKey, + SignatureAlgorithm: s.SigAlgo(), + DNSNames: csr.DNSNames, + IPAddresses: csr.IPAddresses, + EmailAddresses: csr.EmailAddresses, + } + + return +} + +type subjectPublicKeyInfo struct { + Algorithm pkix.AlgorithmIdentifier + SubjectPublicKey asn1.BitString +} + +// ComputeSKI derives an SKI from the certificate's public key in a +// standard manner. This is done by computing the SHA-1 digest of the +// SubjectPublicKeyInfo component of the certificate. +func ComputeSKI(template *x509.Certificate) ([]byte, error) { + pub := template.PublicKey + encodedPub, err := x509.MarshalPKIXPublicKey(pub) + if err != nil { + return nil, err + } + + var subPKI subjectPublicKeyInfo + _, err = asn1.Unmarshal(encodedPub, &subPKI) + if err != nil { + return nil, err + } + + pubHash := sha1.Sum(subPKI.SubjectPublicKey.Bytes) + return pubHash[:], nil +} + +// FillTemplate is a utility function that tries to load as much of +// the certificate template as possible from the profiles and current +// template. It fills in the key uses, expiration, revocation URLs +// and SKI. +func FillTemplate(template *x509.Certificate, defaultProfile, profile *config.SigningProfile) error { + ski, err := ComputeSKI(template) + + var ( + eku []x509.ExtKeyUsage + ku x509.KeyUsage + backdate time.Duration + expiry time.Duration + notBefore time.Time + notAfter time.Time + crlURL, ocspURL string + ) + + // The third value returned from Usages is a list of unknown key usages. + // This should be used when validating the profile at load, and isn't used + // here. + ku, eku, _ = profile.Usages() + if profile.IssuerURL == nil { + profile.IssuerURL = defaultProfile.IssuerURL + } + + if ku == 0 && len(eku) == 0 { + return cferr.New(cferr.PolicyError, cferr.NoKeyUsages) + } + + if expiry = profile.Expiry; expiry == 0 { + expiry = defaultProfile.Expiry + } + + if crlURL = profile.CRL; crlURL == "" { + crlURL = defaultProfile.CRL + } + if ocspURL = profile.OCSP; ocspURL == "" { + ocspURL = defaultProfile.OCSP + } + if backdate = profile.Backdate; backdate == 0 { + backdate = -5 * time.Minute + } else { + backdate = -1 * profile.Backdate + } + + if !profile.NotBefore.IsZero() { + notBefore = profile.NotBefore.UTC() + } else { + notBefore = time.Now().Round(time.Minute).Add(backdate).UTC() + } + + if !profile.NotAfter.IsZero() { + notAfter = profile.NotAfter.UTC() + } else { + notAfter = notBefore.Add(expiry).UTC() + } + + template.NotBefore = notBefore + template.NotAfter = notAfter + template.KeyUsage = ku + template.ExtKeyUsage = eku + template.BasicConstraintsValid = true + template.IsCA = profile.CA + template.SubjectKeyId = ski + + if ocspURL != "" { + template.OCSPServer = []string{ocspURL} + } + if crlURL != "" { + template.CRLDistributionPoints = []string{crlURL} + } + + if len(profile.IssuerURL) != 0 { + template.IssuingCertificateURL = profile.IssuerURL + } + if len(profile.Policies) != 0 { + err = addPolicies(template, profile.Policies) + if err != nil { + return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err) + } + } + if profile.OCSPNoCheck { + ocspNoCheckExtension := pkix.Extension{ + Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1, 5}, + Critical: false, + Value: []byte{0x05, 0x00}, + } + template.ExtraExtensions = append(template.ExtraExtensions, ocspNoCheckExtension) + } + + return nil +} + +type policyInformation struct { + PolicyIdentifier asn1.ObjectIdentifier + Qualifiers []interface{} `asn1:"tag:optional,omitempty"` +} + +type cpsPolicyQualifier struct { + PolicyQualifierID asn1.ObjectIdentifier + Qualifier string `asn1:"tag:optional,ia5"` +} + +type userNotice struct { + ExplicitText string `asn1:"tag:optional,utf8"` +} +type userNoticePolicyQualifier struct { + PolicyQualifierID asn1.ObjectIdentifier + Qualifier userNotice +} + +var ( + // Per https://tools.ietf.org/html/rfc3280.html#page-106, this represents: + // iso(1) identified-organization(3) dod(6) internet(1) security(5) + // mechanisms(5) pkix(7) id-qt(2) id-qt-cps(1) + iDQTCertificationPracticeStatement = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 1} + // iso(1) identified-organization(3) dod(6) internet(1) security(5) + // mechanisms(5) pkix(7) id-qt(2) id-qt-unotice(2) + iDQTUserNotice = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2} + + // CTPoisonOID is the object ID of the critical poison extension for precertificates + // https://tools.ietf.org/html/rfc6962#page-9 + CTPoisonOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3} + + // SCTListOID is the object ID for the Signed Certificate Timestamp certificate extension + // https://tools.ietf.org/html/rfc6962#page-14 + SCTListOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2} +) + +// addPolicies adds Certificate Policies and optional Policy Qualifiers to a +// certificate, based on the input config. Go's x509 library allows setting +// Certificate Policies easily, but does not support nested Policy Qualifiers +// under those policies. So we need to construct the ASN.1 structure ourselves. +func addPolicies(template *x509.Certificate, policies []config.CertificatePolicy) error { + asn1PolicyList := []policyInformation{} + + for _, policy := range policies { + pi := policyInformation{ + // The PolicyIdentifier is an OID assigned to a given issuer. + PolicyIdentifier: asn1.ObjectIdentifier(policy.ID), + } + for _, qualifier := range policy.Qualifiers { + switch qualifier.Type { + case "id-qt-unotice": + pi.Qualifiers = append(pi.Qualifiers, + userNoticePolicyQualifier{ + PolicyQualifierID: iDQTUserNotice, + Qualifier: userNotice{ + ExplicitText: qualifier.Value, + }, + }) + case "id-qt-cps": + pi.Qualifiers = append(pi.Qualifiers, + cpsPolicyQualifier{ + PolicyQualifierID: iDQTCertificationPracticeStatement, + Qualifier: qualifier.Value, + }) + default: + return errors.New("Invalid qualifier type in Policies " + qualifier.Type) + } + } + asn1PolicyList = append(asn1PolicyList, pi) + } + + asn1Bytes, err := asn1.Marshal(asn1PolicyList) + if err != nil { + return err + } + + template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{ + Id: asn1.ObjectIdentifier{2, 5, 29, 32}, + Critical: false, + Value: asn1Bytes, + }) + return nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml new file mode 100644 index 000000000000..bde823d8ab73 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/.travis.yml @@ -0,0 +1,8 @@ +language: go + +go: + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - tip diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md new file mode 100644 index 000000000000..fd62e9490558 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md @@ -0,0 +1,96 @@ +## Migration Guide from v2 -> v3 + +Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. + +### `Token.Claims` is now an interface type + +The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. + +`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. + +The old example for parsing a token looked like this.. + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is now directly mapped to... + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + claims := token.Claims.(jwt.MapClaims) + fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) + } +``` + +`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. + +```go + type MyCustomClaims struct { + User string + *StandardClaims + } + + if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { + claims := token.Claims.(*MyCustomClaims) + fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) + } +``` + +### `ParseFromRequest` has been moved + +To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. + +`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. + +This simple parsing example: + +```go + if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is directly mapped to: + +```go + if token, err := request.ParseFromRequest(tokenString, request.OAuth2Extractor, req, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +There are several concrete `Extractor` types provided for your convenience: + +* `HeaderExtractor` will search a list of headers until one contains content. +* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. +* `MultiExtractor` will try a list of `Extractors` in order until one returns content. +* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. +* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument +* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header + + +### RSA signing methods no longer accept `[]byte` keys + +Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. + +To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. + +```go + func keyLookupFunc(*Token) (interface{}, error) { + // Don't forget to validate the alg is what you expect: + if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { + return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + } + + // Look up key + key, err := lookupPublicKey(token.Header["kid"]) + if err != nil { + return nil, err + } + + // Unpack key from PEM encoded PKCS8 + return jwt.ParseRSAPublicKeyFromPEM(key) + } +``` diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md index 8fa7734cfda9..f48365fafbfd 100644 --- a/vendor/github.com/dgrijalva/jwt-go/README.md +++ b/vendor/github.com/dgrijalva/jwt-go/README.md @@ -1,9 +1,16 @@ -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-jones-json-web-token.html) +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) + +[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) + +**BREAKING CHANGES:*** Version 3.0.0 is here. It includes _a lot_ of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. **NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect. + ## What the heck is a JWT? +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. + In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. @@ -12,39 +19,27 @@ The part in the middle is the interesting bit. It's called the Claims and conta ## What's in the box? -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are RSA256 and HMAC SHA256, though hooks are present for adding your own. - -## Parse and Verify - -Parsing and verifying tokens is pretty straight forward. You pass in the token and a function for looking up the key. This is done as a callback since you may need to parse the token to find out what signing method and key was used. - -```go - token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - return myLookupKey(token.Header["kid"]) - }) - - if err == nil && token.Valid { - deliverGoodness("!") - } else { - deliverUtterRejection(":(") - } -``` - -## Create a token - -```go - // Create the token - token := jwt.New(jwt.SigningMethodHS256) - // Set some claims - token.Claims["foo"] = "bar" - token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix() - // Sign and get the complete encoded token as a string - tokenString, err := token.SignedString(mySigningKey) -``` +This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. + +## Examples + +See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: + +* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) +* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) +* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) + +## Extensions + +This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. + +Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go + +## Compliance + +This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: + +* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. ## Project Status & Versioning @@ -54,8 +49,37 @@ This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning. +## Usage Tips + +### Signing vs Encryption + +A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: + +* The author of the token was in the possession of the signing secret +* The data has not been modified since it was signed + +It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. + +### Choosing a Signing Method + +There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. + +Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. + +Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. + +### JWT and OAuth + +It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. + +Without going too far down the rabbit hole, here's a description of the interaction of these technologies: + +* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. +* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. +* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. + ## More Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. For a more http centric example, see [this gist](https://gist.github.com/cryptix/45c33ecf0ae54828e63b). +The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in to documentation. diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md index 972722ee119e..b605b4509309 100644 --- a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md +++ b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md @@ -1,5 +1,56 @@ ## `jwt-go` Version History +#### 3.0.0 + +* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code + * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. + * `ParseFromRequest` has been moved to `request` subpackage and usage has changed + * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. +* Other Additions and Changes + * Added `Claims` interface type to allow users to decode the claims into a custom type + * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. + * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage + * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` + * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. + * Added several new, more specific, validation errors to error type bitmask + * Moved examples from README to executable example files + * Signing method registry is now thread safe + * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) + +#### 2.7.0 + +This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. + +* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying +* Error text for expired tokens includes how long it's been expired +* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` +* Documentation updates + +#### 2.6.0 + +* Exposed inner error within ValidationError +* Fixed validation errors when using UseJSONNumber flag +* Added several unit tests + +#### 2.5.0 + +* Added support for signing method none. You shouldn't use this. The API tries to make this clear. +* Updated/fixed some documentation +* Added more helpful error message when trying to parse tokens that begin with `BEARER ` + +#### 2.4.0 + +* Added new type, Parser, to allow for configuration of various parsing parameters + * You can now specify a list of valid signing methods. Anything outside this set will be rejected. + * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON +* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) +* Fixed some bugs with ECDSA parsing + +#### 2.3.0 + +* Added support for ECDSA signing methods +* Added support for RSA PSS signing methods (requires go v1.4) + #### 2.2.0 * Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go new file mode 100644 index 000000000000..f0228f02e033 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/claims.go @@ -0,0 +1,134 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// For a type to be a Claims object, it must just have a Valid method that determines +// if the token is invalid for any supported reason +type Claims interface { + Valid() error +} + +// Structured version of Claims Section, as referenced at +// https://tools.ietf.org/html/rfc7519#section-4.1 +// See examples for how to use this with your own claim types +type StandardClaims struct { + Audience string `json:"aud,omitempty"` + ExpiresAt int64 `json:"exp,omitempty"` + Id string `json:"jti,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + Issuer string `json:"iss,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + Subject string `json:"sub,omitempty"` +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if c.VerifyExpiresAt(now, false) == false { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("token is expired by %v", delta) + vErr.Errors |= ValidationErrorExpired + } + + if c.VerifyIssuedAt(now, false) == false { + vErr.Inner = fmt.Errorf("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if c.VerifyNotBefore(now, false) == false { + vErr.Inner = fmt.Errorf("token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + return verifyExp(c.ExpiresAt, cmp, req) +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + return verifyIat(c.IssuedAt, cmp, req) +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + return verifyNbf(c.NotBefore, cmp, req) +} + +// ----- helpers + +func verifyAud(aud string, cmp string, required bool) bool { + if aud == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyExp(exp int64, now int64, required bool) bool { + if exp == 0 { + return !required + } + return now <= exp +} + +func verifyIat(iat int64, now int64, required bool) bool { + if iat == 0 { + return !required + } + return now >= iat +} + +func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyNbf(nbf int64, now int64, required bool) bool { + if nbf == 0 { + return !required + } + return now >= nbf +} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go new file mode 100644 index 000000000000..2f59a2223638 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go @@ -0,0 +1,147 @@ +package jwt + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rand" + "errors" + "math/big" +) + +var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") +) + +// Implements the ECDSA family of signing methods signing methods +type SigningMethodECDSA struct { + Name string + Hash crypto.Hash + KeySize int + CurveBits int +} + +// Specific instances for EC256 and company +var ( + SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA +) + +func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) + + // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) + + // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) +} + +func (m *SigningMethodECDSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an ecdsa.PublicKey struct +func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } + + if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } + + r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { + return nil + } else { + return ErrECDSAVerification + } +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an ecdsa.PrivateKey struct +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize + + if m.CurveBits != curveBits { + return "", ErrInvalidKey + } + + keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } + + // We serialize the outpus (r and s) into big-endian byte arrays and pad + // them with zeros on the left to make sure the sizes work out. Both arrays + // must be keyBytes long, and the output must be 2*keyBytes long. + rBytes := r.Bytes() + rBytesPadded := make([]byte, keyBytes) + copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) + + sBytes := s.Bytes() + sBytesPadded := make([]byte, keyBytes) + copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) + + out := append(rBytesPadded, sBytesPadded...) + + return EncodeSegment(out), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go new file mode 100644 index 000000000000..d19624b7264f --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go @@ -0,0 +1,67 @@ +package jwt + +import ( + "crypto/ecdsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") +) + +// Parse PEM encoded Elliptic Curve Private Key Structure +func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + return nil, err + } + + var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go index e9e788ff9fa0..662df19d4e75 100644 --- a/vendor/github.com/dgrijalva/jwt-go/errors.go +++ b/vendor/github.com/dgrijalva/jwt-go/errors.go @@ -6,9 +6,9 @@ import ( // Error constants var ( - ErrInvalidKey = errors.New("key is invalid or of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - ErrNoTokenInRequest = errors.New("no token present in request") + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") ) // The errors that might occur when parsing and validating a token @@ -16,22 +16,42 @@ const ( ValidationErrorMalformed uint32 = 1 << iota // Token is malformed ValidationErrorUnverifiable // Token could not be verified because of signing problems ValidationErrorSignatureInvalid // Signature validation failed - ValidationErrorExpired // Exp validation failed - ValidationErrorNotValidYet // NBF validation failed + + // Standard Claim validation errors + ValidationErrorAudience // AUD validation failed + ValidationErrorExpired // EXP validation failed + ValidationErrorIssuedAt // IAT validation failed + ValidationErrorIssuer // ISS validation failed + ValidationErrorNotValidYet // NBF validation failed + ValidationErrorId // JTI validation failed + ValidationErrorClaimsInvalid // Generic claims validation error ) +// Helper for constructing a ValidationError with a string error message +func NewValidationError(errorText string, errorFlags uint32) *ValidationError { + return &ValidationError{ + text: errorText, + Errors: errorFlags, + } +} + // The error from Parse if token is not valid type ValidationError struct { - err string + Inner error // stores the error returned by external dependencies, i.e.: KeyFunc Errors uint32 // bitfield. see ValidationError... constants + text string // errors that do not have a valid error just have text } // Validation error is an error type func (e ValidationError) Error() string { - if e.err == "" { + if e.Inner != nil { + return e.Inner.Error() + } else if e.text != "" { + return e.text + } else { return "token is invalid" } - return e.err + return e.Inner.Error() } // No errors diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go index 402ff0859ac5..c22991925455 100644 --- a/vendor/github.com/dgrijalva/jwt-go/hmac.go +++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go @@ -44,26 +44,36 @@ func (m *SigningMethodHMAC) Alg() string { return m.Name } +// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - if keyBytes, ok := key.([]byte); ok { - var sig []byte - var err error - if sig, err = DecodeSegment(signature); err == nil { - if !m.Hash.Available() { - return ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - if !hmac.Equal(sig, hasher.Sum(nil)) { - err = ErrSignatureInvalid - } - } + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } + + // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { return err } - return ErrInvalidKey + // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } + + // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } + + // No validation errors. Signature is good. + return nil } // Implements the Sign method from SigningMethod for this signing method. diff --git a/vendor/github.com/dgrijalva/jwt-go/jwt.go b/vendor/github.com/dgrijalva/jwt-go/jwt.go deleted file mode 100644 index 06995aa6520a..000000000000 --- a/vendor/github.com/dgrijalva/jwt-go/jwt.go +++ /dev/null @@ -1,198 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "net/http" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use propries in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims map[string]interface{} // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: make(map[string]interface{}), - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i, _ := range parts { - var source map[string]interface{} - if i == 0 { - source = t.Header - } else { - source = t.Claims - } - - var jsonValue []byte - if jsonValue, err = json.Marshal(source); err != nil { - return "", err - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - parts := strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, &ValidationError{err: "token contains an invalid number of segments", Errors: ValidationErrorMalformed} - } - - var err error - token := &Token{Raw: tokenString} - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(claimBytes, &token.Claims); err != nil { - return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, &ValidationError{err: "signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable} - } - } else { - return token, &ValidationError{err: "signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable} - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, &ValidationError{err: "no Keyfunc was provided.", Errors: ValidationErrorUnverifiable} - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable} - } - - // Check expiration times - vErr := &ValidationError{} - now := TimeFunc().Unix() - if exp, ok := token.Claims["exp"].(float64); ok { - if now > int64(exp) { - vErr.err = "token is expired" - vErr.Errors |= ValidationErrorExpired - } - } - if nbf, ok := token.Claims["nbf"].(float64); ok { - if now < int64(nbf) { - vErr.err = "token is not valid yet" - vErr.Errors |= ValidationErrorNotValidYet - } - } - - // Perform validation - if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil { - vErr.err = err.Error() - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// Try to find the token in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -// Currently, it looks in the Authorization header as well as -// looking for an 'access_token' request parameter in req.Form. -func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) { - - // Look for an Authorization header - if ah := req.Header.Get("Authorization"); ah != "" { - // Should be a bearer token - if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" { - return Parse(ah[7:], keyFunc) - } - } - - // Look for "access_token" parameter - req.ParseMultipartForm(10e6) - if tokStr := req.Form.Get("access_token"); tokStr != "" { - return Parse(tokStr, keyFunc) - } - - return nil, ErrNoTokenInRequest - -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - - return base64.URLEncoding.DecodeString(seg) -} diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go new file mode 100644 index 000000000000..291213c460d4 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/map_claims.go @@ -0,0 +1,94 @@ +package jwt + +import ( + "encoding/json" + "errors" + // "fmt" +) + +// Claims type that uses the map[string]interface{} for JSON decoding +// This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + aud, _ := m["aud"].(string) + return verifyAud(aud, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + switch exp := m["exp"].(type) { + case float64: + return verifyExp(int64(exp), cmp, req) + case json.Number: + v, _ := exp.Int64() + return verifyExp(v, cmp, req) + } + return req == false +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + switch iat := m["iat"].(type) { + case float64: + return verifyIat(int64(iat), cmp, req) + case json.Number: + v, _ := iat.Int64() + return verifyIat(v, cmp, req) + } + return req == false +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + switch nbf := m["nbf"].(type) { + case float64: + return verifyNbf(int64(nbf), cmp, req) + case json.Number: + v, _ := nbf.Int64() + return verifyNbf(v, cmp, req) + } + return req == false +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + if m.VerifyExpiresAt(now, false) == false { + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } + + if m.VerifyIssuedAt(now, false) == false { + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if m.VerifyNotBefore(now, false) == false { + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go new file mode 100644 index 000000000000..f04d189d067b --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/none.go @@ -0,0 +1,52 @@ +package jwt + +// Implements the none signing method. This is required by the spec +// but you probably should never use it. +var SigningMethodNone *signingMethodNone + +const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" + +var NoneSignatureTypeDisallowedError error + +type signingMethodNone struct{} +type unsafeNoneMagicConstant string + +func init() { + SigningMethodNone = &signingMethodNone{} + NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + + RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { + return SigningMethodNone + }) +} + +func (m *signingMethodNone) Alg() string { + return "none" +} + +// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { + // Key must be UnsafeAllowNoneSignatureType to prevent accidentally + // accepting 'none' signing method + if _, ok := key.(unsafeNoneMagicConstant); !ok { + return NoneSignatureTypeDisallowedError + } + // If signing method is none, signature must be an empty string + if signature != "" { + return NewValidationError( + "'none' signing method with non-empty signature", + ValidationErrorSignatureInvalid, + ) + } + + // Accept 'none' signing method. + return nil +} + +// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { + if _, ok := key.(unsafeNoneMagicConstant); ok { + return "", nil + } + return "", NoneSignatureTypeDisallowedError +} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go new file mode 100644 index 000000000000..7bf1c4ea0842 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -0,0 +1,131 @@ +package jwt + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + ValidMethods []string // If populated, only these methods will be considered valid + UseJSONNumber bool // Use JSON Number format in JSON decoder + SkipClaimsValidation bool // Skip claims validation during token parsing +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + parts := strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } + + var err error + token := &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // parse Claims + var claimBytes []byte + token.Claims = claims + + if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } + + // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } + + // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } + + vErr := &ValidationError{} + + // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { + + // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } + + // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } + + if vErr.valid() { + token.Valid = true + return token, nil + } + + return token, vErr +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go index cddffced5ae1..0ae0b1984e5a 100644 --- a/vendor/github.com/dgrijalva/jwt-go/rsa.go +++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go @@ -44,8 +44,7 @@ func (m *SigningMethodRSA) Alg() string { } // Implements the Verify method from SigningMethod -// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as -// []byte, or an rsa.PublicKey structure. +// For this signing method, must be an rsa.PublicKey structure. func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { var err error @@ -56,16 +55,10 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface } var rsaKey *rsa.PublicKey + var ok bool - switch k := key.(type) { - case []byte: - if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil { - return err - } - case *rsa.PublicKey: - rsaKey = k - default: - return ErrInvalidKey + if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType } // Create hasher @@ -80,20 +73,13 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface } // Implements the Sign method from SigningMethod -// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as -// []byte, or an rsa.PrivateKey structure. +// For this signing method, must be an rsa.PrivateKey structure. func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { - var err error var rsaKey *rsa.PrivateKey + var ok bool - switch k := key.(type) { - case []byte: - if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil { - return "", err - } - case *rsa.PrivateKey: - rsaKey = k - default: + // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { return "", ErrInvalidKey } diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go new file mode 100644 index 000000000000..10ee9db8a4ed --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go @@ -0,0 +1,126 @@ +// +build go1.4 + +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSAPSS family of signing methods signing methods +type SigningMethodRSAPSS struct { + *SigningMethodRSA + Options *rsa.PSSOptions +} + +// Specific instances for RS/PS and company +var ( + SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS +) + +func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA256, + }, + } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) + + // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA384, + }, + } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) + + // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA512, + }, + } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an rsa.PublicKey struct +func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an rsa.PrivateKey struct +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + + switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go index 6f3b6ff04fa2..213a90dbbf8d 100644 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go @@ -10,6 +10,7 @@ import ( var ( ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") + ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") ) // Parse PEM encoded PKCS1 or PKCS8 private key @@ -61,7 +62,7 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { var pkey *rsa.PublicKey var ok bool if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPrivateKey + return nil, ErrNotRSAPublicKey } return pkey, nil diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go index 109dd0f5a4a0..ed1f212b21e1 100644 --- a/vendor/github.com/dgrijalva/jwt-go/signing_method.go +++ b/vendor/github.com/dgrijalva/jwt-go/signing_method.go @@ -1,22 +1,33 @@ package jwt +import ( + "sync" +) + var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) -// Signing method +// Implement SigningMethod to add new methods for signing or verifying tokens. type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error - Sign(signingString string, key interface{}) (string, error) - Alg() string + Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') } // Register the "alg" name and a factory function for signing method. // This is typically done during init() in the method's implementation func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + signingMethods[alg] = f } // Get a signing method from an "alg" string func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + if methodF, ok := signingMethods[alg]; ok { method = methodF() } diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go new file mode 100644 index 000000000000..d637e0867c65 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/token.go @@ -0,0 +1,108 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" + "time" +) + +// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). +// You can override it to use another time value. This is useful for testing or if your +// server uses a different time zone than your tokens. +var TimeFunc = time.Now + +// Parse methods use this callback function to supply +// the key for verification. The function receives the parsed, +// but unverified Token. This allows you to use properties in the +// Header of the token (such as `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// A JWT Token. Different fields will be used depending on whether you're +// creating or parsing/verifying a token. +type Token struct { + Raw string // The raw token. Populated when you Parse a token + Method SigningMethod // The signing method used or to be used + Header map[string]interface{} // The first segment of the token + Claims Claims // The second segment of the token + Signature string // The third segment of the token. Populated when you Parse a token + Valid bool // Is the token valid? Populated when you Parse/Verify a token +} + +// Create a new Token. Takes a signing method +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// Get the complete, signed token +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// Generate the signing string. This is the +// most expensive part of the whole deal. Unless you +// need this for something special, just go straight for +// the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + parts := make([]string, 2) + for i, _ := range parts { + var jsonValue []byte + if i == 0 { + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + } else { + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + } + + parts[i] = EncodeSegment(jsonValue) + } + return strings.Join(parts, "."), nil +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return new(Parser).Parse(tokenString, keyFunc) +} + +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) +} + +// Encode JWT specific base64url encoding with padding stripped +func EncodeSegment(seg []byte) string { + return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") +} + +// Decode JWT specific base64url encoding with padding stripped +func DecodeSegment(seg string) ([]byte, error) { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + + return base64.URLEncoding.DecodeString(seg) +} diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE index c7a3f0cfd456..8f3fee627a45 100644 --- a/vendor/github.com/docker/docker/LICENSE +++ b/vendor/github.com/docker/docker/LICENSE @@ -176,7 +176,7 @@ END OF TERMS AND CONDITIONS - Copyright 2013-2015 Docker, Inc. + Copyright 2013-2016 Docker, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE index 6e6f469ab9b2..8a37c1c7bc49 100644 --- a/vendor/github.com/docker/docker/NOTICE +++ b/vendor/github.com/docker/docker/NOTICE @@ -1,5 +1,5 @@ Docker -Copyright 2012-2015 Docker, Inc. +Copyright 2012-2016 Docker, Inc. This product includes software developed at Docker, Inc. (https://www.docker.com). diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go new file mode 100644 index 000000000000..422e4bbd92b2 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go @@ -0,0 +1,40 @@ +package jsonlog + +import ( + "encoding/json" + "fmt" + "time" +) + +// JSONLog represents a log message, typically a single entry from a given log stream. +// JSONLogs can be easily serialized to and from JSON and support custom formatting. +type JSONLog struct { + // Log is the log message + Log string `json:"log,omitempty"` + // Stream is the log source + Stream string `json:"stream,omitempty"` + // Created is the created timestamp of log + Created time.Time `json:"time"` +} + +// Format returns the log formatted according to format +// If format is nil, returns the log message +// If format is json, returns the log marshaled in json format +// By default, returns the log with the log time formatted according to format. +func (jl *JSONLog) Format(format string) (string, error) { + if format == "" { + return jl.Log, nil + } + if format == "json" { + m, err := json.Marshal(jl) + return string(m), err + } + return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil +} + +// Reset resets the log to nil. +func (jl *JSONLog) Reset() { + jl.Log = "" + jl.Stream = "" + jl.Created = time.Time{} +} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go new file mode 100644 index 000000000000..83ce684a8ef8 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go @@ -0,0 +1,178 @@ +// This code was initially generated by ffjson +// This code was generated via the following steps: +// $ go get -u github.com/pquerna/ffjson +// $ make BIND_DIR=. shell +// $ ffjson pkg/jsonlog/jsonlog.go +// $ mv pkg/jsonglog/jsonlog_ffjson.go pkg/jsonlog/jsonlog_marshalling.go +// +// It has been modified to improve the performance of time marshalling to JSON +// and to clean it up. +// Should this code need to be regenerated when the JSONLog struct is changed, +// the relevant changes which have been made are: +// import ( +// "bytes" +//- +// "unicode/utf8" +// ) +// +// func (mj *JSONLog) MarshalJSON() ([]byte, error) { +//@@ -20,13 +16,13 @@ func (mj *JSONLog) MarshalJSON() ([]byte, error) { +// } +// return buf.Bytes(), nil +// } +//+ +// func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { +//- var err error +//- var obj []byte +//- var first bool = true +//- _ = obj +//- _ = err +//- _ = first +//+ var ( +//+ err error +//+ timestamp string +//+ first bool = true +//+ ) +// buf.WriteString(`{`) +// if len(mj.Log) != 0 { +// if first == true { +//@@ -52,11 +48,11 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { +// buf.WriteString(`,`) +// } +// buf.WriteString(`"time":`) +//- obj, err = mj.Created.MarshalJSON() +//+ timestamp, err = FastTimeMarshalJSON(mj.Created) +// if err != nil { +// return err +// } +//- buf.Write(obj) +//+ buf.WriteString(timestamp) +// buf.WriteString(`}`) +// return nil +// } +// @@ -81,9 +81,10 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { +// if len(mj.Log) != 0 { +// - if first == true { +// - first = false +// - } else { +// - buf.WriteString(`,`) +// - } +// + first = false +// buf.WriteString(`"log":`) +// ffjsonWriteJSONString(buf, mj.Log) +// } + +package jsonlog + +import ( + "bytes" + "unicode/utf8" +) + +// MarshalJSON marshals the JSONLog. +func (mj *JSONLog) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + buf.Grow(1024) + if err := mj.MarshalJSONBuf(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// MarshalJSONBuf marshals the JSONLog and stores the result to a bytes.Buffer. +func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { + var ( + err error + timestamp string + first = true + ) + buf.WriteString(`{`) + if len(mj.Log) != 0 { + first = false + buf.WriteString(`"log":`) + ffjsonWriteJSONString(buf, mj.Log) + } + if len(mj.Stream) != 0 { + if first { + first = false + } else { + buf.WriteString(`,`) + } + buf.WriteString(`"stream":`) + ffjsonWriteJSONString(buf, mj.Stream) + } + if !first { + buf.WriteString(`,`) + } + buf.WriteString(`"time":`) + timestamp, err = FastTimeMarshalJSON(mj.Created) + if err != nil { + return err + } + buf.WriteString(timestamp) + buf.WriteString(`}`) + return nil +} + +func ffjsonWriteJSONString(buf *bytes.Buffer, s string) { + const hex = "0123456789abcdef" + + buf.WriteByte('"') + start := 0 + for i := 0; i < len(s); { + if b := s[i]; b < utf8.RuneSelf { + if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { + i++ + continue + } + if start < i { + buf.WriteString(s[start:i]) + } + switch b { + case '\\', '"': + buf.WriteByte('\\') + buf.WriteByte(b) + case '\n': + buf.WriteByte('\\') + buf.WriteByte('n') + case '\r': + buf.WriteByte('\\') + buf.WriteByte('r') + default: + + buf.WriteString(`\u00`) + buf.WriteByte(hex[b>>4]) + buf.WriteByte(hex[b&0xF]) + } + i++ + start = i + continue + } + c, size := utf8.DecodeRuneInString(s[i:]) + if c == utf8.RuneError && size == 1 { + if start < i { + buf.WriteString(s[start:i]) + } + buf.WriteString(`\ufffd`) + i += size + start = i + continue + } + + if c == '\u2028' || c == '\u2029' { + if start < i { + buf.WriteString(s[start:i]) + } + buf.WriteString(`\u202`) + buf.WriteByte(hex[c&0xF]) + i += size + start = i + continue + } + i += size + } + if start < len(s) { + buf.WriteString(s[start:]) + } + buf.WriteByte('"') +} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go new file mode 100644 index 000000000000..df522c0d66f5 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go @@ -0,0 +1,122 @@ +package jsonlog + +import ( + "bytes" + "encoding/json" + "unicode/utf8" +) + +// JSONLogs is based on JSONLog. +// It allows marshalling JSONLog from Log as []byte +// and an already marshalled Created timestamp. +type JSONLogs struct { + Log []byte `json:"log,omitempty"` + Stream string `json:"stream,omitempty"` + Created string `json:"time"` + + // json-encoded bytes + RawAttrs json.RawMessage `json:"attrs,omitempty"` +} + +// MarshalJSONBuf is based on the same method from JSONLog +// It has been modified to take into account the necessary changes. +func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { + var first = true + + buf.WriteString(`{`) + if len(mj.Log) != 0 { + first = false + buf.WriteString(`"log":`) + ffjsonWriteJSONBytesAsString(buf, mj.Log) + } + if len(mj.Stream) != 0 { + if first == true { + first = false + } else { + buf.WriteString(`,`) + } + buf.WriteString(`"stream":`) + ffjsonWriteJSONString(buf, mj.Stream) + } + if len(mj.RawAttrs) > 0 { + if first { + first = false + } else { + buf.WriteString(`,`) + } + buf.WriteString(`"attrs":`) + buf.Write(mj.RawAttrs) + } + if !first { + buf.WriteString(`,`) + } + buf.WriteString(`"time":`) + buf.WriteString(mj.Created) + buf.WriteString(`}`) + return nil +} + +// This is based on ffjsonWriteJSONBytesAsString. It has been changed +// to accept a string passed as a slice of bytes. +func ffjsonWriteJSONBytesAsString(buf *bytes.Buffer, s []byte) { + const hex = "0123456789abcdef" + + buf.WriteByte('"') + start := 0 + for i := 0; i < len(s); { + if b := s[i]; b < utf8.RuneSelf { + if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { + i++ + continue + } + if start < i { + buf.Write(s[start:i]) + } + switch b { + case '\\', '"': + buf.WriteByte('\\') + buf.WriteByte(b) + case '\n': + buf.WriteByte('\\') + buf.WriteByte('n') + case '\r': + buf.WriteByte('\\') + buf.WriteByte('r') + default: + + buf.WriteString(`\u00`) + buf.WriteByte(hex[b>>4]) + buf.WriteByte(hex[b&0xF]) + } + i++ + start = i + continue + } + c, size := utf8.DecodeRune(s[i:]) + if c == utf8.RuneError && size == 1 { + if start < i { + buf.Write(s[start:i]) + } + buf.WriteString(`\ufffd`) + i += size + start = i + continue + } + + if c == '\u2028' || c == '\u2029' { + if start < i { + buf.Write(s[start:i]) + } + buf.WriteString(`\u202`) + buf.WriteByte(hex[c&0xF]) + i += size + start = i + continue + } + i += size + } + if start < len(s) { + buf.Write(s[start:]) + } + buf.WriteByte('"') +} diff --git a/vendor/github.com/docker/docker/pkg/timeutils/json.go b/vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go similarity index 74% rename from vendor/github.com/docker/docker/pkg/timeutils/json.go rename to vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go index 8043d69d18f0..21173381495d 100644 --- a/vendor/github.com/docker/docker/pkg/timeutils/json.go +++ b/vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go @@ -1,4 +1,5 @@ -package timeutils +// Package jsonlog provides helper functions to parse and print time (time.Time) as JSON. +package jsonlog import ( "errors" @@ -14,9 +15,9 @@ const ( JSONFormat = `"` + time.RFC3339Nano + `"` ) -// FastMarshalJSON avoids one of the extra allocations that +// FastTimeMarshalJSON avoids one of the extra allocations that // time.MarshalJSON is making. -func FastMarshalJSON(t time.Time) (string, error) { +func FastTimeMarshalJSON(t time.Time) (string, error) { if y := t.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. diff --git a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go index 7db1626e48c6..65cccbce177d 100644 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go @@ -7,11 +7,13 @@ import ( "strings" "time" + "github.com/docker/docker/pkg/jsonlog" "github.com/docker/docker/pkg/term" - "github.com/docker/docker/pkg/timeutils" - "github.com/docker/docker/pkg/units" + "github.com/docker/go-units" ) +// JSONError wraps a concrete Code and Message, `Code` is +// is a integer error code, `Message` is the error message. type JSONError struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"` @@ -21,10 +23,14 @@ func (e *JSONError) Error() string { return e.Message } +// JSONProgress describes a Progress. terminalFd is the fd of the current terminal, +// Start is the initial value for the operation. Current is the current status and +// value of the progress made towards Total. Total is the end value describing when +// we made 100% progress for an operation. type JSONProgress struct { terminalFd uintptr - Current int `json:"current,omitempty"` - Total int `json:"total,omitempty"` + Current int64 `json:"current,omitempty"` + Total int64 `json:"total,omitempty"` Start int64 `json:"start,omitempty"` } @@ -54,17 +60,23 @@ func (p *JSONProgress) String() string { percentage = 50 } if width > 110 { - // this number can't be negetive gh#7136 + // 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)) } + 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) + } + if p.Current > 0 && p.Start > 0 && percentage < 50 { - fromStart := time.Now().UTC().Sub(time.Unix(int64(p.Start), 0)) + fromStart := time.Now().UTC().Sub(time.Unix(p.Start, 0)) perEntry := fromStart / time.Duration(p.Current) left := time.Duration(p.Total-p.Current) * perEntry left = (left / time.Second) * time.Second @@ -76,6 +88,9 @@ func (p *JSONProgress) String() string { return pbBox + numbersBox + timeLeftBox } +// 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"` @@ -84,10 +99,16 @@ type JSONMessage struct { ID string `json:"id,omitempty"` From string `json:"from,omitempty"` Time int64 `json:"time,omitempty"` + TimeNano int64 `json:"timeNano,omitempty"` Error *JSONError `json:"errorDetail,omitempty"` ErrorMessage string `json:"error,omitempty"` //deprecated + // Aux contains out-of-band data, such as digests for push signing. + Aux *json.RawMessage `json:"aux,omitempty"` } +// Display displays the JSONMessage to `out`. `isTerminal` describes if `out` +// is a terminal. If this is the case, it will erase the entire current line +// when displaying the progressbar. func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { if jm.Error != nil { if jm.Error.Code == 401 { @@ -103,8 +124,10 @@ func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { } else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal return nil } - if jm.Time != 0 { - fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(timeutils.RFC3339NanoFixed)) + if jm.TimeNano != 0 { + fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(jsonlog.RFC3339NanoFixed)) + } else if jm.Time != 0 { + fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(jsonlog.RFC3339NanoFixed)) } if jm.ID != "" { fmt.Fprintf(out, "%s: ", jm.ID) @@ -124,13 +147,16 @@ func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { return nil } -func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool) error { +// DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal` +// describes if `out` is a terminal. If this is the case, it will print `\n` at the end of +// each line and move the cursor while displaying. +func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(*json.RawMessage)) error { var ( - dec = json.NewDecoder(in) - ids = make(map[string]int) - diff = 0 + dec = json.NewDecoder(in) + ids = make(map[string]int) ) for { + diff := 0 var jm JSONMessage if err := dec.Decode(&jm); err != nil { if err == io.EOF { @@ -139,28 +165,51 @@ func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, return err } + if jm.Aux != nil { + if auxCallback != nil { + auxCallback(jm.Aux) + } + 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 = len(ids) ids[jm.ID] = line if isTerminal { fmt.Fprintf(out, "\n") } - diff = 0 } else { diff = len(ids) - line } - if jm.ID != "" && isTerminal { + if isTerminal { + // NOTE: this appears to be necessary even if + // diff == 0. // [{diff}A = move cursor up diff rows fmt.Fprintf(out, "%c[%dA", 27, 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]int) } err := jm.Display(out, isTerminal) if jm.ID != "" && isTerminal { + // NOTE: this appears to be necessary even if + // diff == 0. // [{diff}B = move cursor down diff rows fmt.Fprintf(out, "%c[%dB", 27, diff) } diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go new file mode 100644 index 000000000000..9b15bfff4c9a --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/longpath/longpath.go @@ -0,0 +1,26 @@ +// longpath introduces some constants and helper functions for handling long paths +// in Windows, which are expected to be prepended with `\\?\` and followed by either +// a drive letter, a UNC server\share, or a volume identifier. + +package longpath + +import ( + "strings" +) + +// Prefix is the longpath prefix for Windows file paths. +const Prefix = `\\?\` + +// AddPrefix will add the Windows long path prefix to the path provided if +// it does not already have it. +func AddPrefix(path string) string { + if !strings.HasPrefix(path, Prefix) { + if strings.HasPrefix(path, `\\`) { + // This is a UNC path, so we need to add 'UNC' to the path as well. + path = Prefix + `UNC` + path[1:] + } else { + path = Prefix + path + } + } + return path +} diff --git a/vendor/github.com/docker/docker/pkg/mount/flags.go b/vendor/github.com/docker/docker/pkg/mount/flags.go index 17dbd7a64cf4..d2fb1fb4d0d5 100644 --- a/vendor/github.com/docker/docker/pkg/mount/flags.go +++ b/vendor/github.com/docker/docker/pkg/mount/flags.go @@ -1,6 +1,7 @@ package mount import ( + "fmt" "strings" ) @@ -67,3 +68,25 @@ func parseOptions(options string) (int, string) { } return flag, strings.Join(data, ",") } + +// ParseTmpfsOptions parse fstab type mount options into flags and data +func ParseTmpfsOptions(options string) (int, string, error) { + flags, data := parseOptions(options) + validFlags := map[string]bool{ + "": true, + "size": true, + "mode": true, + "uid": true, + "gid": true, + "nr_inodes": true, + "nr_blocks": true, + "mpol": true, + } + for _, o := range strings.Split(data, ",") { + opt := strings.SplitN(o, "=", 2) + if !validFlags[opt[0]] { + return 0, "", fmt.Errorf("Invalid tmpfs option %q", opt) + } + } + return flags, data, nil +} diff --git a/vendor/github.com/docker/docker/pkg/mount/flags_linux.go b/vendor/github.com/docker/docker/pkg/mount/flags_linux.go index 2f9f5c58ee5d..dc696dce9075 100644 --- a/vendor/github.com/docker/docker/pkg/mount/flags_linux.go +++ b/vendor/github.com/docker/docker/pkg/mount/flags_linux.go @@ -23,7 +23,7 @@ const ( SYNCHRONOUS = syscall.MS_SYNCHRONOUS // DIRSYNC will force all directory updates within the file system to be done - // synchronously. This affects the following system calls: creat, link, + // synchronously. This affects the following system calls: create, link, // unlink, symlink, mkdir, rmdir, mknod and rename. DIRSYNC = syscall.MS_DIRSYNC diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go index 8245f01d42bc..b8d9aa5c732c 100644 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go +++ b/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go @@ -1,4 +1,4 @@ -// +build !linux,!freebsd freebsd,!cgo +// +build !windows,!linux,!freebsd freebsd,!cgo package mount diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go new file mode 100644 index 000000000000..dab8a37ed01d --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go @@ -0,0 +1,6 @@ +package mount + +func parseMountTable() ([]*Info, error) { + // Do NOT return an error! + return nil, nil +} diff --git a/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go b/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go index 47303bbcb610..8ceec84bc6c8 100644 --- a/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go +++ b/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go @@ -61,8 +61,7 @@ func ensureMountedAs(mountPoint, options string) error { return err } } - mounted, err = Mounted(mountPoint) - if err != nil { + if _, err = Mounted(mountPoint); err != nil { return err } diff --git a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go index 684b4d4cd1ad..b37ae39f8ed9 100644 --- a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go +++ b/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go @@ -3,44 +3,57 @@ package stdcopy import ( "encoding/binary" "errors" + "fmt" "io" "github.com/Sirupsen/logrus" ) -const ( - StdWriterPrefixLen = 8 - StdWriterFdIndex = 0 - StdWriterSizeIndex = 4 -) - -type StdType [StdWriterPrefixLen]byte +// StdType is the type of standard stream +// a writer can multiplex to. +type StdType byte -var ( - Stdin StdType = StdType{0: 0} - Stdout StdType = StdType{0: 1} - Stderr StdType = StdType{0: 2} +const ( + // Stdin represents standard input stream type. + Stdin StdType = iota + // Stdout represents standard output stream type. + Stdout + // Stderr represents standard error steam type. + Stderr + + stdWriterPrefixLen = 8 + stdWriterFdIndex = 0 + stdWriterSizeIndex = 4 + + startingBufLen = 32*1024 + stdWriterPrefixLen + 1 ) -type StdWriter struct { +// stdWriter is wrapper of io.Writer with extra customized info. +type stdWriter struct { io.Writer - prefix StdType - sizeBuf []byte + prefix byte } -func (w *StdWriter) Write(buf []byte) (n int, err error) { - var n1, n2 int +// Write sends the buffer to the underneath writer. +// It insert 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(buf []byte) (n int, err error) { if w == nil || w.Writer == nil { return 0, errors.New("Writer not instantiated") } - binary.BigEndian.PutUint32(w.prefix[4:], uint32(len(buf))) - n1, err = w.Writer.Write(w.prefix[:]) - if err != nil { - n = n1 - StdWriterPrefixLen - } else { - n2, err = w.Writer.Write(buf) - n = n1 + n2 - StdWriterPrefixLen + if buf == nil { + return 0, nil } + + header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix} + binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(buf))) + + line := append(header[:], buf...) + + n, err = w.Writer.Write(line) + n -= stdWriterPrefixLen + if n < 0 { n = 0 } @@ -53,16 +66,13 @@ func (w *StdWriter) Write(buf []byte) (n int, err error) { // 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) *StdWriter { - return &StdWriter{ - Writer: w, - prefix: t, - sizeBuf: make([]byte, 4), +func NewStdWriter(w io.Writer, t StdType) io.Writer { + return &stdWriter{ + Writer: w, + prefix: byte(t), } } -var ErrInvalidStdHeader = errors.New("Unrecognized input header") - // StdCopy is a modified version of io.Copy. // // StdCopy will demultiplex `src`, assuming that it contains two streams, @@ -75,7 +85,7 @@ var ErrInvalidStdHeader = errors.New("Unrecognized input header") // `written` will hold the total number of bytes written to `dstout` and `dsterr`. func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { var ( - buf = make([]byte, 32*1024+StdWriterPrefixLen+1) + buf = make([]byte, startingBufLen) bufLen = len(buf) nr, nw int er, ew error @@ -85,12 +95,12 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) for { // Make sure we have at least a full header - for nr < StdWriterPrefixLen { + for nr < stdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { - if nr < StdWriterPrefixLen { + if nr < stdWriterPrefixLen { logrus.Debugf("Corrupted prefix: %v", buf[:nr]) return written, nil } @@ -103,40 +113,40 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) } // Check the first byte to know where to write - switch buf[StdWriterFdIndex] { - case 0: + switch StdType(buf[stdWriterFdIndex]) { + case Stdin: fallthrough - case 1: + case Stdout: // Write on stdout out = dstout - case 2: + case Stderr: // Write on stderr out = dsterr default: - logrus.Debugf("Error selecting output fd: (%d)", buf[StdWriterFdIndex]) - return 0, ErrInvalidStdHeader + logrus.Debugf("Error selecting output fd: (%d)", buf[stdWriterFdIndex]) + return 0, fmt.Errorf("Unrecognized input header: %d", buf[stdWriterFdIndex]) } // Retrieve the size of the frame - frameSize = int(binary.BigEndian.Uint32(buf[StdWriterSizeIndex : StdWriterSizeIndex+4])) + frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) logrus.Debugf("framesize: %d", frameSize) // Check if the buffer is big enough to read the frame. // Extend it if necessary. - if frameSize+StdWriterPrefixLen > bufLen { - logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+StdWriterPrefixLen-bufLen+1, len(buf)) - buf = append(buf, make([]byte, frameSize+StdWriterPrefixLen-bufLen+1)...) + if frameSize+stdWriterPrefixLen > bufLen { + logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+stdWriterPrefixLen-bufLen+1, len(buf)) + buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) bufLen = len(buf) } // While the amount of bytes read is less than the size of the frame + header, we keep reading - for nr < frameSize+StdWriterPrefixLen { + for nr < frameSize+stdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { - if nr < frameSize+StdWriterPrefixLen { - logrus.Debugf("Corrupted frame: %v", buf[StdWriterPrefixLen:nr]) + if nr < frameSize+stdWriterPrefixLen { + logrus.Debugf("Corrupted frame: %v", buf[stdWriterPrefixLen:nr]) return written, nil } break @@ -148,7 +158,7 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) } // Write the retrieved frame (without header) - nw, ew = out.Write(buf[StdWriterPrefixLen : frameSize+StdWriterPrefixLen]) + nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) if ew != nil { logrus.Debugf("Error writing frame: %s", ew) return 0, ew @@ -161,8 +171,8 @@ func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) written += int64(nw) // Move the rest of the buffer to the beginning - copy(buf, buf[frameSize+StdWriterPrefixLen:]) + copy(buf, buf[frameSize+stdWriterPrefixLen:]) // Move the index - nr -= frameSize + StdWriterPrefixLen + nr -= frameSize + stdWriterPrefixLen } } diff --git a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE index 9e4bd4dbee94..34c4ea7c5059 100644 --- a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE +++ b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE @@ -176,7 +176,7 @@ END OF TERMS AND CONDITIONS - Copyright 2014-2015 Docker, Inc. + Copyright 2014-2016 Docker, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD index ac74d8f0496c..9b4f4a294ea6 100644 --- a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD +++ b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD @@ -1,4 +1,4 @@ -Copyright (c) 2014-2015 The Docker & Go Authors. All rights reserved. +Copyright (c) 2014-2016 The Docker & Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are diff --git a/vendor/github.com/docker/docker/pkg/symlink/README.md b/vendor/github.com/docker/docker/pkg/symlink/README.md index 0d1dbb70e64e..8dba54fd089d 100644 --- a/vendor/github.com/docker/docker/pkg/symlink/README.md +++ b/vendor/github.com/docker/docker/pkg/symlink/README.md @@ -1,4 +1,5 @@ -Package symlink implements EvalSymlinksInScope which is an extension of filepath.EvalSymlinks +Package symlink implements EvalSymlinksInScope which is an extension of filepath.EvalSymlinks, +as well as a Windows long-path aware version of filepath.EvalSymlinks from the [Go standard library](https://golang.org/pkg/path/filepath). The code from filepath.EvalSymlinks has been adapted in fs.go. diff --git a/vendor/github.com/docker/docker/pkg/symlink/fs.go b/vendor/github.com/docker/docker/pkg/symlink/fs.go index b4bdff24dd39..dcf707f426ce 100644 --- a/vendor/github.com/docker/docker/pkg/symlink/fs.go +++ b/vendor/github.com/docker/docker/pkg/symlink/fs.go @@ -12,15 +12,18 @@ import ( "os" "path/filepath" "strings" + + "github.com/docker/docker/pkg/system" ) -// FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an absolute path +// FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an +// absolute path. This function handles paths in a platform-agnostic manner. func FollowSymlinkInScope(path, root string) (string, error) { - path, err := filepath.Abs(path) + path, err := filepath.Abs(filepath.FromSlash(path)) if err != nil { return "", err } - root, err = filepath.Abs(root) + root, err = filepath.Abs(filepath.FromSlash(root)) if err != nil { return "", err } @@ -119,7 +122,7 @@ func evalSymlinksInScope(path, root string) (string, error) { if err != nil { return "", err } - if filepath.IsAbs(dest) { + if system.IsAbs(dest) { b.Reset() } path = dest + string(filepath.Separator) + path @@ -129,3 +132,12 @@ func evalSymlinksInScope(path, root string) (string, error) { // what's happening here return filepath.Clean(root + filepath.Clean(string(filepath.Separator)+b.String())), nil } + +// EvalSymlinks returns the path name after the evaluation of any symbolic +// links. +// If path is relative the result will be relative to the current directory, +// unless one of the components is an absolute symbolic link. +// This version has been updated to support long paths prepended with `\\?\`. +func EvalSymlinks(path string) (string, error) { + return evalSymlinks(path) +} diff --git a/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go b/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go new file mode 100644 index 000000000000..818004f26c04 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go @@ -0,0 +1,11 @@ +// +build !windows + +package symlink + +import ( + "path/filepath" +) + +func evalSymlinks(path string) (string, error) { + return filepath.EvalSymlinks(path) +} diff --git a/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go b/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go new file mode 100644 index 000000000000..449fe564832f --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go @@ -0,0 +1,155 @@ +package symlink + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "syscall" + + "github.com/docker/docker/pkg/longpath" +) + +func toShort(path string) (string, error) { + p, err := syscall.UTF16FromString(path) + if err != nil { + return "", err + } + b := p // GetShortPathName says we can reuse buffer + n, err := syscall.GetShortPathName(&p[0], &b[0], uint32(len(b))) + if err != nil { + return "", err + } + if n > uint32(len(b)) { + b = make([]uint16, n) + if _, err = syscall.GetShortPathName(&p[0], &b[0], uint32(len(b))); err != nil { + return "", err + } + } + return syscall.UTF16ToString(b), nil +} + +func toLong(path string) (string, error) { + p, err := syscall.UTF16FromString(path) + if err != nil { + return "", err + } + b := p // GetLongPathName says we can reuse buffer + n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) + if err != nil { + return "", err + } + if n > uint32(len(b)) { + b = make([]uint16, n) + n, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) + if err != nil { + return "", err + } + } + b = b[:n] + return syscall.UTF16ToString(b), nil +} + +func evalSymlinks(path string) (string, error) { + path, err := walkSymlinks(path) + if err != nil { + return "", err + } + + p, err := toShort(path) + if err != nil { + return "", err + } + p, err = toLong(p) + if err != nil { + return "", err + } + // syscall.GetLongPathName does not change the case of the drive letter, + // but the result of EvalSymlinks must be unique, so we have + // EvalSymlinks(`c:\a`) == EvalSymlinks(`C:\a`). + // Make drive letter upper case. + if len(p) >= 2 && p[1] == ':' && 'a' <= p[0] && p[0] <= 'z' { + p = string(p[0]+'A'-'a') + p[1:] + } else if len(p) >= 6 && p[5] == ':' && 'a' <= p[4] && p[4] <= 'z' { + p = p[:3] + string(p[4]+'A'-'a') + p[5:] + } + return filepath.Clean(p), nil +} + +const utf8RuneSelf = 0x80 + +func walkSymlinks(path string) (string, error) { + const maxIter = 255 + originalPath := path + // consume path by taking each frontmost path element, + // expanding it if it's a symlink, and appending it to b + var b bytes.Buffer + for n := 0; path != ""; n++ { + if n > maxIter { + return "", errors.New("EvalSymlinks: too many links in " + originalPath) + } + + // A path beginning with `\\?\` represents the root, so automatically + // skip that part and begin processing the next segment. + if strings.HasPrefix(path, longpath.Prefix) { + b.WriteString(longpath.Prefix) + path = path[4:] + continue + } + + // find next path component, p + var i = -1 + for j, c := range path { + if c < utf8RuneSelf && os.IsPathSeparator(uint8(c)) { + i = j + break + } + } + var p string + if i == -1 { + p, path = path, "" + } else { + p, path = path[:i], path[i+1:] + } + + if p == "" { + if b.Len() == 0 { + // must be absolute path + b.WriteRune(filepath.Separator) + } + continue + } + + // If this is the first segment after the long path prefix, accept the + // current segment as a volume root or UNC share and move on to the next. + if b.String() == longpath.Prefix { + b.WriteString(p) + b.WriteRune(filepath.Separator) + continue + } + + fi, err := os.Lstat(b.String() + p) + if err != nil { + return "", err + } + if fi.Mode()&os.ModeSymlink == 0 { + b.WriteString(p) + if path != "" || (b.Len() == 2 && len(p) == 2 && p[1] == ':') { + b.WriteRune(filepath.Separator) + } + continue + } + + // it's a symlink, put it at the front of path + dest, err := os.Readlink(b.String() + p) + if err != nil { + return "", err + } + if filepath.IsAbs(dest) || os.IsPathSeparator(dest[0]) { + b.Reset() + } + path = dest + string(filepath.Separator) + path + } + return filepath.Clean(b.String()), nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/docker/docker/pkg/system/chtimes.go new file mode 100644 index 000000000000..7637f12e1a7d --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/chtimes.go @@ -0,0 +1,52 @@ +package system + +import ( + "os" + "syscall" + "time" + "unsafe" +) + +var ( + maxTime time.Time +) + +func init() { + if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { + // This is a 64 bit timespec + // os.Chtimes limits time to the following + maxTime = time.Unix(0, 1<<63-1) + } else { + // This is a 32 bit timespec + maxTime = time.Unix(1<<31-1, 0) + } +} + +// Chtimes changes the access time and modified time of a file at the given path +func Chtimes(name string, atime time.Time, mtime time.Time) error { + unixMinTime := time.Unix(0, 0) + unixMaxTime := maxTime + + // If the modified time is prior to the Unix Epoch, or after the + // end of Unix Time, os.Chtimes has undefined behavior + // default to Unix Epoch in this case, just in case + + if atime.Before(unixMinTime) || atime.After(unixMaxTime) { + atime = unixMinTime + } + + if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { + mtime = unixMinTime + } + + if err := os.Chtimes(name, atime, mtime); err != nil { + return err + } + + // Take platform specific action for setting create time. + if err := setCTime(name, mtime); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go b/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go new file mode 100644 index 000000000000..09d58bcbfdd4 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go @@ -0,0 +1,14 @@ +// +build !windows + +package system + +import ( + "time" +) + +//setCTime will set the create time on a file. On Unix, the create +//time is updated as a side effect of setting the modified time, so +//no action is required. +func setCTime(path string, ctime time.Time) error { + return nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go new file mode 100644 index 000000000000..29458684659b --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go @@ -0,0 +1,27 @@ +// +build windows + +package system + +import ( + "syscall" + "time" +) + +//setCTime will set the create time on a file. On Windows, this requires +//calling SetFileTime and explicitly including the create time. +func setCTime(path string, ctime time.Time) error { + ctimespec := syscall.NsecToTimespec(ctime.UnixNano()) + pathp, e := syscall.UTF16PtrFromString(path) + if e != nil { + return e + } + h, e := syscall.CreateFile(pathp, + syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil, + syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) + if e != nil { + return e + } + defer syscall.Close(h) + c := syscall.NsecToFiletime(syscall.TimespecToNsec(ctimespec)) + return syscall.SetFileTime(h, &c, nil, nil) +} diff --git a/vendor/github.com/docker/docker/pkg/system/errors.go b/vendor/github.com/docker/docker/pkg/system/errors.go new file mode 100644 index 000000000000..288318985e3e --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/errors.go @@ -0,0 +1,10 @@ +package system + +import ( + "errors" +) + +var ( + // ErrNotSupportedPlatform means the platform is not supported. + ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") +) diff --git a/vendor/github.com/docker/docker/pkg/system/events_windows.go b/vendor/github.com/docker/docker/pkg/system/events_windows.go new file mode 100644 index 000000000000..04e2de78714f --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/events_windows.go @@ -0,0 +1,83 @@ +package system + +// This file implements syscalls for Win32 events which are not implemented +// in golang. + +import ( + "syscall" + "unsafe" +) + +var ( + procCreateEvent = modkernel32.NewProc("CreateEventW") + procOpenEvent = modkernel32.NewProc("OpenEventW") + procSetEvent = modkernel32.NewProc("SetEvent") + procResetEvent = modkernel32.NewProc("ResetEvent") + procPulseEvent = modkernel32.NewProc("PulseEvent") +) + +// CreateEvent implements win32 CreateEventW func in golang. It will create an event object. +func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) { + namep, _ := syscall.UTF16PtrFromString(name) + var _p1 uint32 + if manualReset { + _p1 = 1 + } + var _p2 uint32 + if initialState { + _p2 = 1 + } + r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) + use(unsafe.Pointer(namep)) + handle = syscall.Handle(r0) + if handle == syscall.InvalidHandle { + err = e1 + } + return +} + +// OpenEvent implements win32 OpenEventW func in golang. It opens an event object. +func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) { + namep, _ := syscall.UTF16PtrFromString(name) + var _p1 uint32 + if inheritHandle { + _p1 = 1 + } + r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) + use(unsafe.Pointer(namep)) + handle = syscall.Handle(r0) + if handle == syscall.InvalidHandle { + err = e1 + } + return +} + +// SetEvent implements win32 SetEvent func in golang. +func SetEvent(handle syscall.Handle) (err error) { + return setResetPulse(handle, procSetEvent) +} + +// ResetEvent implements win32 ResetEvent func in golang. +func ResetEvent(handle syscall.Handle) (err error) { + return setResetPulse(handle, procResetEvent) +} + +// PulseEvent implements win32 PulseEvent func in golang. +func PulseEvent(handle syscall.Handle) (err error) { + return setResetPulse(handle, procPulseEvent) +} + +func setResetPulse(handle syscall.Handle, proc *syscall.LazyProc) (err error) { + r0, _, _ := proc.Call(uintptr(handle)) + if r0 != 0 { + err = syscall.Errno(r0) + } + return +} + +var temp unsafe.Pointer + +// use ensures a variable is kept alive without the GC freeing while still needed +func use(p unsafe.Pointer) { + temp = p +} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys.go b/vendor/github.com/docker/docker/pkg/system/filesys.go new file mode 100644 index 000000000000..c14feb849659 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/filesys.go @@ -0,0 +1,19 @@ +// +build !windows + +package system + +import ( + "os" + "path/filepath" +) + +// MkdirAll creates a directory named path along with any necessary parents, +// with permission specified by attribute perm for all dir created. +func MkdirAll(path string, perm os.FileMode) error { + return os.MkdirAll(path, perm) +} + +// IsAbs is a platform-specific wrapper for filepath.IsAbs. +func IsAbs(path string) bool { + return filepath.IsAbs(path) +} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go new file mode 100644 index 000000000000..16823d5517ce --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go @@ -0,0 +1,82 @@ +// +build windows + +package system + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "syscall" +) + +// MkdirAll implementation that is volume path aware for Windows. +func MkdirAll(path string, perm os.FileMode) error { + if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { + return nil + } + + // The rest of this method is copied from os.MkdirAll and should be kept + // as-is to ensure compatibility. + + // Fast path: if we can tell whether path is a directory or file, stop with success or error. + dir, err := os.Stat(path) + if err == nil { + if dir.IsDir() { + return nil + } + return &os.PathError{ + Op: "mkdir", + Path: path, + Err: syscall.ENOTDIR, + } + } + + // Slow path: make sure parent exists and then call Mkdir for path. + i := len(path) + for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. + i-- + } + + j := i + for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. + j-- + } + + if j > 1 { + // Create parent + err = MkdirAll(path[0:j-1], perm) + if err != nil { + return err + } + } + + // Parent now exists; invoke Mkdir and use its result. + err = os.Mkdir(path, perm) + if err != nil { + // Handle arguments like "foo/." by + // double-checking that directory doesn't exist. + dir, err1 := os.Lstat(path) + if err1 == nil && dir.IsDir() { + return nil + } + return err + } + return nil +} + +// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, +// golang filepath.IsAbs does not consider a path \windows\system32 as absolute +// as it doesn't start with a drive-letter/colon combination. However, in +// docker we need to verify things such as WORKDIR /windows/system32 in +// a Dockerfile (which gets translated to \windows\system32 when being processed +// by the daemon. This SHOULD be treated as absolute from a docker processing +// perspective. +func IsAbs(path string) bool { + if !filepath.IsAbs(path) { + if !strings.HasPrefix(path, string(os.PathSeparator)) { + return false + } + } + return true +} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat.go b/vendor/github.com/docker/docker/pkg/system/lstat.go new file mode 100644 index 000000000000..bd23c4d50b21 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/lstat.go @@ -0,0 +1,19 @@ +// +build !windows + +package system + +import ( + "syscall" +) + +// Lstat takes a path to a file and returns +// a system.StatT type pertaining to that file. +// +// Throws an error if the file does not exist +func Lstat(path string) (*StatT, error) { + s := &syscall.Stat_t{} + if err := syscall.Lstat(path, s); err != nil { + return nil, err + } + return fromStatT(s) +} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go b/vendor/github.com/docker/docker/pkg/system/lstat_windows.go new file mode 100644 index 000000000000..49e87eb40bae --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/lstat_windows.go @@ -0,0 +1,25 @@ +// +build windows + +package system + +import ( + "os" +) + +// Lstat calls os.Lstat to get a fileinfo interface back. +// This is then copied into our own locally defined structure. +// Note the Linux version uses fromStatT to do the copy back, +// but that not strictly necessary when already in an OS specific module. +func Lstat(path string) (*StatT, error) { + fi, err := os.Lstat(path) + if err != nil { + return nil, err + } + + return &StatT{ + name: fi.Name(), + size: fi.Size(), + mode: fi.Mode(), + modTime: fi.ModTime(), + isDir: fi.IsDir()}, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo.go b/vendor/github.com/docker/docker/pkg/system/meminfo.go new file mode 100644 index 000000000000..3b6e947e6753 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/meminfo.go @@ -0,0 +1,17 @@ +package system + +// MemInfo contains memory statistics of the host system. +type MemInfo struct { + // Total usable RAM (i.e. physical RAM minus a few reserved bits and the + // kernel binary code). + MemTotal int64 + + // Amount of free memory. + MemFree int64 + + // Total amount of swap space available. + SwapTotal int64 + + // Amount of swap space that is currently unused. + SwapFree int64 +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go new file mode 100644 index 000000000000..385f1d5e735a --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go @@ -0,0 +1,65 @@ +package system + +import ( + "bufio" + "io" + "os" + "strconv" + "strings" + + "github.com/docker/go-units" +) + +// ReadMemInfo retrieves memory statistics of the host system and returns a +// MemInfo type. +func ReadMemInfo() (*MemInfo, error) { + file, err := os.Open("/proc/meminfo") + if err != nil { + return nil, err + } + defer file.Close() + return parseMemInfo(file) +} + +// parseMemInfo parses the /proc/meminfo file into +// a MemInfo object given an io.Reader to the file. +// Throws error if there are problems reading from the file +func parseMemInfo(reader io.Reader) (*MemInfo, error) { + meminfo := &MemInfo{} + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + // Expected format: ["MemTotal:", "1234", "kB"] + parts := strings.Fields(scanner.Text()) + + // Sanity checks: Skip malformed entries. + if len(parts) < 3 || parts[2] != "kB" { + continue + } + + // Convert to bytes. + size, err := strconv.Atoi(parts[1]) + if err != nil { + continue + } + bytes := int64(size) * units.KiB + + switch parts[0] { + case "MemTotal:": + meminfo.MemTotal = bytes + case "MemFree:": + meminfo.MemFree = bytes + case "SwapTotal:": + meminfo.SwapTotal = bytes + case "SwapFree:": + meminfo.SwapFree = bytes + } + + } + + // Handle errors that may have occurred during the reading of the file. + if err := scanner.Err(); err != nil { + return nil, err + } + + return meminfo, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go new file mode 100644 index 000000000000..82ddd30c1b06 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go @@ -0,0 +1,8 @@ +// +build !linux,!windows + +package system + +// ReadMemInfo is not supported on platforms other than linux and windows. +func ReadMemInfo() (*MemInfo, error) { + return nil, ErrNotSupportedPlatform +} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go new file mode 100644 index 000000000000..d46642598cf6 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go @@ -0,0 +1,44 @@ +package system + +import ( + "syscall" + "unsafe" +) + +var ( + modkernel32 = syscall.NewLazyDLL("kernel32.dll") + + procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") +) + +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx +type memorystatusex struct { + dwLength uint32 + dwMemoryLoad uint32 + ullTotalPhys uint64 + ullAvailPhys uint64 + ullTotalPageFile uint64 + ullAvailPageFile uint64 + ullTotalVirtual uint64 + ullAvailVirtual uint64 + ullAvailExtendedVirtual uint64 +} + +// ReadMemInfo retrieves memory statistics of the host system and returns a +// MemInfo type. +func ReadMemInfo() (*MemInfo, error) { + msi := &memorystatusex{ + dwLength: 64, + } + r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) + if r1 == 0 { + return &MemInfo{}, nil + } + return &MemInfo{ + MemTotal: int64(msi.ullTotalPhys), + MemFree: int64(msi.ullAvailPhys), + SwapTotal: int64(msi.ullTotalPageFile), + SwapFree: int64(msi.ullAvailPageFile), + }, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod.go b/vendor/github.com/docker/docker/pkg/system/mknod.go new file mode 100644 index 000000000000..73958182b4eb --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/mknod.go @@ -0,0 +1,22 @@ +// +build !windows + +package system + +import ( + "syscall" +) + +// Mknod creates a filesystem node (file, device special file or named pipe) named path +// with attributes specified by mode and dev. +func Mknod(path string, mode uint32, dev int) error { + return syscall.Mknod(path, mode, dev) +} + +// Mkdev is used to build the value of linux devices (in /dev/) which specifies major +// and minor number of the newly created device special file. +// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. +// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, +// then the top 12 bits of the minor. +func Mkdev(major int64, minor int64) uint32 { + return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff)) +} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go b/vendor/github.com/docker/docker/pkg/system/mknod_windows.go new file mode 100644 index 000000000000..2e863c0215b3 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/mknod_windows.go @@ -0,0 +1,13 @@ +// +build windows + +package system + +// Mknod is not implemented on Windows. +func Mknod(path string, mode uint32, dev int) error { + return ErrNotSupportedPlatform +} + +// Mkdev is not implemented on Windows. +func Mkdev(major int64, minor int64) uint32 { + panic("Mkdev not implemented on Windows.") +} diff --git a/vendor/github.com/docker/docker/pkg/system/path_unix.go b/vendor/github.com/docker/docker/pkg/system/path_unix.go new file mode 100644 index 000000000000..1b6cc9cbd9f1 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/path_unix.go @@ -0,0 +1,8 @@ +// +build !windows + +package system + +// DefaultPathEnv is unix style list of directories to search for +// executables. Each directory is separated from the next by a colon +// ':' character . +const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/vendor/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/docker/docker/pkg/system/path_windows.go new file mode 100644 index 000000000000..09e7f89fed3a --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/path_windows.go @@ -0,0 +1,7 @@ +// +build windows + +package system + +// DefaultPathEnv is deliberately empty on Windows as the default path will be set by +// the container. Docker has no context of what the default path should be. +const DefaultPathEnv = "" diff --git a/vendor/github.com/docker/docker/pkg/system/stat.go b/vendor/github.com/docker/docker/pkg/system/stat.go new file mode 100644 index 000000000000..087034c5ec55 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat.go @@ -0,0 +1,53 @@ +// +build !windows + +package system + +import ( + "syscall" +) + +// StatT type contains status of a file. It contains metadata +// like permission, owner, group, size, etc about a file. +type StatT struct { + mode uint32 + uid uint32 + gid uint32 + rdev uint64 + size int64 + mtim syscall.Timespec +} + +// Mode returns file's permission mode. +func (s StatT) Mode() uint32 { + return s.mode +} + +// UID returns file's user id of owner. +func (s StatT) UID() uint32 { + return s.uid +} + +// GID returns file's group id of owner. +func (s StatT) GID() uint32 { + return s.gid +} + +// Rdev returns file's device ID (if it's special file). +func (s StatT) Rdev() uint64 { + return s.rdev +} + +// Size returns file's size. +func (s StatT) Size() int64 { + return s.size +} + +// Mtim returns file's last modification time. +func (s StatT) Mtim() syscall.Timespec { + return s.mtim +} + +// GetLastModification returns file's last modification time. +func (s StatT) GetLastModification() syscall.Timespec { + return s.Mtim() +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go b/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go new file mode 100644 index 000000000000..d0fb6f15190a --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go @@ -0,0 +1,27 @@ +package system + +import ( + "syscall" +) + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtimespec}, nil +} + +// Stat takes a path to a file and returns +// a system.Stat_t type pertaining to that file. +// +// Throws an error if the file does not exist +func Stat(path string) (*StatT, error) { + s := &syscall.Stat_t{} + if err := syscall.Stat(path, s); err != nil { + return nil, err + } + return fromStatT(s) +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_linux.go b/vendor/github.com/docker/docker/pkg/system/stat_linux.go new file mode 100644 index 000000000000..8b1eded1387a --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_linux.go @@ -0,0 +1,33 @@ +package system + +import ( + "syscall" +) + +// fromStatT converts a syscall.Stat_t type to a system.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: s.Mode, + uid: s.Uid, + gid: s.Gid, + rdev: s.Rdev, + mtim: s.Mtim}, nil +} + +// FromStatT exists only on linux, and loads a system.StatT from a +// syscal.Stat_t. +func FromStatT(s *syscall.Stat_t) (*StatT, error) { + return fromStatT(s) +} + +// Stat takes a path to a file and returns +// a system.StatT type pertaining to that file. +// +// Throws an error if the file does not exist +func Stat(path string) (*StatT, error) { + s := &syscall.Stat_t{} + if err := syscall.Stat(path, s); err != nil { + return nil, err + } + return fromStatT(s) +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go b/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go new file mode 100644 index 000000000000..3c3b71fb2196 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go @@ -0,0 +1,15 @@ +package system + +import ( + "syscall" +) + +// fromStatT creates a system.StatT type from a syscall.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtim}, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go new file mode 100644 index 000000000000..b01d08acfee5 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go @@ -0,0 +1,17 @@ +// +build solaris + +package system + +import ( + "syscall" +) + +// fromStatT creates a system.StatT type from a syscall.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtim}, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go b/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go new file mode 100644 index 000000000000..f53e9de4d1a1 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go @@ -0,0 +1,17 @@ +// +build !linux,!windows,!freebsd,!solaris,!openbsd + +package system + +import ( + "syscall" +) + +// fromStatT creates a system.StatT type from a syscall.Stat_t type +func fromStatT(s *syscall.Stat_t) (*StatT, error) { + return &StatT{size: s.Size, + mode: uint32(s.Mode), + uid: s.Uid, + gid: s.Gid, + rdev: uint64(s.Rdev), + mtim: s.Mtimespec}, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_windows.go b/vendor/github.com/docker/docker/pkg/system/stat_windows.go new file mode 100644 index 000000000000..39490c625c03 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/stat_windows.go @@ -0,0 +1,43 @@ +// +build windows + +package system + +import ( + "os" + "time" +) + +// StatT type contains status of a file. It contains metadata +// like name, permission, size, etc about a file. +type StatT struct { + name string + size int64 + mode os.FileMode + modTime time.Time + isDir bool +} + +// Name returns file's name. +func (s StatT) Name() string { + return s.name +} + +// Size returns file's size. +func (s StatT) Size() int64 { + return s.size +} + +// Mode returns file's permission mode. +func (s StatT) Mode() os.FileMode { + return s.mode +} + +// ModTime returns file's last modification time. +func (s StatT) ModTime() time.Time { + return s.modTime +} + +// IsDir returns whether file is actually a directory. +func (s StatT) IsDir() bool { + return s.isDir +} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go b/vendor/github.com/docker/docker/pkg/system/syscall_unix.go new file mode 100644 index 000000000000..3ae912846844 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/syscall_unix.go @@ -0,0 +1,17 @@ +// +build linux freebsd + +package system + +import "syscall" + +// Unmount is a platform-specific helper function to call +// the unmount syscall. +func Unmount(dest string) error { + return syscall.Unmount(dest, 0) +} + +// CommandLineToArgv should not be used on Unix. +// It simply returns commandLine in the only element in the returned array. +func CommandLineToArgv(commandLine string) ([]string, error) { + return []string{commandLine}, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go b/vendor/github.com/docker/docker/pkg/system/syscall_windows.go new file mode 100644 index 000000000000..061e220f79c0 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/syscall_windows.go @@ -0,0 +1,60 @@ +package system + +import ( + "fmt" + "syscall" + "unsafe" +) + +// OSVersion is a wrapper for Windows version information +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx +type OSVersion struct { + Version uint32 + MajorVersion uint8 + MinorVersion uint8 + Build uint16 +} + +// GetOSVersion gets the operating system version on Windows. Note that +// docker.exe must be manifested to get the correct version information. +func GetOSVersion() (OSVersion, error) { + var err error + osv := OSVersion{} + osv.Version, err = syscall.GetVersion() + if err != nil { + return osv, fmt.Errorf("Failed to call GetVersion()") + } + osv.MajorVersion = uint8(osv.Version & 0xFF) + osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) + osv.Build = uint16(osv.Version >> 16) + return osv, nil +} + +// Unmount is a platform-specific helper function to call +// the unmount syscall. Not supported on Windows +func Unmount(dest string) error { + return nil +} + +// CommandLineToArgv wraps the Windows syscall to turn a commandline into an argument array. +func CommandLineToArgv(commandLine string) ([]string, error) { + var argc int32 + + argsPtr, err := syscall.UTF16PtrFromString(commandLine) + if err != nil { + return nil, err + } + + argv, err := syscall.CommandLineToArgv(argsPtr, &argc) + if err != nil { + return nil, err + } + defer syscall.LocalFree(syscall.Handle(uintptr(unsafe.Pointer(argv)))) + + newArgs := make([]string, argc) + for i, v := range (*argv)[:argc] { + newArgs[i] = string(syscall.UTF16ToString((*v)[:])) + } + + return newArgs, nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/umask.go b/vendor/github.com/docker/docker/pkg/system/umask.go new file mode 100644 index 000000000000..c670fcd7586b --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/umask.go @@ -0,0 +1,13 @@ +// +build !windows + +package system + +import ( + "syscall" +) + +// Umask sets current process's file mode creation mask to newmask +// and return oldmask. +func Umask(newmask int) (oldmask int, err error) { + return syscall.Umask(newmask), nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/umask_windows.go b/vendor/github.com/docker/docker/pkg/system/umask_windows.go new file mode 100644 index 000000000000..13f1de1769c7 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/umask_windows.go @@ -0,0 +1,9 @@ +// +build windows + +package system + +// Umask is not supported on the windows platform. +func Umask(newmask int) (oldmask int, err error) { + // should not be called on cli code path + return 0, ErrNotSupportedPlatform +} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go b/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go new file mode 100644 index 000000000000..0a16197544db --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go @@ -0,0 +1,8 @@ +package system + +import "syscall" + +// LUtimesNano is not supported by darwin platform. +func LUtimesNano(path string, ts []syscall.Timespec) error { + return ErrNotSupportedPlatform +} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go b/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go new file mode 100644 index 000000000000..e2eac3b553e0 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go @@ -0,0 +1,22 @@ +package system + +import ( + "syscall" + "unsafe" +) + +// LUtimesNano is used to change access and modification time of the specified path. +// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. +func LUtimesNano(path string, ts []syscall.Timespec) error { + var _path *byte + _path, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS { + return err + } + + return nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_linux.go b/vendor/github.com/docker/docker/pkg/system/utimes_linux.go new file mode 100644 index 000000000000..fc8a1aba95cb --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/utimes_linux.go @@ -0,0 +1,26 @@ +package system + +import ( + "syscall" + "unsafe" +) + +// LUtimesNano is used to change access and modification time of the specified path. +// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. +func LUtimesNano(path string, ts []syscall.Timespec) error { + // These are not currently available in syscall + atFdCwd := -100 + atSymLinkNoFollow := 0x100 + + var _path *byte + _path, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + + if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(atSymLinkNoFollow), 0, 0); err != 0 && err != syscall.ENOSYS { + return err + } + + return nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go new file mode 100644 index 000000000000..50c3a04364d2 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go @@ -0,0 +1,10 @@ +// +build !linux,!freebsd,!darwin + +package system + +import "syscall" + +// LUtimesNano is not supported on platforms other than linux, freebsd and darwin. +func LUtimesNano(path string, ts []syscall.Timespec) error { + return ErrNotSupportedPlatform +} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go b/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go new file mode 100644 index 000000000000..d2e2c0579983 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go @@ -0,0 +1,63 @@ +package system + +import ( + "syscall" + "unsafe" +) + +// Lgetxattr retrieves the value of the extended attribute identified by attr +// and associated with the given path in the file system. +// It will returns a nil slice and nil error if the xattr is not set. +func Lgetxattr(path string, attr string) ([]byte, error) { + pathBytes, err := syscall.BytePtrFromString(path) + if err != nil { + return nil, err + } + attrBytes, err := syscall.BytePtrFromString(attr) + if err != nil { + return nil, err + } + + dest := make([]byte, 128) + destBytes := unsafe.Pointer(&dest[0]) + sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) + if errno == syscall.ENODATA { + return nil, nil + } + if errno == syscall.ERANGE { + dest = make([]byte, sz) + destBytes := unsafe.Pointer(&dest[0]) + sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) + } + if errno != 0 { + return nil, errno + } + + return dest[:sz], nil +} + +var _zero uintptr + +// Lsetxattr sets the value of the extended attribute identified by attr +// and associated with the given path in the file system. +func Lsetxattr(path string, attr string, data []byte, flags int) error { + pathBytes, err := syscall.BytePtrFromString(path) + if err != nil { + return err + } + attrBytes, err := syscall.BytePtrFromString(attr) + if err != nil { + return err + } + var dataBytes unsafe.Pointer + if len(data) > 0 { + dataBytes = unsafe.Pointer(&data[0]) + } else { + dataBytes = unsafe.Pointer(&_zero) + } + _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0) + if errno != 0 { + return errno + } + return nil +} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go new file mode 100644 index 000000000000..0114f2227cf0 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go @@ -0,0 +1,13 @@ +// +build !linux + +package system + +// Lgetxattr is not supported on platforms other than linux. +func Lgetxattr(path string, attr string) ([]byte, error) { + return nil, ErrNotSupportedPlatform +} + +// Lsetxattr is not supported on platforms other than linux. +func Lsetxattr(path string, attr string, data []byte, flags int) error { + return ErrNotSupportedPlatform +} diff --git a/vendor/github.com/docker/docker/pkg/term/ascii.go b/vendor/github.com/docker/docker/pkg/term/ascii.go new file mode 100644 index 000000000000..f5262bccf5f3 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/ascii.go @@ -0,0 +1,66 @@ +package term + +import ( + "fmt" + "strings" +) + +// ASCII list the possible supported ASCII key sequence +var ASCII = []string{ + "ctrl-@", + "ctrl-a", + "ctrl-b", + "ctrl-c", + "ctrl-d", + "ctrl-e", + "ctrl-f", + "ctrl-g", + "ctrl-h", + "ctrl-i", + "ctrl-j", + "ctrl-k", + "ctrl-l", + "ctrl-m", + "ctrl-n", + "ctrl-o", + "ctrl-p", + "ctrl-q", + "ctrl-r", + "ctrl-s", + "ctrl-t", + "ctrl-u", + "ctrl-v", + "ctrl-w", + "ctrl-x", + "ctrl-y", + "ctrl-z", + "ctrl-[", + "ctrl-\\", + "ctrl-]", + "ctrl-^", + "ctrl-_", +} + +// ToBytes converts a string representing a suite of key-sequence to the corresponding ASCII code. +func ToBytes(keys string) ([]byte, error) { + codes := []byte{} +next: + for _, key := range strings.Split(keys, ",") { + if len(key) != 1 { + for code, ctrl := range ASCII { + if ctrl == key { + codes = append(codes, byte(code)) + continue next + } + } + if key == "DEL" { + codes = append(codes, 127) + } else { + return nil, fmt.Errorf("Unknown character: '%s'", key) + } + } else { + codes = append(codes, byte(key[0])) + } + } + return codes, nil +} diff --git a/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go b/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go index d47cf59b8dff..a22cd9d1056f 100644 --- a/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go +++ b/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go @@ -10,6 +10,9 @@ import ( // #include import "C" +// Termios is the Unix API for terminal I/O. +// It is passthgrouh for syscall.Termios in order to make it portable with +// other platforms where it is not available or handled differently. type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw @@ -24,7 +27,6 @@ func MakeRaw(fd uintptr) (*State, error) { newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) - newState.Oflag = newState.Oflag | C.OPOST if err := tcset(fd, &newState); err != 0 { return nil, err } diff --git a/vendor/github.com/docker/docker/pkg/term/term.go b/vendor/github.com/docker/docker/pkg/term/term.go index b945a3dcea9f..11ed20937bce 100644 --- a/vendor/github.com/docker/docker/pkg/term/term.go +++ b/vendor/github.com/docker/docker/pkg/term/term.go @@ -1,5 +1,7 @@ // +build !windows +// Package term provides provides structures and helper functions to work with +// terminal (state, sizes). package term import ( @@ -12,13 +14,16 @@ import ( ) var ( + // ErrInvalidState is returned if the state of the terminal is invalid. ErrInvalidState = errors.New("Invalid terminal state") ) +// State represents the state of the terminal. type State struct { termios Termios } +// Winsize represents the size of the terminal window. type Winsize struct { Height uint16 Width uint16 @@ -26,10 +31,12 @@ type Winsize struct { y uint16 } +// StdStreams returns the standard streams (stdin, stdout, stedrr). func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { return os.Stdin, os.Stdout, os.Stderr } +// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. func GetFdInfo(in interface{}) (uintptr, bool) { var inFd uintptr var isTerminalIn bool @@ -40,19 +47,21 @@ func GetFdInfo(in interface{}) (uintptr, bool) { return inFd, isTerminalIn } +// GetWinsize returns the window size based on the specified file descriptor. func GetWinsize(fd uintptr) (*Winsize, error) { ws := &Winsize{} _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws))) - // Skipp errno = 0 + // Skip errno = 0 if err == 0 { return ws, nil } return ws, err } +// SetWinsize tries to set the specified window size for the specified file descriptor. func SetWinsize(fd uintptr, ws *Winsize) error { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws))) - // Skipp errno = 0 + // Skip errno = 0 if err == 0 { return nil } @@ -65,8 +74,8 @@ func IsTerminal(fd uintptr) bool { return tcget(fd, &termios) == 0 } -// Restore restores the terminal connected to the given file descriptor to a -// previous state. +// RestoreTerminal restores the terminal connected to the given file descriptor +// to a previous state. func RestoreTerminal(fd uintptr, state *State) error { if state == nil { return ErrInvalidState @@ -77,6 +86,7 @@ func RestoreTerminal(fd uintptr, state *State) error { return nil } +// SaveState saves the state of the terminal connected to the given file descriptor. func SaveState(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { @@ -86,6 +96,8 @@ func SaveState(fd uintptr) (*State, error) { return &oldState, nil } +// DisableEcho applies the specified state to the terminal connected to the file +// descriptor, with echo disabled. func DisableEcho(fd uintptr, state *State) error { newState := state.termios newState.Lflag &^= syscall.ECHO @@ -97,6 +109,8 @@ func DisableEcho(fd uintptr, state *State) error { return nil } +// SetRawTerminal puts the terminal connected to the given file descriptor into +// raw mode and returns the previous state. func SetRawTerminal(fd uintptr) (*State, error) { oldState, err := MakeRaw(fd) if err != nil { @@ -113,6 +127,5 @@ func handleInterrupt(fd uintptr, state *State) { go func() { _ = <-sigchan RestoreTerminal(fd, state) - os.Exit(0) }() } diff --git a/vendor/github.com/docker/docker/pkg/term/term_windows.go b/vendor/github.com/docker/docker/pkg/term/term_windows.go index f7fa1b3a276b..3101c80c8225 100644 --- a/vendor/github.com/docker/docker/pkg/term/term_windows.go +++ b/vendor/github.com/docker/docker/pkg/term/term_windows.go @@ -5,14 +5,18 @@ package term import ( "io" "os" + "os/signal" + "syscall" - "github.com/Sirupsen/logrus" - "github.com/docker/docker/pkg/term/winconsole" + "github.com/Azure/go-ansiterm/winterm" + "github.com/docker/docker/pkg/system" + "github.com/docker/docker/pkg/term/windows" ) // State holds the console mode for the terminal. type State struct { - mode uint32 + inMode, outMode uint32 + inHandle, outHandle syscall.Handle } // Winsize is used for window size. @@ -23,117 +27,279 @@ type Winsize struct { y uint16 } +const ( + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx + enableVirtualTerminalInput = 0x0200 + enableVirtualTerminalProcessing = 0x0004 +) + +// usingNativeConsole is true if we are using the Windows native console +var usingNativeConsole bool + +// StdStreams returns the standard streams (stdin, stdout, stedrr). func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { switch { case os.Getenv("ConEmuANSI") == "ON": - // The ConEmu shell emulates ANSI well by default. - return os.Stdin, os.Stdout, os.Stderr + // The ConEmu terminal emulates ANSI on output streams well. + return windows.ConEmuStreams() case os.Getenv("MSYSTEM") != "": // MSYS (mingw) does not emulate ANSI well. - return winconsole.WinConsoleStreams() + return windows.ConsoleStreams() default: - return winconsole.WinConsoleStreams() + if useNativeConsole() { + usingNativeConsole = true + return os.Stdin, os.Stdout, os.Stderr + } + return windows.ConsoleStreams() + } +} + +// useNativeConsole determines if the docker client should use the built-in +// console which supports ANSI emulation, or fall-back to the golang emulator +// (github.com/azure/go-ansiterm). +func useNativeConsole() bool { + osv, err := system.GetOSVersion() + if err != nil { + return false + } + + // Native console is not available before major version 10 + if osv.MajorVersion < 10 { + return false + } + + // Must have a late pre-release TP4 build of Windows Server 2016/Windows 10 TH2 or later + if osv.Build < 10578 { + return false + } + + // Get the console modes. If this fails, we can't use the native console + state, err := getNativeConsole() + if err != nil { + return false + } + + // Probe the console to see if it can be enabled. + if nil != probeNativeConsole(state) { + return false + } + + // Environment variable override + if e := os.Getenv("USE_NATIVE_CONSOLE"); e != "" { + if e == "1" { + return true + } + return false + } + + // TODO Windows. The native emulator still has issues which + // mean it shouldn't be enabled for everyone. Change this next line to true + // to change the default to "enable if available". In the meantime, users + // can still try it out by using USE_NATIVE_CONSOLE env variable. + return false +} + +// getNativeConsole returns the console modes ('state') for the native Windows console +func getNativeConsole() (State, error) { + var ( + err error + state State + ) + + // Get the handle to stdout + if state.outHandle, err = syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE); err != nil { + return state, err + } + + // Get the console mode from the consoles stdout handle + if err = syscall.GetConsoleMode(state.outHandle, &state.outMode); err != nil { + return state, err + } + + // Get the handle to stdin + if state.inHandle, err = syscall.GetStdHandle(syscall.STD_INPUT_HANDLE); err != nil { + return state, err + } + + // Get the console mode from the consoles stdin handle + if err = syscall.GetConsoleMode(state.inHandle, &state.inMode); err != nil { + return state, err + } + + return state, nil +} + +// probeNativeConsole probes the console to determine if native can be supported, +func probeNativeConsole(state State) error { + if err := winterm.SetConsoleMode(uintptr(state.outHandle), state.outMode|enableVirtualTerminalProcessing); err != nil { + return err + } + defer winterm.SetConsoleMode(uintptr(state.outHandle), state.outMode) + + if err := winterm.SetConsoleMode(uintptr(state.inHandle), state.inMode|enableVirtualTerminalInput); err != nil { + return err } + defer winterm.SetConsoleMode(uintptr(state.inHandle), state.inMode) + + return nil +} + +// enableNativeConsole turns on native console mode +func enableNativeConsole(state State) error { + if err := winterm.SetConsoleMode(uintptr(state.outHandle), state.outMode|enableVirtualTerminalProcessing); err != nil { + return err + } + + if err := winterm.SetConsoleMode(uintptr(state.inHandle), state.inMode|enableVirtualTerminalInput); err != nil { + winterm.SetConsoleMode(uintptr(state.outHandle), state.outMode) // restore out if we can + return err + } + + return nil +} + +// disableNativeConsole turns off native console mode +func disableNativeConsole(state *State) error { + // Try and restore both in an out before error checking. + errout := winterm.SetConsoleMode(uintptr(state.outHandle), state.outMode) + errin := winterm.SetConsoleMode(uintptr(state.inHandle), state.inMode) + if errout != nil { + return errout + } + if errin != nil { + return errin + } + return nil } -// GetFdInfo returns file descriptor and bool indicating whether the file is a terminal. +// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. func GetFdInfo(in interface{}) (uintptr, bool) { - return winconsole.GetHandleInfo(in) + return windows.GetHandleInfo(in) } -// GetWinsize retrieves the window size of the terminal connected to the passed file descriptor. +// GetWinsize returns the window size based on the specified file descriptor. func GetWinsize(fd uintptr) (*Winsize, error) { - info, err := winconsole.GetConsoleScreenBufferInfo(fd) + info, err := winterm.GetConsoleScreenBufferInfo(fd) if err != nil { return nil, err } - // TODO(azlinux): Set the pixel width / height of the console (currently unused by any caller) - return &Winsize{ + winsize := &Winsize{ Width: uint16(info.Window.Right - info.Window.Left + 1), Height: uint16(info.Window.Bottom - info.Window.Top + 1), x: 0, - y: 0}, nil -} + y: 0} -// SetWinsize sets the size of the given terminal connected to the passed file descriptor. -func SetWinsize(fd uintptr, ws *Winsize) error { - // TODO(azlinux): Implement SetWinsize - logrus.Debugf("[windows] SetWinsize: WARNING -- Unsupported method invoked") - return nil + return winsize, nil } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { - return winconsole.IsConsole(fd) + return windows.IsConsole(fd) } -// RestoreTerminal restores the terminal connected to the given file descriptor to a -// previous state. +// RestoreTerminal restores the terminal connected to the given file descriptor +// to a previous state. func RestoreTerminal(fd uintptr, state *State) error { - return winconsole.SetConsoleMode(fd, state.mode) + if usingNativeConsole { + return disableNativeConsole(state) + } + return winterm.SetConsoleMode(fd, state.outMode) } // SaveState saves the state of the terminal connected to the given file descriptor. func SaveState(fd uintptr) (*State, error) { - mode, e := winconsole.GetConsoleMode(fd) + if usingNativeConsole { + state, err := getNativeConsole() + if err != nil { + return nil, err + } + return &state, nil + } + + mode, e := winterm.GetConsoleMode(fd) if e != nil { return nil, e } - return &State{mode}, nil + + return &State{outMode: mode}, nil } // DisableEcho disables echo for the terminal connected to the given file descriptor. -// -- See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx +// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx func DisableEcho(fd uintptr, state *State) error { - mode := state.mode - mode &^= winconsole.ENABLE_ECHO_INPUT - mode |= winconsole.ENABLE_PROCESSED_INPUT | winconsole.ENABLE_LINE_INPUT - // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. - return winconsole.SetConsoleMode(fd, mode) + mode := state.inMode + mode &^= winterm.ENABLE_ECHO_INPUT + mode |= winterm.ENABLE_PROCESSED_INPUT | winterm.ENABLE_LINE_INPUT + err := winterm.SetConsoleMode(fd, mode) + if err != nil { + return err + } + + // Register an interrupt handler to catch and restore prior state + restoreAtInterrupt(fd, state) + return nil } // SetRawTerminal puts the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. +// mode and returns the previous state. func SetRawTerminal(fd uintptr) (*State, error) { state, err := MakeRaw(fd) if err != nil { return nil, err } - // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. + + // Register an interrupt handler to catch and restore prior state + restoreAtInterrupt(fd, state) return state, err } -// MakeRaw puts the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. +// MakeRaw puts the terminal (Windows Console) connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be restored. func MakeRaw(fd uintptr) (*State, error) { state, err := SaveState(fd) if err != nil { return nil, err } + mode := state.inMode + if usingNativeConsole { + if err := enableNativeConsole(*state); err != nil { + return nil, err + } + mode |= enableVirtualTerminalInput + } + // See // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx - mode := state.mode // Disable these modes - mode &^= winconsole.ENABLE_ECHO_INPUT - mode &^= winconsole.ENABLE_LINE_INPUT - mode &^= winconsole.ENABLE_MOUSE_INPUT - mode &^= winconsole.ENABLE_WINDOW_INPUT - mode &^= winconsole.ENABLE_PROCESSED_INPUT + mode &^= winterm.ENABLE_ECHO_INPUT + mode &^= winterm.ENABLE_LINE_INPUT + mode &^= winterm.ENABLE_MOUSE_INPUT + mode &^= winterm.ENABLE_WINDOW_INPUT + mode &^= winterm.ENABLE_PROCESSED_INPUT // Enable these modes - mode |= winconsole.ENABLE_EXTENDED_FLAGS - mode |= winconsole.ENABLE_INSERT_MODE - mode |= winconsole.ENABLE_QUICK_EDIT_MODE + mode |= winterm.ENABLE_EXTENDED_FLAGS + mode |= winterm.ENABLE_INSERT_MODE + mode |= winterm.ENABLE_QUICK_EDIT_MODE - err = winconsole.SetConsoleMode(fd, mode) + err = winterm.SetConsoleMode(fd, mode) if err != nil { return nil, err } return state, nil } + +func restoreAtInterrupt(fd uintptr, state *State) { + sigchan := make(chan os.Signal, 1) + signal.Notify(sigchan, os.Interrupt) + + go func() { + _ = <-sigchan + RestoreTerminal(fd, state) + os.Exit(0) + }() +} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_darwin.go b/vendor/github.com/docker/docker/pkg/term/termios_darwin.go index 11cd70d10b84..480db900ac92 100644 --- a/vendor/github.com/docker/docker/pkg/term/termios_darwin.go +++ b/vendor/github.com/docker/docker/pkg/term/termios_darwin.go @@ -8,7 +8,10 @@ import ( const ( getTermios = syscall.TIOCGETA setTermios = syscall.TIOCSETA +) +// Termios magic numbers, passthrough to the ones defined in syscall. +const ( IGNBRK = syscall.IGNBRK PARMRK = syscall.PARMRK INLCR = syscall.INLCR @@ -29,6 +32,7 @@ const ( IEXTEN = syscall.IEXTEN ) +// Termios is the Unix API for terminal I/O. type Termios struct { Iflag uint64 Oflag uint64 diff --git a/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go b/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go index ed3659572cc1..ed843ad69c94 100644 --- a/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go +++ b/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go @@ -8,7 +8,10 @@ import ( const ( getTermios = syscall.TIOCGETA setTermios = syscall.TIOCSETA +) +// Termios magic numbers, passthrough to the ones defined in syscall. +const ( IGNBRK = syscall.IGNBRK PARMRK = syscall.PARMRK INLCR = syscall.INLCR @@ -29,6 +32,7 @@ const ( IEXTEN = syscall.IEXTEN ) +// Termios is the Unix API for terminal I/O. type Termios struct { Iflag uint32 Oflag uint32 diff --git a/vendor/github.com/docker/docker/pkg/term/termios_linux.go b/vendor/github.com/docker/docker/pkg/term/termios_linux.go index 024187ff0664..22921b6aef38 100644 --- a/vendor/github.com/docker/docker/pkg/term/termios_linux.go +++ b/vendor/github.com/docker/docker/pkg/term/termios_linux.go @@ -12,6 +12,7 @@ const ( setTermios = syscall.TCSETS ) +// Termios is the Unix API for terminal I/O. type Termios struct { Iflag uint32 Oflag uint32 diff --git a/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go b/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go new file mode 100644 index 000000000000..ed843ad69c94 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go @@ -0,0 +1,69 @@ +package term + +import ( + "syscall" + "unsafe" +) + +const ( + getTermios = syscall.TIOCGETA + setTermios = syscall.TIOCSETA +) + +// Termios magic numbers, passthrough to the ones defined in syscall. +const ( + IGNBRK = syscall.IGNBRK + PARMRK = syscall.PARMRK + INLCR = syscall.INLCR + IGNCR = syscall.IGNCR + ECHONL = syscall.ECHONL + CSIZE = syscall.CSIZE + ICRNL = syscall.ICRNL + ISTRIP = syscall.ISTRIP + PARENB = syscall.PARENB + ECHO = syscall.ECHO + ICANON = syscall.ICANON + ISIG = syscall.ISIG + IXON = syscall.IXON + BRKINT = syscall.BRKINT + INPCK = syscall.INPCK + OPOST = syscall.OPOST + CS8 = syscall.CS8 + IEXTEN = syscall.IEXTEN +) + +// Termios is the Unix API for terminal I/O. +type Termios struct { + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [20]byte + Ispeed uint32 + Ospeed uint32 +} + +// MakeRaw put the terminal connected to the given file descriptor into raw +// mode and returns the previous state of the terminal so that it can be +// restored. +func MakeRaw(fd uintptr) (*State, error) { + var oldState State + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { + return nil, err + } + + newState := oldState.termios + newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) + newState.Oflag &^= OPOST + newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) + newState.Cflag &^= (CSIZE | PARENB) + newState.Cflag |= CS8 + newState.Cc[syscall.VMIN] = 1 + newState.Cc[syscall.VTIME] = 0 + + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { + return nil, err + } + + return &oldState, nil +} diff --git a/vendor/github.com/docker/docker/pkg/term/winconsole/console_windows.go b/vendor/github.com/docker/docker/pkg/term/winconsole/console_windows.go deleted file mode 100644 index ce40a93167f9..000000000000 --- a/vendor/github.com/docker/docker/pkg/term/winconsole/console_windows.go +++ /dev/null @@ -1,1053 +0,0 @@ -// +build windows - -package winconsole - -import ( - "bytes" - "fmt" - "io" - "os" - "strconv" - "strings" - "sync" - "syscall" - "unsafe" - - "github.com/Sirupsen/logrus" -) - -const ( - // Consts for Get/SetConsoleMode function - // -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx - ENABLE_PROCESSED_INPUT = 0x0001 - ENABLE_LINE_INPUT = 0x0002 - ENABLE_ECHO_INPUT = 0x0004 - ENABLE_WINDOW_INPUT = 0x0008 - ENABLE_MOUSE_INPUT = 0x0010 - ENABLE_INSERT_MODE = 0x0020 - ENABLE_QUICK_EDIT_MODE = 0x0040 - ENABLE_EXTENDED_FLAGS = 0x0080 - - // If parameter is a screen buffer handle, additional values - ENABLE_PROCESSED_OUTPUT = 0x0001 - ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 - - //http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes - FOREGROUND_BLUE = 1 - FOREGROUND_GREEN = 2 - FOREGROUND_RED = 4 - FOREGROUND_INTENSITY = 8 - FOREGROUND_MASK_SET = 0x000F - FOREGROUND_MASK_UNSET = 0xFFF0 - - BACKGROUND_BLUE = 16 - BACKGROUND_GREEN = 32 - BACKGROUND_RED = 64 - BACKGROUND_INTENSITY = 128 - BACKGROUND_MASK_SET = 0x00F0 - BACKGROUND_MASK_UNSET = 0xFF0F - - COMMON_LVB_REVERSE_VIDEO = 0x4000 - COMMON_LVB_UNDERSCORE = 0x8000 - - // http://man7.org/linux/man-pages/man4/console_codes.4.html - // ECMA-48 Set Graphics Rendition - ANSI_ATTR_RESET = 0 - ANSI_ATTR_BOLD = 1 - ANSI_ATTR_DIM = 2 - ANSI_ATTR_UNDERLINE = 4 - ANSI_ATTR_BLINK = 5 - ANSI_ATTR_REVERSE = 7 - ANSI_ATTR_INVISIBLE = 8 - - ANSI_ATTR_UNDERLINE_OFF = 24 - ANSI_ATTR_BLINK_OFF = 25 - ANSI_ATTR_REVERSE_OFF = 27 - ANSI_ATTR_INVISIBLE_OFF = 8 - - ANSI_FOREGROUND_BLACK = 30 - ANSI_FOREGROUND_RED = 31 - ANSI_FOREGROUND_GREEN = 32 - ANSI_FOREGROUND_YELLOW = 33 - ANSI_FOREGROUND_BLUE = 34 - ANSI_FOREGROUND_MAGENTA = 35 - ANSI_FOREGROUND_CYAN = 36 - ANSI_FOREGROUND_WHITE = 37 - ANSI_FOREGROUND_DEFAULT = 39 - - ANSI_BACKGROUND_BLACK = 40 - ANSI_BACKGROUND_RED = 41 - ANSI_BACKGROUND_GREEN = 42 - ANSI_BACKGROUND_YELLOW = 43 - ANSI_BACKGROUND_BLUE = 44 - ANSI_BACKGROUND_MAGENTA = 45 - ANSI_BACKGROUND_CYAN = 46 - ANSI_BACKGROUND_WHITE = 47 - ANSI_BACKGROUND_DEFAULT = 49 - - ANSI_MAX_CMD_LENGTH = 256 - - MAX_INPUT_EVENTS = 128 - MAX_INPUT_BUFFER = 1024 - DEFAULT_WIDTH = 80 - DEFAULT_HEIGHT = 24 -) - -// http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx -const ( - VK_PRIOR = 0x21 // PAGE UP key - VK_NEXT = 0x22 // PAGE DOWN key - VK_END = 0x23 // END key - VK_HOME = 0x24 // HOME key - VK_LEFT = 0x25 // LEFT ARROW key - VK_UP = 0x26 // UP ARROW key - VK_RIGHT = 0x27 // RIGHT ARROW key - VK_DOWN = 0x28 // DOWN ARROW key - VK_SELECT = 0x29 // SELECT key - VK_PRINT = 0x2A // PRINT key - VK_EXECUTE = 0x2B // EXECUTE key - VK_SNAPSHOT = 0x2C // PRINT SCREEN key - VK_INSERT = 0x2D // INS key - VK_DELETE = 0x2E // DEL key - VK_HELP = 0x2F // HELP key - VK_F1 = 0x70 // F1 key - VK_F2 = 0x71 // F2 key - VK_F3 = 0x72 // F3 key - VK_F4 = 0x73 // F4 key - VK_F5 = 0x74 // F5 key - VK_F6 = 0x75 // F6 key - VK_F7 = 0x76 // F7 key - VK_F8 = 0x77 // F8 key - VK_F9 = 0x78 // F9 key - VK_F10 = 0x79 // F10 key - VK_F11 = 0x7A // F11 key - VK_F12 = 0x7B // F12 key -) - -var kernel32DLL = syscall.NewLazyDLL("kernel32.dll") - -var ( - setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") - getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") - setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") - setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") - fillConsoleOutputCharacterProc = kernel32DLL.NewProc("FillConsoleOutputCharacterW") - writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") - readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") - getNumberOfConsoleInputEventsProc = kernel32DLL.NewProc("GetNumberOfConsoleInputEvents") - getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") - setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") - setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") - setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") -) - -// types for calling various windows API -// see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093(v=vs.85).aspx -type ( - SHORT int16 - BOOL int32 - WORD uint16 - WCHAR uint16 - DWORD uint32 - - SMALL_RECT struct { - Left SHORT - Top SHORT - Right SHORT - Bottom SHORT - } - - COORD struct { - X SHORT - Y SHORT - } - - CONSOLE_SCREEN_BUFFER_INFO struct { - Size COORD - CursorPosition COORD - Attributes WORD - Window SMALL_RECT - MaximumWindowSize COORD - } - - CONSOLE_CURSOR_INFO struct { - Size DWORD - Visible BOOL - } - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684166(v=vs.85).aspx - KEY_EVENT_RECORD struct { - KeyDown BOOL - RepeatCount WORD - VirtualKeyCode WORD - VirtualScanCode WORD - UnicodeChar WCHAR - ControlKeyState DWORD - } - - INPUT_RECORD struct { - EventType WORD - KeyEvent KEY_EVENT_RECORD - } - - CHAR_INFO struct { - UnicodeChar WCHAR - Attributes WORD - } -) - -// TODO(azlinux): Basic type clean-up -// -- Convert all uses of uintptr to syscall.Handle to be consistent with Windows syscall -// -- Convert, as appropriate, types to use defined Windows types (e.g., DWORD instead of uint32) - -// Implements the TerminalEmulator interface -type WindowsTerminal struct { - outMutex sync.Mutex - inMutex sync.Mutex - inputBuffer []byte - inputSize int - inputEvents []INPUT_RECORD - screenBufferInfo *CONSOLE_SCREEN_BUFFER_INFO - inputEscapeSequence []byte -} - -func getStdHandle(stdhandle int) uintptr { - handle, err := syscall.GetStdHandle(stdhandle) - if err != nil { - panic(fmt.Errorf("could not get standard io handle %d", stdhandle)) - } - return uintptr(handle) -} - -func WinConsoleStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { - handler := &WindowsTerminal{ - inputBuffer: make([]byte, MAX_INPUT_BUFFER), - inputEscapeSequence: []byte(KEY_ESC_CSI), - inputEvents: make([]INPUT_RECORD, MAX_INPUT_EVENTS), - } - - if IsConsole(os.Stdin.Fd()) { - stdIn = &terminalReader{ - wrappedReader: os.Stdin, - emulator: handler, - command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), - fd: getStdHandle(syscall.STD_INPUT_HANDLE), - } - } else { - stdIn = os.Stdin - } - - if IsConsole(os.Stdout.Fd()) { - stdoutHandle := getStdHandle(syscall.STD_OUTPUT_HANDLE) - - // Save current screen buffer info - screenBufferInfo, err := GetConsoleScreenBufferInfo(stdoutHandle) - if err != nil { - // If GetConsoleScreenBufferInfo returns a nil error, it usually means that stdout is not a TTY. - // However, this is in the branch where stdout is a TTY, hence the panic. - panic("could not get console screen buffer info") - } - handler.screenBufferInfo = screenBufferInfo - - buffer = make([]CHAR_INFO, screenBufferInfo.MaximumWindowSize.X*screenBufferInfo.MaximumWindowSize.Y) - - stdOut = &terminalWriter{ - wrappedWriter: os.Stdout, - emulator: handler, - command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), - fd: stdoutHandle, - } - } else { - stdOut = os.Stdout - } - - if IsConsole(os.Stderr.Fd()) { - stdErr = &terminalWriter{ - wrappedWriter: os.Stderr, - emulator: handler, - command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), - fd: getStdHandle(syscall.STD_ERROR_HANDLE), - } - } else { - stdErr = os.Stderr - } - - return stdIn, stdOut, stdErr -} - -// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. -func GetHandleInfo(in interface{}) (uintptr, bool) { - var inFd uintptr - var isTerminalIn bool - - switch t := in.(type) { - case *terminalReader: - in = t.wrappedReader - case *terminalWriter: - in = t.wrappedWriter - } - - if file, ok := in.(*os.File); ok { - inFd = file.Fd() - isTerminalIn = IsConsole(inFd) - } - return inFd, isTerminalIn -} - -func getError(r1, r2 uintptr, lastErr error) error { - // If the function fails, the return value is zero. - if r1 == 0 { - if lastErr != nil { - return lastErr - } - return syscall.EINVAL - } - return nil -} - -// GetConsoleMode gets the console mode for given file descriptor -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx -func GetConsoleMode(handle uintptr) (uint32, error) { - var mode uint32 - err := syscall.GetConsoleMode(syscall.Handle(handle), &mode) - return mode, err -} - -// SetConsoleMode sets the console mode for given file descriptor -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx -func SetConsoleMode(handle uintptr, mode uint32) error { - return getError(setConsoleModeProc.Call(handle, uintptr(mode), 0)) -} - -// SetCursorVisible sets the cursor visbility -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx -func SetCursorVisible(handle uintptr, isVisible BOOL) (bool, error) { - var cursorInfo *CONSOLE_CURSOR_INFO = &CONSOLE_CURSOR_INFO{} - if err := getError(getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { - return false, err - } - cursorInfo.Visible = isVisible - if err := getError(setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { - return false, err - } - return true, nil -} - -// SetWindowSize sets the size of the console window. -func SetWindowSize(handle uintptr, width, height, max SHORT) (bool, error) { - window := SMALL_RECT{Left: 0, Top: 0, Right: width - 1, Bottom: height - 1} - coord := COORD{X: width - 1, Y: max} - if err := getError(setConsoleWindowInfoProc.Call(handle, uintptr(1), uintptr(unsafe.Pointer(&window)))); err != nil { - return false, err - } - if err := getError(setConsoleScreenBufferSizeProc.Call(handle, marshal(coord))); err != nil { - return false, err - } - return true, nil -} - -// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx -func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { - var info CONSOLE_SCREEN_BUFFER_INFO - if err := getError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)); err != nil { - return nil, err - } - return &info, nil -} - -// setConsoleTextAttribute sets the attributes of characters written to the -// console screen buffer by the WriteFile or WriteConsole function, -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx -func setConsoleTextAttribute(handle uintptr, attribute WORD) error { - return getError(setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)) -} - -func writeConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) (bool, error) { - if err := getError(writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), marshal(bufferSize), marshal(bufferCoord), uintptr(unsafe.Pointer(writeRegion)))); err != nil { - return false, err - } - return true, nil -} - -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682663(v=vs.85).aspx -func fillConsoleOutputCharacter(handle uintptr, fillChar byte, length uint32, writeCord COORD) (bool, error) { - out := int64(0) - if err := getError(fillConsoleOutputCharacterProc.Call(handle, uintptr(fillChar), uintptr(length), marshal(writeCord), uintptr(unsafe.Pointer(&out)))); err != nil { - return false, err - } - return true, nil -} - -// Gets the number of space characters to write for "clearing" the section of terminal -func getNumberOfChars(fromCoord COORD, toCoord COORD, screenSize COORD) uint32 { - // must be valid cursor position - if fromCoord.X < 0 || fromCoord.Y < 0 || toCoord.X < 0 || toCoord.Y < 0 { - return 0 - } - if fromCoord.X >= screenSize.X || fromCoord.Y >= screenSize.Y || toCoord.X >= screenSize.X || toCoord.Y >= screenSize.Y { - return 0 - } - // can't be backwards - if fromCoord.Y > toCoord.Y { - return 0 - } - // same line - if fromCoord.Y == toCoord.Y { - return uint32(toCoord.X-fromCoord.X) + 1 - } - // spans more than one line - if fromCoord.Y < toCoord.Y { - // from start till end of line for first line + from start of line till end - retValue := uint32(screenSize.X-fromCoord.X) + uint32(toCoord.X) + 1 - // don't count first and last line - linesBetween := toCoord.Y - fromCoord.Y - 1 - if linesBetween > 0 { - retValue = retValue + uint32(linesBetween*screenSize.X) - } - return retValue - } - return 0 -} - -var buffer []CHAR_INFO - -func clearDisplayRect(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { - var writeRegion SMALL_RECT - writeRegion.Left = fromCoord.X - writeRegion.Top = fromCoord.Y - writeRegion.Right = toCoord.X - writeRegion.Bottom = toCoord.Y - - // allocate and initialize buffer - width := toCoord.X - fromCoord.X + 1 - height := toCoord.Y - fromCoord.Y + 1 - size := uint32(width) * uint32(height) - if size > 0 { - buffer := make([]CHAR_INFO, size) - for i := range buffer { - buffer[i] = CHAR_INFO{WCHAR(' '), attributes} - } - - // Write to buffer - r, err := writeConsoleOutput(handle, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, &writeRegion) - if !r { - if err != nil { - return 0, err - } - return 0, syscall.EINVAL - } - } - return uint32(size), nil -} - -func clearDisplayRange(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { - nw := uint32(0) - // start and end on same line - if fromCoord.Y == toCoord.Y { - return clearDisplayRect(handle, attributes, fromCoord, toCoord) - } - // TODO(azlinux): if full screen, optimize - - // spans more than one line - if fromCoord.Y < toCoord.Y { - // from start position till end of line for first line - n, err := clearDisplayRect(handle, attributes, fromCoord, COORD{X: toCoord.X, Y: fromCoord.Y}) - if err != nil { - return nw, err - } - nw += n - // lines between - linesBetween := toCoord.Y - fromCoord.Y - 1 - if linesBetween > 0 { - n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: fromCoord.Y + 1}, COORD{X: toCoord.X, Y: toCoord.Y - 1}) - if err != nil { - return nw, err - } - nw += n - } - // lines at end - n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: toCoord.Y}, toCoord) - if err != nil { - return nw, err - } - nw += n - } - return nw, nil -} - -// setConsoleCursorPosition sets the console cursor position -// Note The X and Y are zero based -// If relative is true then the new position is relative to current one -func setConsoleCursorPosition(handle uintptr, isRelative bool, column int16, line int16) error { - screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) - if err != nil { - return err - } - var position COORD - if isRelative { - position.X = screenBufferInfo.CursorPosition.X + SHORT(column) - position.Y = screenBufferInfo.CursorPosition.Y + SHORT(line) - } else { - position.X = SHORT(column) - position.Y = SHORT(line) - } - return getError(setConsoleCursorPositionProc.Call(handle, marshal(position), 0)) -} - -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms683207(v=vs.85).aspx -func getNumberOfConsoleInputEvents(handle uintptr) (uint16, error) { - var n DWORD - if err := getError(getNumberOfConsoleInputEventsProc.Call(handle, uintptr(unsafe.Pointer(&n)))); err != nil { - return 0, err - } - return uint16(n), nil -} - -//http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx -func readConsoleInputKey(handle uintptr, inputBuffer []INPUT_RECORD) (int, error) { - var nr DWORD - if err := getError(readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&inputBuffer[0])), uintptr(len(inputBuffer)), uintptr(unsafe.Pointer(&nr)))); err != nil { - return 0, err - } - return int(nr), nil -} - -func getWindowsTextAttributeForAnsiValue(originalFlag WORD, defaultValue WORD, ansiValue int16) (WORD, error) { - flag := WORD(originalFlag) - if flag == 0 { - flag = defaultValue - } - switch ansiValue { - case ANSI_ATTR_RESET: - flag &^= COMMON_LVB_UNDERSCORE - flag &^= BACKGROUND_INTENSITY - flag = flag | FOREGROUND_INTENSITY - case ANSI_ATTR_INVISIBLE: - // TODO: how do you reset reverse? - case ANSI_ATTR_UNDERLINE: - flag = flag | COMMON_LVB_UNDERSCORE - case ANSI_ATTR_BLINK: - // seems like background intenisty is blink - flag = flag | BACKGROUND_INTENSITY - case ANSI_ATTR_UNDERLINE_OFF: - flag &^= COMMON_LVB_UNDERSCORE - case ANSI_ATTR_BLINK_OFF: - // seems like background intenisty is blink - flag &^= BACKGROUND_INTENSITY - case ANSI_ATTR_BOLD: - flag = flag | FOREGROUND_INTENSITY - case ANSI_ATTR_DIM: - flag &^= FOREGROUND_INTENSITY - case ANSI_ATTR_REVERSE, ANSI_ATTR_REVERSE_OFF: - // swap forground and background bits - foreground := flag & FOREGROUND_MASK_SET - background := flag & BACKGROUND_MASK_SET - flag = (flag & BACKGROUND_MASK_UNSET & FOREGROUND_MASK_UNSET) | (foreground << 4) | (background >> 4) - - // FOREGROUND - case ANSI_FOREGROUND_DEFAULT: - flag = (flag & FOREGROUND_MASK_UNSET) | (defaultValue & FOREGROUND_MASK_SET) - case ANSI_FOREGROUND_BLACK: - flag = flag ^ (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) - case ANSI_FOREGROUND_RED: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED - case ANSI_FOREGROUND_GREEN: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN - case ANSI_FOREGROUND_YELLOW: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN - case ANSI_FOREGROUND_BLUE: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_BLUE - case ANSI_FOREGROUND_MAGENTA: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_BLUE - case ANSI_FOREGROUND_CYAN: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN | FOREGROUND_BLUE - case ANSI_FOREGROUND_WHITE: - flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE - - // Background - case ANSI_BACKGROUND_DEFAULT: - // Black with no intensity - flag = (flag & BACKGROUND_MASK_UNSET) | (defaultValue & BACKGROUND_MASK_SET) - case ANSI_BACKGROUND_BLACK: - flag = (flag & BACKGROUND_MASK_UNSET) - case ANSI_BACKGROUND_RED: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED - case ANSI_BACKGROUND_GREEN: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN - case ANSI_BACKGROUND_YELLOW: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN - case ANSI_BACKGROUND_BLUE: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_BLUE - case ANSI_BACKGROUND_MAGENTA: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_BLUE - case ANSI_BACKGROUND_CYAN: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN | BACKGROUND_BLUE - case ANSI_BACKGROUND_WHITE: - flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE - } - return flag, nil -} - -// HandleOutputCommand interpretes the Ansi commands and then makes appropriate Win32 calls -func (term *WindowsTerminal) HandleOutputCommand(handle uintptr, command []byte) (n int, err error) { - // always consider all the bytes in command, processed - n = len(command) - - parsedCommand := parseAnsiCommand(command) - logrus.Debugf("[windows] HandleOutputCommand: %v", parsedCommand) - - // console settings changes need to happen in atomic way - term.outMutex.Lock() - defer term.outMutex.Unlock() - - switch parsedCommand.Command { - case "m": - // [Value;...;Valuem - // Set Graphics Mode: - // Calls the graphics functions specified by the following values. - // These specified functions remain active until the next occurrence of this escape sequence. - // Graphics mode changes the colors and attributes of text (such as bold and underline) displayed on the screen. - screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) - if err != nil { - return n, err - } - flag := screenBufferInfo.Attributes - for _, e := range parsedCommand.Parameters { - value, _ := strconv.ParseInt(e, 10, 16) // base 10, 16 bit - if value == ANSI_ATTR_RESET { - flag = term.screenBufferInfo.Attributes // reset - } else { - flag, err = getWindowsTextAttributeForAnsiValue(flag, term.screenBufferInfo.Attributes, int16(value)) - if err != nil { - return n, err - } - } - } - if err := setConsoleTextAttribute(handle, flag); err != nil { - return n, err - } - case "H", "f": - // [line;columnH - // [line;columnf - // Moves the cursor to the specified position (coordinates). - // If you do not specify a position, the cursor moves to the home position at the upper-left corner of the screen (line 0, column 0). - screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) - if err != nil { - return n, err - } - line, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) - if err != nil { - return n, err - } - if line > int16(screenBufferInfo.Window.Bottom) { - line = int16(screenBufferInfo.Window.Bottom) + 1 - } - column, err := parseInt16OrDefault(parsedCommand.getParam(1), 1) - if err != nil { - return n, err - } - if column > int16(screenBufferInfo.Window.Right) { - column = int16(screenBufferInfo.Window.Right) + 1 - } - // The numbers are not 0 based, but 1 based - logrus.Debugf("[windows] HandleOutputCommmand: Moving cursor to (%v,%v)", column-1, line-1) - if err := setConsoleCursorPosition(handle, false, column-1, line-1); err != nil { - return n, err - } - - case "A": - // [valueA - // Moves the cursor up by the specified number of lines without changing columns. - // If the cursor is already on the top line, ignores this sequence. - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) - if err != nil { - return len(command), err - } - if err := setConsoleCursorPosition(handle, true, 0, -value); err != nil { - return n, err - } - case "B": - // [valueB - // Moves the cursor down by the specified number of lines without changing columns. - // If the cursor is already on the bottom line, ignores this sequence. - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) - if err != nil { - return n, err - } - if err := setConsoleCursorPosition(handle, true, 0, value); err != nil { - return n, err - } - case "C": - // [valueC - // Moves the cursor forward by the specified number of columns without changing lines. - // If the cursor is already in the rightmost column, ignores this sequence. - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) - if err != nil { - return n, err - } - if err := setConsoleCursorPosition(handle, true, value, 0); err != nil { - return n, err - } - case "D": - // [valueD - // Moves the cursor back by the specified number of columns without changing lines. - // If the cursor is already in the leftmost column, ignores this sequence. - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) - if err != nil { - return n, err - } - if err := setConsoleCursorPosition(handle, true, -value, 0); err != nil { - return n, err - } - case "J": - // [J Erases from the cursor to the end of the screen, including the cursor position. - // [1J Erases from the beginning of the screen to the cursor, including the cursor position. - // [2J Erases the complete display. The cursor does not move. - // Clears the screen and moves the cursor to the home position (line 0, column 0). - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) - if err != nil { - return n, err - } - var start COORD - var cursor COORD - var end COORD - screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) - if err != nil { - return n, err - } - switch value { - case 0: - start = screenBufferInfo.CursorPosition - // end of the buffer - end.X = screenBufferInfo.Size.X - 1 - end.Y = screenBufferInfo.Size.Y - 1 - // cursor - cursor = screenBufferInfo.CursorPosition - case 1: - - // start of the screen - start.X = 0 - start.Y = 0 - // end of the screen - end = screenBufferInfo.CursorPosition - // cursor - cursor = screenBufferInfo.CursorPosition - case 2: - // start of the screen - start.X = 0 - start.Y = 0 - // end of the buffer - end.X = screenBufferInfo.Size.X - 1 - end.Y = screenBufferInfo.Size.Y - 1 - // cursor - cursor.X = 0 - cursor.Y = 0 - } - if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { - return n, err - } - // remember the the cursor position is 1 based - if err := setConsoleCursorPosition(handle, false, int16(cursor.X), int16(cursor.Y)); err != nil { - return n, err - } - - case "K": - // [K - // Clears all characters from the cursor position to the end of the line (including the character at the cursor position). - // [K Erases from the cursor to the end of the line, including the cursor position. - // [1K Erases from the beginning of the line to the cursor, including the cursor position. - // [2K Erases the complete line. - value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) - var start COORD - var cursor COORD - var end COORD - screenBufferInfo, err := GetConsoleScreenBufferInfo(uintptr(handle)) - if err != nil { - return n, err - } - switch value { - case 0: - // start is where cursor is - start = screenBufferInfo.CursorPosition - // end of line - end.X = screenBufferInfo.Size.X - 1 - end.Y = screenBufferInfo.CursorPosition.Y - // cursor remains the same - cursor = screenBufferInfo.CursorPosition - - case 1: - // beginning of line - start.X = 0 - start.Y = screenBufferInfo.CursorPosition.Y - // until cursor - end = screenBufferInfo.CursorPosition - // cursor remains the same - cursor = screenBufferInfo.CursorPosition - case 2: - // start of the line - start.X = 0 - start.Y = screenBufferInfo.CursorPosition.Y - 1 - // end of the line - end.X = screenBufferInfo.Size.X - 1 - end.Y = screenBufferInfo.CursorPosition.Y - 1 - // cursor - cursor.X = 0 - cursor.Y = screenBufferInfo.CursorPosition.Y - 1 - } - if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { - return n, err - } - // remember the the cursor position is 1 based - if err := setConsoleCursorPosition(uintptr(handle), false, int16(cursor.X), int16(cursor.Y)); err != nil { - return n, err - } - - case "l": - for _, value := range parsedCommand.Parameters { - switch value { - case "?25", "25": - SetCursorVisible(uintptr(handle), BOOL(0)) - case "?1049", "1049": - // TODO (azlinux): Restore terminal - case "?1", "1": - // If the DECCKM function is reset, then the arrow keys send ANSI cursor sequences to the host. - term.inputEscapeSequence = []byte(KEY_ESC_CSI) - } - } - case "h": - for _, value := range parsedCommand.Parameters { - switch value { - case "?25", "25": - SetCursorVisible(uintptr(handle), BOOL(1)) - case "?1049", "1049": - // TODO (azlinux): Save terminal - case "?1", "1": - // If the DECCKM function is set, then the arrow keys send application sequences to the host. - // DECCKM (default off): When set, the cursor keys send an ESC O prefix, rather than ESC [. - term.inputEscapeSequence = []byte(KEY_ESC_O) - } - } - - case "]": - /* - TODO (azlinux): - Linux Console Private CSI Sequences - - The following sequences are neither ECMA-48 nor native VT102. They are - native to the Linux console driver. Colors are in SGR parameters: 0 = - black, 1 = red, 2 = green, 3 = brown, 4 = blue, 5 = magenta, 6 = cyan, - 7 = white. - - ESC [ 1 ; n ] Set color n as the underline color - ESC [ 2 ; n ] Set color n as the dim color - ESC [ 8 ] Make the current color pair the default attributes. - ESC [ 9 ; n ] Set screen blank timeout to n minutes. - ESC [ 10 ; n ] Set bell frequency in Hz. - ESC [ 11 ; n ] Set bell duration in msec. - ESC [ 12 ; n ] Bring specified console to the front. - ESC [ 13 ] Unblank the screen. - ESC [ 14 ; n ] Set the VESA powerdown interval in minutes. - - */ - } - return n, nil -} - -// WriteChars writes the bytes to given writer. -func (term *WindowsTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - return w.Write(p) -} - -const ( - CAPSLOCK_ON = 0x0080 //The CAPS LOCK light is on. - ENHANCED_KEY = 0x0100 //The key is enhanced. - LEFT_ALT_PRESSED = 0x0002 //The left ALT key is pressed. - LEFT_CTRL_PRESSED = 0x0008 //The left CTRL key is pressed. - NUMLOCK_ON = 0x0020 //The NUM LOCK light is on. - RIGHT_ALT_PRESSED = 0x0001 //The right ALT key is pressed. - RIGHT_CTRL_PRESSED = 0x0004 //The right CTRL key is pressed. - SCROLLLOCK_ON = 0x0040 //The SCROLL LOCK light is on. - SHIFT_PRESSED = 0x0010 // The SHIFT key is pressed. -) - -const ( - KEY_CONTROL_PARAM_2 = ";2" - KEY_CONTROL_PARAM_3 = ";3" - KEY_CONTROL_PARAM_4 = ";4" - KEY_CONTROL_PARAM_5 = ";5" - KEY_CONTROL_PARAM_6 = ";6" - KEY_CONTROL_PARAM_7 = ";7" - KEY_CONTROL_PARAM_8 = ";8" - KEY_ESC_CSI = "\x1B[" - KEY_ESC_N = "\x1BN" - KEY_ESC_O = "\x1BO" -) - -var keyMapPrefix = map[WORD]string{ - VK_UP: "\x1B[%sA", - VK_DOWN: "\x1B[%sB", - VK_RIGHT: "\x1B[%sC", - VK_LEFT: "\x1B[%sD", - VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 - VK_END: "\x1B[4%s~", // showkey shows ^[[4 - VK_INSERT: "\x1B[2%s~", - VK_DELETE: "\x1B[3%s~", - VK_PRIOR: "\x1B[5%s~", - VK_NEXT: "\x1B[6%s~", - VK_F1: "", - VK_F2: "", - VK_F3: "\x1B[13%s~", - VK_F4: "\x1B[14%s~", - VK_F5: "\x1B[15%s~", - VK_F6: "\x1B[17%s~", - VK_F7: "\x1B[18%s~", - VK_F8: "\x1B[19%s~", - VK_F9: "\x1B[20%s~", - VK_F10: "\x1B[21%s~", - VK_F11: "\x1B[23%s~", - VK_F12: "\x1B[24%s~", -} - -var arrowKeyMapPrefix = map[WORD]string{ - VK_UP: "%s%sA", - VK_DOWN: "%s%sB", - VK_RIGHT: "%s%sC", - VK_LEFT: "%s%sD", -} - -func getControlStateParameter(shift, alt, control, meta bool) string { - if shift && alt && control { - return KEY_CONTROL_PARAM_8 - } - if alt && control { - return KEY_CONTROL_PARAM_7 - } - if shift && control { - return KEY_CONTROL_PARAM_6 - } - if control { - return KEY_CONTROL_PARAM_5 - } - if shift && alt { - return KEY_CONTROL_PARAM_4 - } - if alt { - return KEY_CONTROL_PARAM_3 - } - if shift { - return KEY_CONTROL_PARAM_2 - } - return "" -} - -func getControlKeys(controlState DWORD) (shift, alt, control bool) { - shift = 0 != (controlState & SHIFT_PRESSED) - alt = 0 != (controlState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) - control = 0 != (controlState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) - return shift, alt, control -} - -func charSequenceForKeys(key WORD, controlState DWORD, escapeSequence []byte) string { - i, ok := arrowKeyMapPrefix[key] - if ok { - shift, alt, control := getControlKeys(controlState) - modifier := getControlStateParameter(shift, alt, control, false) - return fmt.Sprintf(i, escapeSequence, modifier) - } - - i, ok = keyMapPrefix[key] - if ok { - shift, alt, control := getControlKeys(controlState) - modifier := getControlStateParameter(shift, alt, control, false) - return fmt.Sprintf(i, modifier) - } - - return "" -} - -// mapKeystokeToTerminalString maps the given input event record to string -func mapKeystokeToTerminalString(keyEvent *KEY_EVENT_RECORD, escapeSequence []byte) string { - _, alt, control := getControlKeys(keyEvent.ControlKeyState) - if keyEvent.UnicodeChar == 0 { - return charSequenceForKeys(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) - } - if control { - // TODO(azlinux): Implement following control sequences - // -D Signals the end of input from the keyboard; also exits current shell. - // -H Deletes the first character to the left of the cursor. Also called the ERASE key. - // -Q Restarts printing after it has been stopped with -s. - // -S Suspends printing on the screen (does not stop the program). - // -U Deletes all characters on the current line. Also called the KILL key. - // -E Quits current command and creates a core - - } - // +Key generates ESC N Key - if !control && alt { - return KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) - } - return string(keyEvent.UnicodeChar) -} - -// getAvailableInputEvents polls the console for availble events -// The function does not return until at least one input record has been read. -func getAvailableInputEvents(handle uintptr, inputEvents []INPUT_RECORD) (n int, err error) { - // TODO(azlinux): Why is there a for loop? Seems to me, that `n` cannot be negative. - tibor - for { - // Read number of console events available - n, err = readConsoleInputKey(handle, inputEvents) - if err != nil || n >= 0 { - return n, err - } - } -} - -// getTranslatedKeyCodes converts the input events into the string of characters -// The ansi escape sequence are used to map key strokes to the strings -func getTranslatedKeyCodes(inputEvents []INPUT_RECORD, escapeSequence []byte) string { - var buf bytes.Buffer - for i := 0; i < len(inputEvents); i++ { - input := inputEvents[i] - if input.EventType == KEY_EVENT && input.KeyEvent.KeyDown != 0 { - keyString := mapKeystokeToTerminalString(&input.KeyEvent, escapeSequence) - buf.WriteString(keyString) - } - } - return buf.String() -} - -// ReadChars reads the characters from the given reader -func (term *WindowsTerminal) ReadChars(fd uintptr, r io.Reader, p []byte) (n int, err error) { - for term.inputSize == 0 { - nr, err := getAvailableInputEvents(fd, term.inputEvents) - if nr == 0 && nil != err { - return n, err - } - if nr > 0 { - keyCodes := getTranslatedKeyCodes(term.inputEvents[:nr], term.inputEscapeSequence) - term.inputSize = copy(term.inputBuffer, keyCodes) - } - } - n = copy(p, term.inputBuffer[:term.inputSize]) - term.inputSize -= n - return n, nil -} - -// HandleInputSequence interprets the input sequence command -func (term *WindowsTerminal) HandleInputSequence(fd uintptr, command []byte) (n int, err error) { - return 0, nil -} - -func marshal(c COORD) uintptr { - return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) -} - -// IsConsole returns true if the given file descriptor is a terminal. -// -- The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. -func IsConsole(fd uintptr) bool { - _, e := GetConsoleMode(fd) - return e == nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/winconsole/term_emulator.go b/vendor/github.com/docker/docker/pkg/term/winconsole/term_emulator.go deleted file mode 100644 index 2d5edc0390e5..000000000000 --- a/vendor/github.com/docker/docker/pkg/term/winconsole/term_emulator.go +++ /dev/null @@ -1,234 +0,0 @@ -package winconsole - -import ( - "fmt" - "io" - "strconv" - "strings" -) - -// http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html -const ( - ANSI_ESCAPE_PRIMARY = 0x1B - ANSI_ESCAPE_SECONDARY = 0x5B - ANSI_COMMAND_FIRST = 0x40 - ANSI_COMMAND_LAST = 0x7E - ANSI_PARAMETER_SEP = ";" - ANSI_CMD_G0 = '(' - ANSI_CMD_G1 = ')' - ANSI_CMD_G2 = '*' - ANSI_CMD_G3 = '+' - ANSI_CMD_DECPNM = '>' - ANSI_CMD_DECPAM = '=' - ANSI_CMD_OSC = ']' - ANSI_CMD_STR_TERM = '\\' - ANSI_BEL = 0x07 - KEY_EVENT = 1 -) - -// Interface that implements terminal handling -type terminalEmulator interface { - HandleOutputCommand(fd uintptr, command []byte) (n int, err error) - HandleInputSequence(fd uintptr, command []byte) (n int, err error) - WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) - ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) -} - -type terminalWriter struct { - wrappedWriter io.Writer - emulator terminalEmulator - command []byte - inSequence bool - fd uintptr -} - -type terminalReader struct { - wrappedReader io.ReadCloser - emulator terminalEmulator - command []byte - inSequence bool - fd uintptr -} - -// http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html -func isAnsiCommandChar(b byte) bool { - switch { - case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: - return true - case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: - // non-CSI escape sequence terminator - return true - case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: - // String escape sequence terminator - return true - } - return false -} - -func isCharacterSelectionCmdChar(b byte) bool { - return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) -} - -func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) -} - -// Write writes len(p) bytes from p to the underlying data stream. -// http://golang.org/pkg/io/#Writer -func (tw *terminalWriter) Write(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - if tw.emulator == nil { - return tw.wrappedWriter.Write(p) - } - // Emulate terminal by extracting commands and executing them - totalWritten := 0 - start := 0 // indicates start of the next chunk - end := len(p) - for current := 0; current < end; current++ { - if tw.inSequence { - // inside escape sequence - tw.command = append(tw.command, p[current]) - if isAnsiCommandChar(p[current]) { - if !isXtermOscSequence(tw.command, p[current]) { - // found the last command character. - // Now we have a complete command. - nchar, err := tw.emulator.HandleOutputCommand(tw.fd, tw.command) - totalWritten += nchar - if err != nil { - return totalWritten, err - } - - // clear the command - // don't include current character again - tw.command = tw.command[:0] - start = current + 1 - tw.inSequence = false - } - } - } else { - if p[current] == ANSI_ESCAPE_PRIMARY { - // entering escape sequnce - tw.inSequence = true - // indicates end of "normal sequence", write whatever you have so far - if len(p[start:current]) > 0 { - nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:current]) - totalWritten += nw - if err != nil { - return totalWritten, err - } - } - // include the current character as part of the next sequence - tw.command = append(tw.command, p[current]) - } - } - } - // note that so far, start of the escape sequence triggers writing out of bytes to console. - // For the part _after_ the end of last escape sequence, it is not written out yet. So write it out - if !tw.inSequence { - // assumption is that we can't be inside sequence and therefore command should be empty - if len(p[start:]) > 0 { - nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:]) - totalWritten += nw - if err != nil { - return totalWritten, err - } - } - } - return totalWritten, nil - -} - -// Read reads up to len(p) bytes into p. -// http://golang.org/pkg/io/#Reader -func (tr *terminalReader) Read(p []byte) (n int, err error) { - //Implementations of Read are discouraged from returning a zero byte count - // with a nil error, except when len(p) == 0. - if len(p) == 0 { - return 0, nil - } - if nil == tr.emulator { - return tr.readFromWrappedReader(p) - } - return tr.emulator.ReadChars(tr.fd, tr.wrappedReader, p) -} - -// Close the underlying stream -func (tr *terminalReader) Close() (err error) { - return tr.wrappedReader.Close() -} - -func (tr *terminalReader) readFromWrappedReader(p []byte) (n int, err error) { - return tr.wrappedReader.Read(p) -} - -type ansiCommand struct { - CommandBytes []byte - Command string - Parameters []string - IsSpecial bool -} - -func parseAnsiCommand(command []byte) *ansiCommand { - if isCharacterSelectionCmdChar(command[1]) { - // Is Character Set Selection commands - return &ansiCommand{ - CommandBytes: command, - Command: string(command), - IsSpecial: true, - } - } - // last char is command character - lastCharIndex := len(command) - 1 - - retValue := &ansiCommand{ - CommandBytes: command, - Command: string(command[lastCharIndex]), - IsSpecial: false, - } - // more than a single escape - if lastCharIndex != 0 { - start := 1 - // skip if double char escape sequence - if command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { - start++ - } - // convert this to GetNextParam method - retValue.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) - } - return retValue -} - -func (c *ansiCommand) getParam(index int) string { - if len(c.Parameters) > index { - return c.Parameters[index] - } - return "" -} - -func (ac *ansiCommand) String() string { - return fmt.Sprintf("0x%v \"%v\" (\"%v\")", - bytesToHex(ac.CommandBytes), - ac.Command, - strings.Join(ac.Parameters, "\",\"")) -} - -func bytesToHex(b []byte) string { - hex := make([]string, len(b)) - for i, ch := range b { - hex[i] = fmt.Sprintf("%X", ch) - } - return strings.Join(hex, "") -} - -func parseInt16OrDefault(s string, defaultValue int16) (n int16, err error) { - if s == "" { - return defaultValue, nil - } - parsedValue, err := strconv.ParseInt(s, 10, 16) - if err != nil { - return defaultValue, err - } - return int16(parsedValue), nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go new file mode 100644 index 000000000000..3bf2b2b6b46b --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go @@ -0,0 +1,257 @@ +// +build windows + +package windows + +import ( + "bytes" + "errors" + "fmt" + "os" + "strings" + "unsafe" + + ansiterm "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm/winterm" +) + +const ( + escapeSequence = ansiterm.KEY_ESC_CSI +) + +// ansiReader wraps a standard input file (e.g., os.Stdin) providing ANSI sequence translation. +type ansiReader struct { + file *os.File + fd uintptr + buffer []byte + cbBuffer int + command []byte +} + +func newAnsiReader(nFile int) *ansiReader { + file, fd := winterm.GetStdFile(nFile) + return &ansiReader{ + file: file, + fd: fd, + command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), + buffer: make([]byte, 0), + } +} + +// Close closes the wrapped file. +func (ar *ansiReader) Close() (err error) { + return ar.file.Close() +} + +// Fd returns the file descriptor of the wrapped file. +func (ar *ansiReader) Fd() uintptr { + return ar.fd +} + +// Read reads up to len(p) bytes of translated input events into p. +func (ar *ansiReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + + // Previously read bytes exist, read as much as we can and return + if len(ar.buffer) > 0 { + logger.Debugf("Reading previously cached bytes") + + originalLength := len(ar.buffer) + copiedLength := copy(p, ar.buffer) + + if copiedLength == originalLength { + ar.buffer = make([]byte, 0, len(p)) + } else { + ar.buffer = ar.buffer[copiedLength:] + } + + logger.Debugf("Read from cache p[%d]: % x", copiedLength, p) + return copiedLength, nil + } + + // Read and translate key events + events, err := readInputEvents(ar.fd, len(p)) + if err != nil { + return 0, err + } else if len(events) == 0 { + logger.Debug("No input events detected") + return 0, nil + } + + keyBytes := translateKeyEvents(events, []byte(escapeSequence)) + + // Save excess bytes and right-size keyBytes + if len(keyBytes) > len(p) { + logger.Debugf("Received %d keyBytes, only room for %d bytes", len(keyBytes), len(p)) + ar.buffer = keyBytes[len(p):] + keyBytes = keyBytes[:len(p)] + } else if len(keyBytes) == 0 { + logger.Debug("No key bytes returned from the translator") + return 0, nil + } + + copiedLength := copy(p, keyBytes) + if copiedLength != len(keyBytes) { + return 0, errors.New("Unexpected copy length encountered.") + } + + logger.Debugf("Read p[%d]: % x", copiedLength, p) + logger.Debugf("Read keyBytes[%d]: % x", copiedLength, keyBytes) + return copiedLength, nil +} + +// readInputEvents polls until at least one event is available. +func readInputEvents(fd uintptr, maxBytes int) ([]winterm.INPUT_RECORD, error) { + // Determine the maximum number of records to retrieve + // -- Cast around the type system to obtain the size of a single INPUT_RECORD. + // unsafe.Sizeof requires an expression vs. a type-reference; the casting + // tricks the type system into believing it has such an expression. + recordSize := int(unsafe.Sizeof(*((*winterm.INPUT_RECORD)(unsafe.Pointer(&maxBytes))))) + countRecords := maxBytes / recordSize + if countRecords > ansiterm.MAX_INPUT_EVENTS { + countRecords = ansiterm.MAX_INPUT_EVENTS + } + logger.Debugf("[windows] readInputEvents: Reading %v records (buffer size %v, record size %v)", countRecords, maxBytes, recordSize) + + // Wait for and read input events + events := make([]winterm.INPUT_RECORD, countRecords) + nEvents := uint32(0) + eventsExist, err := winterm.WaitForSingleObject(fd, winterm.WAIT_INFINITE) + if err != nil { + return nil, err + } + + if eventsExist { + err = winterm.ReadConsoleInput(fd, events, &nEvents) + if err != nil { + return nil, err + } + } + + // Return a slice restricted to the number of returned records + logger.Debugf("[windows] readInputEvents: Read %v events", nEvents) + return events[:nEvents], nil +} + +// KeyEvent Translation Helpers + +var arrowKeyMapPrefix = map[winterm.WORD]string{ + winterm.VK_UP: "%s%sA", + winterm.VK_DOWN: "%s%sB", + winterm.VK_RIGHT: "%s%sC", + winterm.VK_LEFT: "%s%sD", +} + +var keyMapPrefix = map[winterm.WORD]string{ + winterm.VK_UP: "\x1B[%sA", + winterm.VK_DOWN: "\x1B[%sB", + winterm.VK_RIGHT: "\x1B[%sC", + winterm.VK_LEFT: "\x1B[%sD", + winterm.VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 + winterm.VK_END: "\x1B[4%s~", // showkey shows ^[[4 + winterm.VK_INSERT: "\x1B[2%s~", + winterm.VK_DELETE: "\x1B[3%s~", + winterm.VK_PRIOR: "\x1B[5%s~", + winterm.VK_NEXT: "\x1B[6%s~", + winterm.VK_F1: "", + winterm.VK_F2: "", + winterm.VK_F3: "\x1B[13%s~", + winterm.VK_F4: "\x1B[14%s~", + winterm.VK_F5: "\x1B[15%s~", + winterm.VK_F6: "\x1B[17%s~", + winterm.VK_F7: "\x1B[18%s~", + winterm.VK_F8: "\x1B[19%s~", + winterm.VK_F9: "\x1B[20%s~", + winterm.VK_F10: "\x1B[21%s~", + winterm.VK_F11: "\x1B[23%s~", + winterm.VK_F12: "\x1B[24%s~", +} + +// translateKeyEvents converts the input events into the appropriate ANSI string. +func translateKeyEvents(events []winterm.INPUT_RECORD, escapeSequence []byte) []byte { + var buffer bytes.Buffer + for _, event := range events { + if event.EventType == winterm.KEY_EVENT && event.KeyEvent.KeyDown != 0 { + buffer.WriteString(keyToString(&event.KeyEvent, escapeSequence)) + } + } + + return buffer.Bytes() +} + +// keyToString maps the given input event record to the corresponding string. +func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) string { + if keyEvent.UnicodeChar == 0 { + return formatVirtualKey(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) + } + + _, alt, control := getControlKeys(keyEvent.ControlKeyState) + if control { + // TODO(azlinux): Implement following control sequences + // -D Signals the end of input from the keyboard; also exits current shell. + // -H Deletes the first character to the left of the cursor. Also called the ERASE key. + // -Q Restarts printing after it has been stopped with -s. + // -S Suspends printing on the screen (does not stop the program). + // -U Deletes all characters on the current line. Also called the KILL key. + // -E Quits current command and creates a core + + } + + // +Key generates ESC N Key + if !control && alt { + return ansiterm.KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) + } + + return string(keyEvent.UnicodeChar) +} + +// formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string. +func formatVirtualKey(key winterm.WORD, controlState winterm.DWORD, escapeSequence []byte) string { + shift, alt, control := getControlKeys(controlState) + modifier := getControlKeysModifier(shift, alt, control) + + if format, ok := arrowKeyMapPrefix[key]; ok { + return fmt.Sprintf(format, escapeSequence, modifier) + } + + if format, ok := keyMapPrefix[key]; ok { + return fmt.Sprintf(format, modifier) + } + + return "" +} + +// getControlKeys extracts the shift, alt, and ctrl key states. +func getControlKeys(controlState winterm.DWORD) (shift, alt, control bool) { + shift = 0 != (controlState & winterm.SHIFT_PRESSED) + alt = 0 != (controlState & (winterm.LEFT_ALT_PRESSED | winterm.RIGHT_ALT_PRESSED)) + control = 0 != (controlState & (winterm.LEFT_CTRL_PRESSED | winterm.RIGHT_CTRL_PRESSED)) + return shift, alt, control +} + +// getControlKeysModifier returns the ANSI modifier for the given combination of control keys. +func getControlKeysModifier(shift, alt, control bool) string { + if shift && alt && control { + return ansiterm.KEY_CONTROL_PARAM_8 + } + if alt && control { + return ansiterm.KEY_CONTROL_PARAM_7 + } + if shift && control { + return ansiterm.KEY_CONTROL_PARAM_6 + } + if control { + return ansiterm.KEY_CONTROL_PARAM_5 + } + if shift && alt { + return ansiterm.KEY_CONTROL_PARAM_4 + } + if alt { + return ansiterm.KEY_CONTROL_PARAM_3 + } + if shift { + return ansiterm.KEY_CONTROL_PARAM_2 + } + return "" +} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go new file mode 100644 index 000000000000..9f3232c09341 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go @@ -0,0 +1,76 @@ +// +build windows + +package windows + +import ( + "io/ioutil" + "os" + + ansiterm "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm/winterm" + "github.com/Sirupsen/logrus" +) + +var logger *logrus.Logger + +// ansiWriter wraps a standard output file (e.g., os.Stdout) providing ANSI sequence translation. +type ansiWriter struct { + file *os.File + fd uintptr + infoReset *winterm.CONSOLE_SCREEN_BUFFER_INFO + command []byte + escapeSequence []byte + inAnsiSequence bool + parser *ansiterm.AnsiParser +} + +func newAnsiWriter(nFile int) *ansiWriter { + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("ansiReaderWriter.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.DebugLevel, + } + + file, fd := winterm.GetStdFile(nFile) + info, err := winterm.GetConsoleScreenBufferInfo(fd) + if err != nil { + return nil + } + + parser := ansiterm.CreateParser("Ground", winterm.CreateWinEventHandler(fd, file)) + logger.Infof("newAnsiWriter: parser %p", parser) + + aw := &ansiWriter{ + file: file, + fd: fd, + infoReset: info, + command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), + escapeSequence: []byte(ansiterm.KEY_ESC_CSI), + parser: parser, + } + + logger.Infof("newAnsiWriter: aw.parser %p", aw.parser) + logger.Infof("newAnsiWriter: %v", aw) + return aw +} + +func (aw *ansiWriter) Fd() uintptr { + return aw.fd +} + +// Write writes len(p) bytes from p to the underlying data stream. +func (aw *ansiWriter) Write(p []byte) (total int, err error) { + if len(p) == 0 { + return 0, nil + } + + logger.Infof("Write: % x", p) + logger.Infof("Write: %s", string(p)) + return aw.parser.Parse(p) +} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/console.go b/vendor/github.com/docker/docker/pkg/term/windows/console.go new file mode 100644 index 000000000000..3036a046053d --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/windows/console.go @@ -0,0 +1,97 @@ +// +build windows + +package windows + +import ( + "io" + "os" + "syscall" + + "github.com/Azure/go-ansiterm/winterm" + + ansiterm "github.com/Azure/go-ansiterm" + "github.com/Sirupsen/logrus" + "io/ioutil" +) + +// ConEmuStreams returns prepared versions of console streams, +// for proper use in ConEmu terminal. +// The ConEmu terminal emulates ANSI on output streams well by default. +func ConEmuStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + if IsConsole(os.Stdin.Fd()) { + stdIn = newAnsiReader(syscall.STD_INPUT_HANDLE) + } else { + stdIn = os.Stdin + } + + stdOut = os.Stdout + stdErr = os.Stderr + + // WARNING (BEGIN): sourced from newAnsiWriter + + logFile := ioutil.Discard + + if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { + logFile, _ = os.Create("ansiReaderWriter.log") + } + + logger = &logrus.Logger{ + Out: logFile, + Formatter: new(logrus.TextFormatter), + Level: logrus.DebugLevel, + } + + // WARNING (END): sourced from newAnsiWriter + + return stdIn, stdOut, stdErr +} + +// ConsoleStreams returns a wrapped version for each standard stream referencing a console, +// that handles ANSI character sequences. +func ConsoleStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { + if IsConsole(os.Stdin.Fd()) { + stdIn = newAnsiReader(syscall.STD_INPUT_HANDLE) + } else { + stdIn = os.Stdin + } + + if IsConsole(os.Stdout.Fd()) { + stdOut = newAnsiWriter(syscall.STD_OUTPUT_HANDLE) + } else { + stdOut = os.Stdout + } + + if IsConsole(os.Stderr.Fd()) { + stdErr = newAnsiWriter(syscall.STD_ERROR_HANDLE) + } else { + stdErr = os.Stderr + } + + return stdIn, stdOut, stdErr +} + +// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. +func GetHandleInfo(in interface{}) (uintptr, bool) { + switch t := in.(type) { + case *ansiReader: + return t.Fd(), true + case *ansiWriter: + return t.Fd(), true + } + + var inFd uintptr + var isTerminal bool + + if file, ok := in.(*os.File); ok { + inFd = file.Fd() + isTerminal = IsConsole(inFd) + } + return inFd, isTerminal +} + +// IsConsole returns true if the given file descriptor is a Windows Console. +// The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. +func IsConsole(fd uintptr) bool { + _, e := winterm.GetConsoleMode(fd) + return e == nil +} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/windows.go b/vendor/github.com/docker/docker/pkg/term/windows/windows.go new file mode 100644 index 000000000000..bf4c7b502563 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/term/windows/windows.go @@ -0,0 +1,5 @@ +// These files implement ANSI-aware input and output streams for use by the Docker Windows client. +// When asked for the set of standard streams (e.g., stdin, stdout, stderr), the code will create +// and return pseudo-streams that convert ANSI sequences to / from Windows Console API calls. + +package windows diff --git a/vendor/github.com/docker/docker/pkg/timeutils/utils.go b/vendor/github.com/docker/docker/pkg/timeutils/utils.go deleted file mode 100644 index 8437f12472c5..000000000000 --- a/vendor/github.com/docker/docker/pkg/timeutils/utils.go +++ /dev/null @@ -1,36 +0,0 @@ -package timeutils - -import ( - "strconv" - "strings" - "time" -) - -// GetTimestamp tries to parse given string as golang duration, -// then RFC3339 time and finally as a Unix timestamp. If -// any of these were successful, it returns a Unix timestamp -// as string otherwise returns the given value back. -// In case of duration input, the returned timestamp is computed -// as the given reference time minus the amount of the duration. -func GetTimestamp(value string, reference time.Time) string { - if d, err := time.ParseDuration(value); value != "0" && err == nil { - return strconv.FormatInt(reference.Add(-d).Unix(), 10) - } - - var format string - if strings.Contains(value, ".") { - format = time.RFC3339Nano - } else { - format = time.RFC3339 - } - - loc := time.FixedZone(time.Now().Zone()) - if len(value) < len(format) { - format = format[:len(value)] - } - t, err := time.ParseInLocation(format, value, loc) - if err != nil { - return value - } - return strconv.FormatInt(t.Unix(), 10) -} diff --git a/vendor/github.com/docker/docker/pkg/units/duration.go b/vendor/github.com/docker/docker/pkg/units/duration.go deleted file mode 100644 index 44012aafb5eb..000000000000 --- a/vendor/github.com/docker/docker/pkg/units/duration.go +++ /dev/null @@ -1,31 +0,0 @@ -package units - -import ( - "fmt" - "time" -) - -// HumanDuration returns a human-readable approximation of a duration -// (eg. "About a minute", "4 hours ago", etc.) -func HumanDuration(d time.Duration) string { - if seconds := int(d.Seconds()); seconds < 1 { - return "Less than a second" - } else if seconds < 60 { - return fmt.Sprintf("%d seconds", seconds) - } else if minutes := int(d.Minutes()); minutes == 1 { - return "About a minute" - } else if minutes < 60 { - return fmt.Sprintf("%d minutes", minutes) - } else if hours := int(d.Hours()); hours == 1 { - return "About an hour" - } else if hours < 48 { - return fmt.Sprintf("%d hours", hours) - } else if hours < 24*7*2 { - return fmt.Sprintf("%d days", hours/24) - } else if hours < 24*30*3 { - return fmt.Sprintf("%d weeks", hours/24/7) - } else if hours < 24*365*2 { - return fmt.Sprintf("%d months", hours/24/30) - } - return fmt.Sprintf("%d years", int(d.Hours())/24/365) -} diff --git a/vendor/github.com/docker/docker/pkg/units/size.go b/vendor/github.com/docker/docker/pkg/units/size.go deleted file mode 100644 index 9e84697caff5..000000000000 --- a/vendor/github.com/docker/docker/pkg/units/size.go +++ /dev/null @@ -1,93 +0,0 @@ -package units - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// See: http://en.wikipedia.org/wiki/Binary_prefix -const ( - // Decimal - - KB = 1000 - MB = 1000 * KB - GB = 1000 * MB - TB = 1000 * GB - PB = 1000 * TB - - // Binary - - KiB = 1024 - MiB = 1024 * KiB - GiB = 1024 * MiB - TiB = 1024 * GiB - PiB = 1024 * TiB -) - -type unitMap map[string]int64 - -var ( - decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} - binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} - sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`) -) - -var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} -var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - -// CustomSize returns a human-readable approximation of a size -// using custom format -func CustomSize(format string, size float64, base float64, _map []string) string { - i := 0 - for size >= base { - size = size / base - i++ - } - return fmt.Sprintf(format, size, _map[i]) -} - -// HumanSize returns a human-readable approximation of a size -// using SI standard (eg. "44kB", "17MB") -func HumanSize(size float64) string { - return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) -} - -func BytesSize(size float64) string { - return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs) -} - -// FromHumanSize returns an integer from a human-readable specification of a -// size using SI standard (eg. "44kB", "17MB") -func FromHumanSize(size string) (int64, error) { - return parseSize(size, decimalMap) -} - -// RAMInBytes parses a human-readable string representing an amount of RAM -// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and -// returns the number of bytes, or -1 if the string is unparseable. -// Units are case-insensitive, and the 'b' suffix is optional. -func RAMInBytes(size string) (int64, error) { - return parseSize(size, binaryMap) -} - -// Parses the human-readable size string into the amount it represents -func parseSize(sizeStr string, uMap unitMap) (int64, error) { - matches := sizeRegex.FindStringSubmatch(sizeStr) - if len(matches) != 3 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - size, err := strconv.ParseInt(matches[1], 10, 0) - if err != nil { - return -1, err - } - - unitPrefix := strings.ToLower(matches[2]) - if mul, ok := uMap[unitPrefix]; ok { - size *= mul - } - - return size, nil -} diff --git a/vendor/github.com/emicklei/go-restful/README.md b/vendor/github.com/emicklei/go-restful/README.md index 8f954c0163c0..e5492e47672d 100644 --- a/vendor/github.com/emicklei/go-restful/README.md +++ b/vendor/github.com/emicklei/go-restful/README.md @@ -40,7 +40,7 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo - Routes for request → function mapping with path parameter (e.g. {id}) support - Configurable router: - - Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but doest **not** accept) regular expressions (See RouterJSR311 which is used by default) + - Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but does **not** accept) regular expressions (See RouterJSR311 which is used by default) - Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}, See CurlyRouter) - Request API for reading structs from JSON/XML and accesing parameters (path,query,header) - Response API for writing structs to JSON/XML and setting headers @@ -71,4 +71,4 @@ func (u UserResource) findUser(request *restful.Request, response *restful.Respo (c) 2012 - 2015, http://ernestmicklei.com. MIT License -Type ```git shortlog -s``` for a full list of contributors. \ No newline at end of file +Type ```git shortlog -s``` for a full list of contributors. diff --git a/vendor/github.com/emicklei/go-restful/curly.go b/vendor/github.com/emicklei/go-restful/curly.go index ce284f747680..185300dbc73d 100644 --- a/vendor/github.com/emicklei/go-restful/curly.go +++ b/vendor/github.com/emicklei/go-restful/curly.go @@ -44,16 +44,16 @@ func (c CurlyRouter) SelectRoute( } // selectRoutes return a collection of Route from a WebService that matches the path tokens from the request. -func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) []Route { - candidates := &sortableCurlyRoutes{[]*curlyRoute{}} +func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) sortableCurlyRoutes { + candidates := sortableCurlyRoutes{} for _, each := range ws.routes { matches, paramCount, staticCount := c.matchesRouteByPathTokens(each.pathParts, requestTokens) if matches { - candidates.add(&curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? + candidates.add(curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? } } sort.Sort(sort.Reverse(candidates)) - return candidates.routes() + return candidates } // matchesRouteByPathTokens computes whether it matches, howmany parameters do match and what the number of static path elements are. @@ -110,9 +110,9 @@ func (c CurlyRouter) regularMatchesPathToken(routeToken string, colon int, reque // detectRoute selectes from a list of Route the first match by inspecting both the Accept and Content-Type // headers of the Request. See also RouterJSR311 in jsr311.go -func (c CurlyRouter) detectRoute(candidateRoutes []Route, httpRequest *http.Request) (*Route, error) { +func (c CurlyRouter) detectRoute(candidateRoutes sortableCurlyRoutes, httpRequest *http.Request) (*Route, error) { // tracing is done inside detectRoute - return RouterJSR311{}.detectRoute(candidateRoutes, httpRequest) + return RouterJSR311{}.detectRoute(candidateRoutes.routes(), httpRequest) } // detectWebService returns the best matching webService given the list of path tokens. diff --git a/vendor/github.com/emicklei/go-restful/curly_route.go b/vendor/github.com/emicklei/go-restful/curly_route.go index 3edab72fd803..296f94650e65 100644 --- a/vendor/github.com/emicklei/go-restful/curly_route.go +++ b/vendor/github.com/emicklei/go-restful/curly_route.go @@ -11,30 +11,28 @@ type curlyRoute struct { staticCount int } -type sortableCurlyRoutes struct { - candidates []*curlyRoute -} +type sortableCurlyRoutes []curlyRoute -func (s *sortableCurlyRoutes) add(route *curlyRoute) { - s.candidates = append(s.candidates, route) +func (s *sortableCurlyRoutes) add(route curlyRoute) { + *s = append(*s, route) } -func (s *sortableCurlyRoutes) routes() (routes []Route) { - for _, each := range s.candidates { +func (s sortableCurlyRoutes) routes() (routes []Route) { + for _, each := range s { routes = append(routes, each.route) // TODO change return type } return routes } -func (s *sortableCurlyRoutes) Len() int { - return len(s.candidates) +func (s sortableCurlyRoutes) Len() int { + return len(s) } -func (s *sortableCurlyRoutes) Swap(i, j int) { - s.candidates[i], s.candidates[j] = s.candidates[j], s.candidates[i] +func (s sortableCurlyRoutes) Swap(i, j int) { + s[i], s[j] = s[j], s[i] } -func (s *sortableCurlyRoutes) Less(i, j int) bool { - ci := s.candidates[i] - cj := s.candidates[j] +func (s sortableCurlyRoutes) Less(i, j int) bool { + ci := s[i] + cj := s[j] // primary key if ci.staticCount < cj.staticCount { diff --git a/vendor/github.com/emicklei/go-restful/jsr311.go b/vendor/github.com/emicklei/go-restful/jsr311.go index b4fa9bbae69f..511444ac6854 100644 --- a/vendor/github.com/emicklei/go-restful/jsr311.go +++ b/vendor/github.com/emicklei/go-restful/jsr311.go @@ -74,7 +74,7 @@ func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*R // accept outputMediaOk := []Route{} accept := httpRequest.Header.Get(HEADER_Accept) - if accept == "" { + if len(accept) == 0 { accept = "*/*" } for _, each := range inputMediaOk { @@ -88,7 +88,8 @@ func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*R } return nil, NewError(http.StatusNotAcceptable, "406: Not Acceptable") } - return r.bestMatchByMedia(outputMediaOk, contentType, accept), nil + // return r.bestMatchByMedia(outputMediaOk, contentType, accept), nil + return &outputMediaOk[0], nil } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 diff --git a/vendor/github.com/emicklei/go-restful/response.go b/vendor/github.com/emicklei/go-restful/response.go index 696c67eb70c2..971cd0b42ced 100644 --- a/vendor/github.com/emicklei/go-restful/response.go +++ b/vendor/github.com/emicklei/go-restful/response.go @@ -130,25 +130,25 @@ func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error { } // WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value) -// It uses the standard encoding/xml package for marshalling the valuel ; not using a registered EntityReaderWriter. +// It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter. func (r *Response) WriteAsXml(value interface{}) error { return writeXML(r, http.StatusOK, MIME_XML, value) } // WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value) -// It uses the standard encoding/xml package for marshalling the valuel ; not using a registered EntityReaderWriter. +// It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter. func (r *Response) WriteHeaderAndXml(status int, value interface{}) error { return writeXML(r, status, MIME_XML, value) } // WriteAsJson is a convenience method for writing a value in json. -// It uses the standard encoding/json package for marshalling the valuel ; not using a registered EntityReaderWriter. +// It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. func (r *Response) WriteAsJson(value interface{}) error { return writeJSON(r, http.StatusOK, MIME_JSON, value) } // WriteJson is a convenience method for writing a value in Json with a given Content-Type. -// It uses the standard encoding/json package for marshalling the valuel ; not using a registered EntityReaderWriter. +// It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. func (r *Response) WriteJson(value interface{}, contentType string) error { return writeJSON(r, http.StatusOK, contentType, value) } diff --git a/vendor/github.com/emicklei/go-restful/route_builder.go b/vendor/github.com/emicklei/go-restful/route_builder.go index b49b7c74d35e..8bc1ab684621 100644 --- a/vendor/github.com/emicklei/go-restful/route_builder.go +++ b/vendor/github.com/emicklei/go-restful/route_builder.go @@ -128,7 +128,7 @@ func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder { return b } -// Operation allows you to document what the acutal method/function call is of the Route. +// Operation allows you to document what the actual method/function call is of the Route. // Unless called, the operation name is derived from the RouteFunction set using To(..). func (b *RouteBuilder) Operation(name string) *RouteBuilder { b.operation = name diff --git a/vendor/github.com/emicklei/go-restful/swagger/config.go b/vendor/github.com/emicklei/go-restful/swagger/config.go index 944d988eefb3..510d6fc133aa 100644 --- a/vendor/github.com/emicklei/go-restful/swagger/config.go +++ b/vendor/github.com/emicklei/go-restful/swagger/config.go @@ -9,6 +9,8 @@ import ( // PostBuildDeclarationMapFunc can be used to modify the api declaration map. type PostBuildDeclarationMapFunc func(apiDeclarationMap *ApiDeclarationList) +type MapSchemaFormatFunc func(typeName string) string + type Config struct { // url where the services are available, e.g. http://localhost:8080 // if left empty then the basePath of Swagger is taken from the actual request @@ -31,4 +33,6 @@ type Config struct { PostBuildHandler PostBuildDeclarationMapFunc // Swagger global info struct Info Info + // [optional] If set, model builder should call this handler to get addition typename-to-swagger-format-field convertion. + SchemaFormatHandler MapSchemaFormatFunc } diff --git a/vendor/github.com/emicklei/go-restful/swagger/model_builder.go b/vendor/github.com/emicklei/go-restful/swagger/model_builder.go index fcc2976cb964..696d192e5bce 100644 --- a/vendor/github.com/emicklei/go-restful/swagger/model_builder.go +++ b/vendor/github.com/emicklei/go-restful/swagger/model_builder.go @@ -14,6 +14,7 @@ type ModelBuildable interface { type modelBuilder struct { Models *ModelList + Config *Config } type documentable interface { @@ -231,7 +232,7 @@ func (b modelBuilder) buildStructTypeProperty(field reflect.StructField, jsonNam if field.Name == fieldType.Name() && field.Anonymous && !hasNamedJSONTag(field) { // embedded struct - sub := modelBuilder{new(ModelList)} + sub := modelBuilder{new(ModelList), b.Config} sub.addModel(fieldType, "") subKey := sub.keyFrom(fieldType) // merge properties from sub @@ -410,6 +411,11 @@ func (b modelBuilder) jsonSchemaType(modelName string) string { } func (b modelBuilder) jsonSchemaFormat(modelName string) string { + if b.Config != nil && b.Config.SchemaFormatHandler != nil { + if mapped := b.Config.SchemaFormatHandler(modelName); mapped != "" { + return mapped + } + } schemaMap := map[string]string{ "int": "int32", "int32": "int32", diff --git a/vendor/github.com/emicklei/go-restful/swagger/swagger_webservice.go b/vendor/github.com/emicklei/go-restful/swagger/swagger_webservice.go index 8dc3d5f9ea62..58dd6259022e 100644 --- a/vendor/github.com/emicklei/go-restful/swagger/swagger_webservice.go +++ b/vendor/github.com/emicklei/go-restful/swagger/swagger_webservice.go @@ -241,7 +241,7 @@ func (sws SwaggerService) composeDeclaration(ws *restful.WebService, pathPrefix DataTypeFields: DataTypeFields{Type: &voidString}, Parameters: []Parameter{}, Nickname: route.Operation, - ResponseMessages: composeResponseMessages(route, &decl)} + ResponseMessages: composeResponseMessages(route, &decl, &sws.config)} operation.Consumes = route.Consumes operation.Produces = route.Produces @@ -271,7 +271,7 @@ func withoutWildcard(path string) string { } // composeResponseMessages takes the ResponseErrors (if any) and creates ResponseMessages from them. -func composeResponseMessages(route restful.Route, decl *ApiDeclaration) (messages []ResponseMessage) { +func composeResponseMessages(route restful.Route, decl *ApiDeclaration, config *Config) (messages []ResponseMessage) { if route.ResponseErrors == nil { return messages } @@ -294,7 +294,7 @@ func composeResponseMessages(route restful.Route, decl *ApiDeclaration) (message if isCollection { modelName = "array[" + modelName + "]" } - modelBuilder{&decl.Models}.addModel(st, "") + modelBuilder{Models: &decl.Models, Config: config}.addModel(st, "") // reference the model message.ResponseModel = modelName } @@ -332,11 +332,11 @@ func detectCollectionType(st reflect.Type) (bool, reflect.Type) { // addModelFromSample creates and adds (or overwrites) a Model from a sample resource func (sws SwaggerService) addModelFromSampleTo(operation *Operation, isResponse bool, sample interface{}, models *ModelList) { if isResponse { - type_, items := asDataType(sample) + type_, items := asDataType(sample, &sws.config) operation.Type = type_ operation.Items = items } - modelBuilder{models}.addModelFrom(sample) + modelBuilder{Models: models, Config: &sws.config}.addModelFrom(sample) } func asSwaggerParameter(param restful.ParameterData) Parameter { @@ -411,7 +411,7 @@ func asParamType(kind int) string { return "" } -func asDataType(any interface{}) (*string, *Item) { +func asDataType(any interface{}, config *Config) (*string, *Item) { // If it's not a collection, return the suggested model name st := reflect.TypeOf(any) isCollection, st := detectCollectionType(st) @@ -424,7 +424,7 @@ func asDataType(any interface{}) (*string, *Item) { // XXX: This is not very elegant // We create an Item object referring to the given model models := ModelList{} - mb := modelBuilder{&models} + mb := modelBuilder{Models: &models, Config: config} mb.addModelFrom(any) elemTypeName := mb.getElementTypeName(modelName, "", st) diff --git a/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go b/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go new file mode 100644 index 000000000000..c52878dd5965 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go @@ -0,0 +1,99 @@ +// Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. +// http://github.com/gogo/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package sortkeys + +import ( + "sort" +) + +func Strings(l []string) { + sort.Strings(l) +} + +func Float64s(l []float64) { + sort.Float64s(l) +} + +func Float32s(l []float32) { + sort.Sort(Float32Slice(l)) +} + +func Int64s(l []int64) { + sort.Sort(Int64Slice(l)) +} + +func Int32s(l []int32) { + sort.Sort(Int32Slice(l)) +} + +func Uint64s(l []uint64) { + sort.Sort(Uint64Slice(l)) +} + +func Uint32s(l []uint32) { + sort.Sort(Uint32Slice(l)) +} + +func Bools(l []bool) { + sort.Sort(BoolSlice(l)) +} + +type BoolSlice []bool + +func (p BoolSlice) Len() int { return len(p) } +func (p BoolSlice) Less(i, j int) bool { return p[j] } +func (p BoolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Int64Slice []int64 + +func (p Int64Slice) Len() int { return len(p) } +func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] } +func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Int32Slice []int32 + +func (p Int32Slice) Len() int { return len(p) } +func (p Int32Slice) Less(i, j int) bool { return p[i] < p[j] } +func (p Int32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Uint64Slice []uint64 + +func (p Uint64Slice) Len() int { return len(p) } +func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] } +func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Uint32Slice []uint32 + +func (p Uint32Slice) Len() int { return len(p) } +func (p Uint32Slice) Less(i, j int) bool { return p[i] < p[j] } +func (p Uint32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +type Float32Slice []float32 + +func (p Float32Slice) Len() int { return len(p) } +func (p Float32Slice) Less(i, j int) bool { return p[i] < p[j] } +func (p Float32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } diff --git a/vendor/github.com/google/cadvisor/collector/config.go b/vendor/github.com/google/cadvisor/collector/config.go index 637f6406ba2b..75063d93b021 100644 --- a/vendor/github.com/google/cadvisor/collector/config.go +++ b/vendor/github.com/google/cadvisor/collector/config.go @@ -17,12 +17,13 @@ package collector import ( "time" + "encoding/json" "github.com/google/cadvisor/info/v1" ) type Config struct { //the endpoint to hit to scrape metrics - Endpoint string `json:"endpoint"` + Endpoint EndpointConfig `json:"endpoint"` //holds information about different metrics that can be collected MetricsConfig []MetricConfig `json:"metrics_config"` @@ -52,7 +53,7 @@ type MetricConfig struct { type Prometheus struct { //the endpoint to hit to scrape metrics - Endpoint string `json:"endpoint"` + Endpoint EndpointConfig `json:"endpoint"` //the frequency at which metrics should be collected PollingFrequency time.Duration `json:"polling_frequency"` @@ -60,3 +61,40 @@ type Prometheus struct { //holds names of different metrics that can be collected MetricsConfig []string `json:"metrics_config"` } + +type EndpointConfig struct { + // The full URL of the endpoint to reach + URL string + // A configuration in which an actual URL is constructed from, using the container's ip address + URLConfig URLConfig +} + +type URLConfig struct { + // the protocol to use for connecting to the endpoint. Eg 'http' or 'https' + Protocol string `json:"protocol"` + + // the port to use for connecting to the endpoint. Eg '8778' + Port json.Number `json:"port"` + + // the path to use for the endpoint. Eg '/metrics' + Path string `json:"path"` +} + +func (ec *EndpointConfig) UnmarshalJSON(b []byte) error { + url := "" + config := URLConfig{ + Protocol: "http", + Port: "8000", + } + + if err := json.Unmarshal(b, &url); err == nil { + ec.URL = url + return nil + } + err := json.Unmarshal(b, &config) + if err == nil { + ec.URLConfig = config + return nil + } + return err +} diff --git a/vendor/github.com/google/cadvisor/collector/generic_collector.go b/vendor/github.com/google/cadvisor/collector/generic_collector.go index c155da74b50b..73071fc13abe 100644 --- a/vendor/github.com/google/cadvisor/collector/generic_collector.go +++ b/vendor/github.com/google/cadvisor/collector/generic_collector.go @@ -24,6 +24,7 @@ import ( "strings" "time" + "github.com/google/cadvisor/container" "github.com/google/cadvisor/info/v1" ) @@ -51,13 +52,15 @@ type collectorInfo struct { } //Returns a new collector using the information extracted from the configfile -func NewCollector(collectorName string, configFile []byte, metricCountLimit int) (*GenericCollector, error) { +func NewCollector(collectorName string, configFile []byte, metricCountLimit int, containerHandler container.ContainerHandler) (*GenericCollector, error) { var configInJSON Config err := json.Unmarshal(configFile, &configInJSON) if err != nil { return nil, err } + configInJSON.Endpoint.configure(containerHandler) + //TODO : Add checks for validity of config file (eg : Accurate JSON fields) if len(configInJSON.MetricsConfig) == 0 { @@ -130,7 +133,7 @@ func (collector *GenericCollector) Collect(metrics map[string][]v1.MetricVal) (t currentTime := time.Now() nextCollectionTime := currentTime.Add(time.Duration(collector.info.minPollingFrequency)) - uri := collector.configFile.Endpoint + uri := collector.configFile.Endpoint.URL response, err := http.Get(uri) if err != nil { return nextCollectionTime, nil, err diff --git a/vendor/github.com/google/cadvisor/collector/prometheus_collector.go b/vendor/github.com/google/cadvisor/collector/prometheus_collector.go index 0022d026f091..a2beabf64a0d 100644 --- a/vendor/github.com/google/cadvisor/collector/prometheus_collector.go +++ b/vendor/github.com/google/cadvisor/collector/prometheus_collector.go @@ -24,6 +24,7 @@ import ( "strings" "time" + "github.com/google/cadvisor/container" "github.com/google/cadvisor/info/v1" ) @@ -46,13 +47,15 @@ type PrometheusCollector struct { } //Returns a new collector using the information extracted from the configfile -func NewPrometheusCollector(collectorName string, configFile []byte, metricCountLimit int) (*PrometheusCollector, error) { +func NewPrometheusCollector(collectorName string, configFile []byte, metricCountLimit int, containerHandler container.ContainerHandler) (*PrometheusCollector, error) { var configInJSON Prometheus err := json.Unmarshal(configFile, &configInJSON) if err != nil { return nil, err } + configInJSON.Endpoint.configure(containerHandler) + minPollingFrequency := configInJSON.PollingFrequency // Minimum supported frequency is 1s @@ -108,7 +111,7 @@ func getMetricData(line string) string { func (collector *PrometheusCollector) GetSpec() []v1.MetricSpec { specs := []v1.MetricSpec{} - response, err := http.Get(collector.configFile.Endpoint) + response, err := http.Get(collector.configFile.Endpoint.URL) if err != nil { return specs } @@ -153,7 +156,7 @@ func (collector *PrometheusCollector) Collect(metrics map[string][]v1.MetricVal) currentTime := time.Now() nextCollectionTime := currentTime.Add(time.Duration(collector.pollingFrequency)) - uri := collector.configFile.Endpoint + uri := collector.configFile.Endpoint.URL response, err := http.Get(uri) if err != nil { return nextCollectionTime, nil, err diff --git a/vendor/github.com/google/cadvisor/collector/util.go b/vendor/github.com/google/cadvisor/collector/util.go new file mode 100644 index 000000000000..b8814d131fa6 --- /dev/null +++ b/vendor/github.com/google/cadvisor/collector/util.go @@ -0,0 +1,26 @@ +// Copyright 2016 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collector + +import "github.com/google/cadvisor/container" + +func (endpointConfig *EndpointConfig) configure(containerHandler container.ContainerHandler) { + //If the exact URL was not specified, generate it based on the ip address of the container. + endpoint := endpointConfig + if endpoint.URL == "" { + ipAddress := containerHandler.GetContainerIPAddress() + endpointConfig.URL = endpoint.URLConfig.Protocol + "://" + ipAddress + ":" + endpoint.URLConfig.Port.String() + endpoint.URLConfig.Path + } +} diff --git a/vendor/github.com/google/cadvisor/container/container.go b/vendor/github.com/google/cadvisor/container/container.go index c42819da2988..0927d327c6a7 100644 --- a/vendor/github.com/google/cadvisor/container/container.go +++ b/vendor/github.com/google/cadvisor/container/container.go @@ -59,6 +59,9 @@ type ContainerHandler interface { // Returns container labels, if available. GetContainerLabels() map[string]string + // Returns the container's ip address, if available + GetContainerIPAddress() string + // Returns whether the container still exists. Exists() bool diff --git a/vendor/github.com/google/cadvisor/container/docker/handler.go b/vendor/github.com/google/cadvisor/container/docker/handler.go index fd3e2fdc4ba9..c8f4a68e3d13 100644 --- a/vendor/github.com/google/cadvisor/container/docker/handler.go +++ b/vendor/github.com/google/cadvisor/container/docker/handler.go @@ -94,6 +94,9 @@ type dockerContainerHandler struct { // Filesystem handler. fsHandler common.FsHandler + // The IP address of the container + ipAddress string + ignoreMetrics container.MetricSet // thin pool watcher @@ -222,6 +225,22 @@ func newDockerContainerHandler( handler.networkMode = ctnr.HostConfig.NetworkMode handler.deviceID = ctnr.GraphDriver.Data["DeviceId"] + // Obtain the IP address for the contianer. + // If the NetworkMode starts with 'container:' then we need to use the IP address of the container specified. + // This happens in cases such as kubernetes where the containers doesn't have an IP address itself and we need to use the pod's address + ipAddress := ctnr.NetworkSettings.IPAddress + networkMode := string(ctnr.HostConfig.NetworkMode) + if ipAddress == "" && strings.HasPrefix(networkMode, "container:") { + containerId := strings.TrimPrefix(networkMode, "container:") + c, err := client.ContainerInspect(context.Background(), containerId) + if err != nil { + return nil, fmt.Errorf("failed to inspect container %q: %v", id, err) + } + ipAddress = c.NetworkSettings.IPAddress + } + + handler.ipAddress = ipAddress + if !ignoreMetrics.Has(container.DiskUsageMetrics) { handler.fsHandler = &dockerFsHandler{ fsHandler: common.NewFsHandler(time.Minute, rootfsStorageDir, otherStorageDir, fsInfo), @@ -412,6 +431,10 @@ func (self *dockerContainerHandler) GetContainerLabels() map[string]string { return self.labels } +func (self *dockerContainerHandler) GetContainerIPAddress() string { + return self.ipAddress +} + func (self *dockerContainerHandler) ListProcesses(listType container.ListType) ([]int, error) { return containerlibcontainer.GetProcesses(self.cgroupManager) } diff --git a/vendor/github.com/google/cadvisor/container/mock.go b/vendor/github.com/google/cadvisor/container/mock.go deleted file mode 100644 index c6facb319cff..000000000000 --- a/vendor/github.com/google/cadvisor/container/mock.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build test - -package container - -import ( - info "github.com/google/cadvisor/info/v1" - - "github.com/stretchr/testify/mock" -) - -// This struct mocks a container handler. -type MockContainerHandler struct { - mock.Mock - Name string - Aliases []string -} - -func NewMockContainerHandler(containerName string) *MockContainerHandler { - return &MockContainerHandler{ - Name: containerName, - } -} - -// If self.Name is not empty, then ContainerReference() will return self.Name and self.Aliases. -// Otherwise, it will use the value provided by .On().Return(). -func (self *MockContainerHandler) ContainerReference() (info.ContainerReference, error) { - if len(self.Name) > 0 { - var aliases []string - if len(self.Aliases) > 0 { - aliases = make([]string, len(self.Aliases)) - copy(aliases, self.Aliases) - } - return info.ContainerReference{ - Name: self.Name, - Aliases: aliases, - }, nil - } - args := self.Called() - return args.Get(0).(info.ContainerReference), args.Error(1) -} - -func (self *MockContainerHandler) Start() {} - -func (self *MockContainerHandler) Cleanup() {} - -func (self *MockContainerHandler) GetSpec() (info.ContainerSpec, error) { - args := self.Called() - return args.Get(0).(info.ContainerSpec), args.Error(1) -} - -func (self *MockContainerHandler) GetStats() (*info.ContainerStats, error) { - args := self.Called() - return args.Get(0).(*info.ContainerStats), args.Error(1) -} - -func (self *MockContainerHandler) ListContainers(listType ListType) ([]info.ContainerReference, error) { - args := self.Called(listType) - return args.Get(0).([]info.ContainerReference), args.Error(1) -} - -func (self *MockContainerHandler) ListProcesses(listType ListType) ([]int, error) { - args := self.Called(listType) - return args.Get(0).([]int), args.Error(1) -} - -func (self *MockContainerHandler) Exists() bool { - args := self.Called() - return args.Get(0).(bool) -} - -func (self *MockContainerHandler) GetCgroupPath(path string) (string, error) { - args := self.Called(path) - return args.Get(0).(string), args.Error(1) -} - -func (self *MockContainerHandler) GetContainerLabels() map[string]string { - args := self.Called() - return args.Get(0).(map[string]string) -} - -func (self *MockContainerHandler) Type() ContainerType { - args := self.Called() - return args.Get(0).(ContainerType) -} - -type FactoryForMockContainerHandler struct { - Name string - PrepareContainerHandlerFunc func(name string, handler *MockContainerHandler) -} - -func (self *FactoryForMockContainerHandler) String() string { - return self.Name -} - -func (self *FactoryForMockContainerHandler) NewContainerHandler(name string, inHostNamespace bool) (ContainerHandler, error) { - handler := &MockContainerHandler{} - if self.PrepareContainerHandlerFunc != nil { - self.PrepareContainerHandlerFunc(name, handler) - } - return handler, nil -} - -func (self *FactoryForMockContainerHandler) CanHandle(name string) bool { - return true -} diff --git a/vendor/github.com/google/cadvisor/container/raw/handler.go b/vendor/github.com/google/cadvisor/container/raw/handler.go index 7b959acf4a56..29bf7c1e53c7 100644 --- a/vendor/github.com/google/cadvisor/container/raw/handler.go +++ b/vendor/github.com/google/cadvisor/container/raw/handler.go @@ -256,6 +256,11 @@ func (self *rawContainerHandler) GetContainerLabels() map[string]string { return map[string]string{} } +func (self *rawContainerHandler) GetContainerIPAddress() string { + // the IP address for the raw container corresponds to the system ip address. + return "127.0.0.1" +} + func (self *rawContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) { return common.ListContainers(self.name, self.cgroupPaths, listType) } diff --git a/vendor/github.com/google/cadvisor/container/rkt/handler.go b/vendor/github.com/google/cadvisor/container/rkt/handler.go index a6b75652800c..fad91dbec55c 100644 --- a/vendor/github.com/google/cadvisor/container/rkt/handler.go +++ b/vendor/github.com/google/cadvisor/container/rkt/handler.go @@ -250,6 +250,21 @@ func (handler *rktContainerHandler) GetStats() (*info.ContainerStats, error) { return stats, nil } +func (self *rktContainerHandler) GetContainerIPAddress() string { + // attempt to return the ip address of the pod + // if a specific ip address of the pod could not be determined, return the system ip address + if self.isPod && len(self.apiPod.Networks) > 0 { + address := self.apiPod.Networks[0].Ipv4 + if address != "" { + return address + } else { + return self.apiPod.Networks[0].Ipv6 + } + } else { + return "127.0.0.1" + } +} + func (handler *rktContainerHandler) GetCgroupPath(resource string) (string, error) { path, ok := handler.cgroupPaths[resource] if !ok { diff --git a/vendor/github.com/google/cadvisor/fs/fs.go b/vendor/github.com/google/cadvisor/fs/fs.go index dafc7bf70b15..4bc39e52dad7 100644 --- a/vendor/github.com/google/cadvisor/fs/fs.go +++ b/vendor/github.com/google/cadvisor/fs/fs.go @@ -99,46 +99,64 @@ func NewFsInfo(context Context) (FsInfo, error) { if err != nil { return nil, err } + + // Avoid devicemapper container mounts - these are tracked by the ThinPoolWatcher + excluded := []string{fmt.Sprintf("%s/devicemapper/mnt", context.Docker.Root)} fsInfo := &RealFsInfo{ - partitions: make(map[string]partition, 0), + partitions: processMounts(mounts, excluded), labels: make(map[string]string, 0), dmsetup: devicemapper.NewDmsetupClient(), } + fsInfo.addRktImagesLabel(context, mounts) + // need to call this before the log line below printing out the partitions, as this function may + // add a "partition" for devicemapper to fsInfo.partitions + fsInfo.addDockerImagesLabel(context, mounts) + + glog.Infof("Filesystem partitions: %+v", fsInfo.partitions) + fsInfo.addSystemRootLabel(mounts) + return fsInfo, nil +} + +func processMounts(mounts []*mount.Info, excludedMountpointPrefixes []string) map[string]partition { + partitions := make(map[string]partition, 0) + supportedFsType := map[string]bool{ // all ext systems are checked through prefix. "btrfs": true, "xfs": true, "zfs": true, } + for _, mount := range mounts { - var Fstype string if !strings.HasPrefix(mount.Fstype, "ext") && !supportedFsType[mount.Fstype] { continue } // Avoid bind mounts. - if _, ok := fsInfo.partitions[mount.Source]; ok { + if _, ok := partitions[mount.Source]; ok { continue } - if mount.Fstype == "zfs" { - Fstype = mount.Fstype + + hasPrefix := false + for _, prefix := range excludedMountpointPrefixes { + if strings.HasPrefix(mount.Mountpoint, prefix) { + hasPrefix = true + break + } + } + if hasPrefix { + continue } - fsInfo.partitions[mount.Source] = partition{ - fsType: Fstype, + + partitions[mount.Source] = partition{ + fsType: mount.Fstype, mountpoint: mount.Mountpoint, major: uint(mount.Major), minor: uint(mount.Minor), } } - fsInfo.addRktImagesLabel(context, mounts) - // need to call this before the log line below printing out the partitions, as this function may - // add a "partition" for devicemapper to fsInfo.partitions - fsInfo.addDockerImagesLabel(context, mounts) - - glog.Infof("Filesystem partitions: %+v", fsInfo.partitions) - fsInfo.addSystemRootLabel(mounts) - return fsInfo, nil + return partitions } // getDockerDeviceMapperInfo returns information about the devicemapper device and "partition" if diff --git a/vendor/github.com/google/cadvisor/info/v2/container.go b/vendor/github.com/google/cadvisor/info/v2/container.go index d300c525f51d..42d990ff00f4 100644 --- a/vendor/github.com/google/cadvisor/info/v2/container.go +++ b/vendor/github.com/google/cadvisor/info/v2/container.go @@ -216,6 +216,9 @@ type FsInfo struct { // Labels associated with this filesystem. Labels []string `json:"labels"` + + // Number of available Inodes. + InodesFree uint64 `json:"inodes_free"` } type RequestOptions struct { diff --git a/vendor/github.com/google/cadvisor/manager/manager.go b/vendor/github.com/google/cadvisor/manager/manager.go index 7cf7d43b1448..27c388a759fe 100644 --- a/vendor/github.com/google/cadvisor/manager/manager.go +++ b/vendor/github.com/google/cadvisor/manager/manager.go @@ -232,12 +232,12 @@ type manager struct { func (self *manager) Start() error { err := docker.Register(self, self.fsInfo, self.ignoreMetrics) if err != nil { - glog.Errorf("Docker container factory registration failed: %v.", err) + glog.Warningf("Docker container factory registration failed: %v.", err) } err = rkt.Register(self, self.fsInfo, self.ignoreMetrics) if err != nil { - glog.Errorf("Registration of the rkt container factory failed: %v", err) + glog.Warningf("Registration of the rkt container factory failed: %v", err) } else { watcher, err := rktwatcher.NewRktContainerWatcher() if err != nil { @@ -248,7 +248,7 @@ func (self *manager) Start() error { err = systemd.Register(self, self.fsInfo, self.ignoreMetrics) if err != nil { - glog.Errorf("Registration of the systemd container factory failed: %v", err) + glog.Warningf("Registration of the systemd container factory failed: %v", err) } err = raw.Register(self, self.fsInfo, self.ignoreMetrics) @@ -687,6 +687,7 @@ func (self *manager) GetFsInfo(label string) ([]v2.FsInfo, error) { Usage: fs.Usage, Available: fs.Available, Labels: labels, + InodesFree: fs.InodesFree, } fsInfo = append(fsInfo, fi) } @@ -751,7 +752,7 @@ func (m *manager) registerCollectors(collectorConfigs map[string]string, cont *c glog.V(3).Infof("Got config from %q: %q", v, configFile) if strings.HasPrefix(k, "prometheus") || strings.HasPrefix(k, "Prometheus") { - newCollector, err := collector.NewPrometheusCollector(k, configFile, *applicationMetricsCountLimit) + newCollector, err := collector.NewPrometheusCollector(k, configFile, *applicationMetricsCountLimit, cont.handler) if err != nil { glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err) return err @@ -762,7 +763,7 @@ func (m *manager) registerCollectors(collectorConfigs map[string]string, cont *c return err } } else { - newCollector, err := collector.NewCollector(k, configFile, *applicationMetricsCountLimit) + newCollector, err := collector.NewCollector(k, configFile, *applicationMetricsCountLimit, cont.handler) if err != nil { glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err) return err diff --git a/vendor/github.com/google/cadvisor/manager/watcher/raw/raw.go b/vendor/github.com/google/cadvisor/manager/watcher/raw/raw.go index b6f4153920c5..103fa887afec 100644 --- a/vendor/github.com/google/cadvisor/manager/watcher/raw/raw.go +++ b/vendor/github.com/google/cadvisor/manager/watcher/raw/raw.go @@ -19,6 +19,7 @@ package raw import ( "fmt" "io/ioutil" + "os" "path" "strings" @@ -133,9 +134,15 @@ func (self *rawContainerWatcher) watchDirectory(dir string, containerName string } for _, entry := range entries { if entry.IsDir() { - // TODO(vmarmol): We don't have to fail here, maybe we can recover and try to get as many registrations as we can. - _, err = self.watchDirectory(path.Join(dir, entry.Name()), path.Join(containerName, entry.Name())) + entryPath := path.Join(dir, entry.Name()) + _, err = self.watchDirectory(entryPath, path.Join(containerName, entry.Name())) if err != nil { + glog.Errorf("Failed to watch directory %q: %v", entryPath, err) + if os.IsNotExist(err) { + // The directory may have been removed before watching. Try to watch the other + // subdirectories. (https://github.com/kubernetes/kubernetes/issues/28997) + continue + } return alreadyWatching, err } } diff --git a/vendor/github.com/google/cadvisor/utils/cloudinfo/gce.go b/vendor/github.com/google/cadvisor/utils/cloudinfo/gce.go index 0d044d6258b0..4c2e330dfeac 100644 --- a/vendor/github.com/google/cadvisor/utils/cloudinfo/gce.go +++ b/vendor/github.com/google/cadvisor/utils/cloudinfo/gce.go @@ -15,15 +15,27 @@ package cloudinfo import ( + "io/ioutil" "strings" info "github.com/google/cadvisor/info/v1" + "github.com/golang/glog" "google.golang.org/cloud/compute/metadata" ) +const ( + gceProductName = "/sys/class/dmi/id/product_name" + google = "Google" +) + func onGCE() bool { - return metadata.OnGCE() + data, err := ioutil.ReadFile(gceProductName) + if err != nil { + glog.V(2).Infof("Error while reading product_name: %v", err) + return false + } + return strings.Contains(string(data), google) } func getGceInstanceType() info.InstanceType { diff --git a/vendor/github.com/google/cadvisor/version/VERSION b/vendor/github.com/google/cadvisor/version/VERSION deleted file mode 100644 index 40a6dfede5db..000000000000 --- a/vendor/github.com/google/cadvisor/version/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.23.4 diff --git a/vendor/github.com/google/certificate-transparency/LICENSE b/vendor/github.com/google/certificate-transparency/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/LICENSE @@ -0,0 +1,202 @@ + + 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/google/certificate-transparency/go/README.md b/vendor/github.com/google/certificate-transparency/go/README.md new file mode 100644 index 000000000000..82c5d1b3afd6 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/README.md @@ -0,0 +1,25 @@ +This is the really early beginnings of a certificate transparency log +client written in Go, along with a log scanner tool. + +You'll need go v1.1 or higher to compile. + +# Installation + +This go code must be imported into your go workspace before you can +use it, which can be done with: + + go get github.com/google/certificate-transparency/go/client + go get github.com/google/certificate-transparency/go/scanner + etc. + +# Building the binaries + +To compile the log scanner run: + + go build github.com/google/certificate-transparency/go/scanner/main/scanner.go + +# Contributing + +When sending pull requests, please ensure that everything's been run +through ```gofmt``` beforehand so we can keep everything nice and +tidy. diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go b/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go new file mode 100755 index 000000000000..e9874779523e --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go @@ -0,0 +1,956 @@ +// Copyright 2009 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 asn1 implements parsing of DER-encoded ASN.1 data structures, +// as defined in ITU-T Rec X.690. +// +// See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' +// http://luca.ntop.org/Teaching/Appunti/asn1.html. +// +// START CT CHANGES +// This is a fork of the Go standard library ASN.1 implementation +// (encoding/asn1). The main difference is that this version tries to correct +// for errors (e.g. use of tagPrintableString when the string data is really +// ISO8859-1 - a common error present in many x509 certificates in the wild.) +// END CT CHANGES +package asn1 + +// ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc +// are different encoding formats for those objects. Here, we'll be dealing +// with DER, the Distinguished Encoding Rules. DER is used in X.509 because +// it's fast to parse and, unlike BER, has a unique encoding for every object. +// When calculating hashes over objects, it's important that the resulting +// bytes be the same at both ends and DER removes this margin of error. +// +// ASN.1 is very complex and this package doesn't attempt to implement +// everything by any means. + +import ( + // START CT CHANGES + "errors" + "fmt" + // END CT CHANGES + "math/big" + "reflect" + // START CT CHANGES + "strings" + // END CT CHANGES + "time" +) + +// A StructuralError suggests that the ASN.1 data is valid, but the Go type +// which is receiving it doesn't match. +type StructuralError struct { + Msg string +} + +func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg } + +// A SyntaxError suggests that the ASN.1 data is invalid. +type SyntaxError struct { + Msg string +} + +func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg } + +// We start by dealing with each of the primitive types in turn. + +// BOOLEAN + +func parseBool(bytes []byte) (ret bool, err error) { + if len(bytes) != 1 { + err = SyntaxError{"invalid boolean"} + return + } + + // DER demands that "If the encoding represents the boolean value TRUE, + // its single contents octet shall have all eight bits set to one." + // Thus only 0 and 255 are valid encoded values. + switch bytes[0] { + case 0: + ret = false + case 0xff: + ret = true + default: + err = SyntaxError{"invalid boolean"} + } + + return +} + +// INTEGER + +// parseInt64 treats the given bytes as a big-endian, signed integer and +// returns the result. +func parseInt64(bytes []byte) (ret int64, err error) { + if len(bytes) > 8 { + // We'll overflow an int64 in this case. + err = StructuralError{"integer too large"} + return + } + for bytesRead := 0; bytesRead < len(bytes); bytesRead++ { + ret <<= 8 + ret |= int64(bytes[bytesRead]) + } + + // Shift up and down in order to sign extend the result. + ret <<= 64 - uint8(len(bytes))*8 + ret >>= 64 - uint8(len(bytes))*8 + return +} + +// parseInt treats the given bytes as a big-endian, signed integer and returns +// the result. +func parseInt32(bytes []byte) (int32, error) { + ret64, err := parseInt64(bytes) + if err != nil { + return 0, err + } + if ret64 != int64(int32(ret64)) { + return 0, StructuralError{"integer too large"} + } + return int32(ret64), nil +} + +var bigOne = big.NewInt(1) + +// parseBigInt treats the given bytes as a big-endian, signed integer and returns +// the result. +func parseBigInt(bytes []byte) *big.Int { + ret := new(big.Int) + if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { + // This is a negative number. + notBytes := make([]byte, len(bytes)) + for i := range notBytes { + notBytes[i] = ^bytes[i] + } + ret.SetBytes(notBytes) + ret.Add(ret, bigOne) + ret.Neg(ret) + return ret + } + ret.SetBytes(bytes) + return ret +} + +// BIT STRING + +// BitString is the structure to use when you want an ASN.1 BIT STRING type. A +// bit string is padded up to the nearest byte in memory and the number of +// valid bits is recorded. Padding bits will be zero. +type BitString struct { + Bytes []byte // bits packed into bytes. + BitLength int // length in bits. +} + +// At returns the bit at the given index. If the index is out of range it +// returns false. +func (b BitString) At(i int) int { + if i < 0 || i >= b.BitLength { + return 0 + } + x := i / 8 + y := 7 - uint(i%8) + return int(b.Bytes[x]>>y) & 1 +} + +// RightAlign returns a slice where the padding bits are at the beginning. The +// slice may share memory with the BitString. +func (b BitString) RightAlign() []byte { + shift := uint(8 - (b.BitLength % 8)) + if shift == 8 || len(b.Bytes) == 0 { + return b.Bytes + } + + a := make([]byte, len(b.Bytes)) + a[0] = b.Bytes[0] >> shift + for i := 1; i < len(b.Bytes); i++ { + a[i] = b.Bytes[i-1] << (8 - shift) + a[i] |= b.Bytes[i] >> shift + } + + return a +} + +// parseBitString parses an ASN.1 bit string from the given byte slice and returns it. +func parseBitString(bytes []byte) (ret BitString, err error) { + if len(bytes) == 0 { + err = SyntaxError{"zero length BIT STRING"} + return + } + paddingBits := int(bytes[0]) + if paddingBits > 7 || + len(bytes) == 1 && paddingBits > 0 || + bytes[len(bytes)-1]&((1< 4 { + err = StructuralError{"base 128 integer too large"} + return + } + ret <<= 7 + b := bytes[offset] + ret |= int(b & 0x7f) + offset++ + if b&0x80 == 0 { + return + } + } + err = SyntaxError{"truncated base 128 integer"} + return +} + +// UTCTime + +func parseUTCTime(bytes []byte) (ret time.Time, err error) { + s := string(bytes) + ret, err = time.Parse("0601021504Z0700", s) + if err != nil { + ret, err = time.Parse("060102150405Z0700", s) + } + if err == nil && ret.Year() >= 2050 { + // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 + ret = ret.AddDate(-100, 0, 0) + } + + return +} + +// parseGeneralizedTime parses the GeneralizedTime from the given byte slice +// and returns the resulting time. +func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) { + return time.Parse("20060102150405Z0700", string(bytes)) +} + +// PrintableString + +// parsePrintableString parses a ASN.1 PrintableString from the given byte +// array and returns it. +func parsePrintableString(bytes []byte) (ret string, err error) { + for _, b := range bytes { + if !isPrintable(b) { + err = SyntaxError{"PrintableString contains invalid character"} + return + } + } + ret = string(bytes) + return +} + +// isPrintable returns true iff the given b is in the ASN.1 PrintableString set. +func isPrintable(b byte) bool { + return 'a' <= b && b <= 'z' || + 'A' <= b && b <= 'Z' || + '0' <= b && b <= '9' || + '\'' <= b && b <= ')' || + '+' <= b && b <= '/' || + b == ' ' || + b == ':' || + b == '=' || + b == '?' || + // This is technically not allowed in a PrintableString. + // However, x509 certificates with wildcard strings don't + // always use the correct string type so we permit it. + b == '*' +} + +// IA5String + +// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given +// byte slice and returns it. +func parseIA5String(bytes []byte) (ret string, err error) { + for _, b := range bytes { + if b >= 0x80 { + err = SyntaxError{"IA5String contains invalid character"} + return + } + } + ret = string(bytes) + return +} + +// T61String + +// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given +// byte slice and returns it. +func parseT61String(bytes []byte) (ret string, err error) { + return string(bytes), nil +} + +// UTF8String + +// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte +// array and returns it. +func parseUTF8String(bytes []byte) (ret string, err error) { + return string(bytes), nil +} + +// A RawValue represents an undecoded ASN.1 object. +type RawValue struct { + Class, Tag int + IsCompound bool + Bytes []byte + FullBytes []byte // includes the tag and length +} + +// RawContent is used to signal that the undecoded, DER data needs to be +// preserved for a struct. To use it, the first field of the struct must have +// this type. It's an error for any of the other fields to have this type. +type RawContent []byte + +// Tagging + +// parseTagAndLength parses an ASN.1 tag and length pair from the given offset +// into a byte slice. It returns the parsed data and the new offset. SET and +// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we +// don't distinguish between ordered and unordered objects in this code. +func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) { + offset = initOffset + b := bytes[offset] + offset++ + ret.class = int(b >> 6) + ret.isCompound = b&0x20 == 0x20 + ret.tag = int(b & 0x1f) + + // If the bottom five bits are set, then the tag number is actually base 128 + // encoded afterwards + if ret.tag == 0x1f { + ret.tag, offset, err = parseBase128Int(bytes, offset) + if err != nil { + return + } + } + if offset >= len(bytes) { + err = SyntaxError{"truncated tag or length"} + return + } + b = bytes[offset] + offset++ + if b&0x80 == 0 { + // The length is encoded in the bottom 7 bits. + ret.length = int(b & 0x7f) + } else { + // Bottom 7 bits give the number of length bytes to follow. + numBytes := int(b & 0x7f) + if numBytes == 0 { + err = SyntaxError{"indefinite length found (not DER)"} + return + } + ret.length = 0 + for i := 0; i < numBytes; i++ { + if offset >= len(bytes) { + err = SyntaxError{"truncated tag or length"} + return + } + b = bytes[offset] + offset++ + if ret.length >= 1<<23 { + // We can't shift ret.length up without + // overflowing. + err = StructuralError{"length too large"} + return + } + ret.length <<= 8 + ret.length |= int(b) + if ret.length == 0 { + // DER requires that lengths be minimal. + err = StructuralError{"superfluous leading zeros in length"} + return + } + } + } + + return +} + +// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse +// a number of ASN.1 values from the given byte slice and returns them as a +// slice of Go values of the given type. +func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { + expectedTag, compoundType, ok := getUniversalType(elemType) + if !ok { + err = StructuralError{"unknown Go type for slice"} + return + } + + // First we iterate over the input and count the number of elements, + // checking that the types are correct in each case. + numElements := 0 + for offset := 0; offset < len(bytes); { + var t tagAndLength + t, offset, err = parseTagAndLength(bytes, offset) + if err != nil { + return + } + // We pretend that GENERAL STRINGs are PRINTABLE STRINGs so + // that a sequence of them can be parsed into a []string. + if t.tag == tagGeneralString { + t.tag = tagPrintableString + } + if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag { + err = StructuralError{"sequence tag mismatch"} + return + } + if invalidLength(offset, t.length, len(bytes)) { + err = SyntaxError{"truncated sequence"} + return + } + offset += t.length + numElements++ + } + ret = reflect.MakeSlice(sliceType, numElements, numElements) + params := fieldParameters{} + offset := 0 + for i := 0; i < numElements; i++ { + offset, err = parseField(ret.Index(i), bytes, offset, params) + if err != nil { + return + } + } + return +} + +var ( + bitStringType = reflect.TypeOf(BitString{}) + objectIdentifierType = reflect.TypeOf(ObjectIdentifier{}) + enumeratedType = reflect.TypeOf(Enumerated(0)) + flagType = reflect.TypeOf(Flag(false)) + timeType = reflect.TypeOf(time.Time{}) + rawValueType = reflect.TypeOf(RawValue{}) + rawContentsType = reflect.TypeOf(RawContent(nil)) + bigIntType = reflect.TypeOf(new(big.Int)) +) + +// invalidLength returns true iff offset + length > sliceLength, or if the +// addition would overflow. +func invalidLength(offset, length, sliceLength int) bool { + return offset+length < offset || offset+length > sliceLength +} + +// START CT CHANGES + +// Tests whether the data in |bytes| would be a valid ISO8859-1 string. +// Clearly, a sequence of bytes comprised solely of valid ISO8859-1 +// codepoints does not imply that the encoding MUST be ISO8859-1, rather that +// you would not encounter an error trying to interpret the data as such. +func couldBeISO8859_1(bytes []byte) bool { + for _, b := range bytes { + if b < 0x20 || (b >= 0x7F && b < 0xA0) { + return false + } + } + return true +} + +// Checks whether the data in |bytes| would be a valid T.61 string. +// Clearly, a sequence of bytes comprised solely of valid T.61 +// codepoints does not imply that the encoding MUST be T.61, rather that +// you would not encounter an error trying to interpret the data as such. +func couldBeT61(bytes []byte) bool { + for _, b := range bytes { + switch b { + case 0x00: + // Since we're guessing at (incorrect) encodings for a + // PrintableString, we'll err on the side of caution and disallow + // strings with a NUL in them, don't want to re-create a PayPal NUL + // situation in monitors. + fallthrough + case 0x23, 0x24, 0x5C, 0x5E, 0x60, 0x7B, 0x7D, 0x7E, 0xA5, 0xA6, 0xAC, 0xAD, 0xAE, 0xAF, + 0xB9, 0xBA, 0xC0, 0xC9, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, + 0xDA, 0xDB, 0xDC, 0xDE, 0xDF, 0xE5, 0xFF: + // These are all invalid code points in T.61, so it can't be a T.61 string. + return false + } + } + return true +} + +// Converts the data in |bytes| to the equivalent UTF-8 string. +func iso8859_1ToUTF8(bytes []byte) string { + buf := make([]rune, len(bytes)) + for i, b := range bytes { + buf[i] = rune(b) + } + return string(buf) +} + +// END CT CHANGES + +// parseField is the main parsing function. Given a byte slice and an offset +// into the array, it will try to parse a suitable ASN.1 value out and store it +// in the given Value. +func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { + offset = initOffset + fieldType := v.Type() + + // If we have run out of data, it may be that there are optional elements at the end. + if offset == len(bytes) { + if !setDefaultValue(v, params) { + err = SyntaxError{"sequence truncated"} + } + return + } + + // Deal with raw values. + if fieldType == rawValueType { + var t tagAndLength + t, offset, err = parseTagAndLength(bytes, offset) + if err != nil { + return + } + if invalidLength(offset, t.length, len(bytes)) { + err = SyntaxError{"data truncated"} + return + } + result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]} + offset += t.length + v.Set(reflect.ValueOf(result)) + return + } + + // Deal with the ANY type. + if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 { + var t tagAndLength + t, offset, err = parseTagAndLength(bytes, offset) + if err != nil { + return + } + if invalidLength(offset, t.length, len(bytes)) { + err = SyntaxError{"data truncated"} + return + } + var result interface{} + if !t.isCompound && t.class == classUniversal { + innerBytes := bytes[offset : offset+t.length] + switch t.tag { + case tagPrintableString: + result, err = parsePrintableString(innerBytes) + // START CT CHANGES + if err != nil && strings.Contains(err.Error(), "PrintableString contains invalid character") { + // Probably an ISO8859-1 string stuffed in, check if it + // would be valid and assume that's what's happened if so, + // otherwise try T.61, failing that give up and just assign + // the bytes + switch { + case couldBeISO8859_1(innerBytes): + result, err = iso8859_1ToUTF8(innerBytes), nil + case couldBeT61(innerBytes): + result, err = parseT61String(innerBytes) + default: + result = nil + err = errors.New("PrintableString contains invalid character, but couldn't determine correct String type.") + } + } + // END CT CHANGES + case tagIA5String: + result, err = parseIA5String(innerBytes) + case tagT61String: + result, err = parseT61String(innerBytes) + case tagUTF8String: + result, err = parseUTF8String(innerBytes) + case tagInteger: + result, err = parseInt64(innerBytes) + case tagBitString: + result, err = parseBitString(innerBytes) + case tagOID: + result, err = parseObjectIdentifier(innerBytes) + case tagUTCTime: + result, err = parseUTCTime(innerBytes) + case tagOctetString: + result = innerBytes + default: + // If we don't know how to handle the type, we just leave Value as nil. + } + } + offset += t.length + if err != nil { + return + } + if result != nil { + v.Set(reflect.ValueOf(result)) + } + return + } + universalTag, compoundType, ok1 := getUniversalType(fieldType) + if !ok1 { + err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)} + return + } + + t, offset, err := parseTagAndLength(bytes, offset) + if err != nil { + return + } + if params.explicit { + expectedClass := classContextSpecific + if params.application { + expectedClass = classApplication + } + if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { + if t.length > 0 { + t, offset, err = parseTagAndLength(bytes, offset) + if err != nil { + return + } + } else { + if fieldType != flagType { + err = StructuralError{"zero length explicit tag was not an asn1.Flag"} + return + } + v.SetBool(true) + return + } + } else { + // The tags didn't match, it might be an optional element. + ok := setDefaultValue(v, params) + if ok { + offset = initOffset + } else { + err = StructuralError{"explicitly tagged member didn't match"} + } + return + } + } + + // Special case for strings: all the ASN.1 string types map to the Go + // type string. getUniversalType returns the tag for PrintableString + // when it sees a string, so if we see a different string type on the + // wire, we change the universal type to match. + if universalTag == tagPrintableString { + switch t.tag { + case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: + universalTag = t.tag + } + } + + // Special case for time: UTCTime and GeneralizedTime both map to the + // Go type time.Time. + if universalTag == tagUTCTime && t.tag == tagGeneralizedTime { + universalTag = tagGeneralizedTime + } + + expectedClass := classUniversal + expectedTag := universalTag + + if !params.explicit && params.tag != nil { + expectedClass = classContextSpecific + expectedTag = *params.tag + } + + if !params.explicit && params.application && params.tag != nil { + expectedClass = classApplication + expectedTag = *params.tag + } + + // We have unwrapped any explicit tagging at this point. + if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { + // Tags don't match. Again, it could be an optional element. + ok := setDefaultValue(v, params) + if ok { + offset = initOffset + } else { + err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} + } + return + } + if invalidLength(offset, t.length, len(bytes)) { + err = SyntaxError{"data truncated"} + return + } + innerBytes := bytes[offset : offset+t.length] + offset += t.length + + // We deal with the structures defined in this package first. + switch fieldType { + case objectIdentifierType: + newSlice, err1 := parseObjectIdentifier(innerBytes) + v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) + if err1 == nil { + reflect.Copy(v, reflect.ValueOf(newSlice)) + } + err = err1 + return + case bitStringType: + bs, err1 := parseBitString(innerBytes) + if err1 == nil { + v.Set(reflect.ValueOf(bs)) + } + err = err1 + return + case timeType: + var time time.Time + var err1 error + if universalTag == tagUTCTime { + time, err1 = parseUTCTime(innerBytes) + } else { + time, err1 = parseGeneralizedTime(innerBytes) + } + if err1 == nil { + v.Set(reflect.ValueOf(time)) + } + err = err1 + return + case enumeratedType: + parsedInt, err1 := parseInt32(innerBytes) + if err1 == nil { + v.SetInt(int64(parsedInt)) + } + err = err1 + return + case flagType: + v.SetBool(true) + return + case bigIntType: + parsedInt := parseBigInt(innerBytes) + v.Set(reflect.ValueOf(parsedInt)) + return + } + switch val := v; val.Kind() { + case reflect.Bool: + parsedBool, err1 := parseBool(innerBytes) + if err1 == nil { + val.SetBool(parsedBool) + } + err = err1 + return + case reflect.Int, reflect.Int32, reflect.Int64: + if val.Type().Size() == 4 { + parsedInt, err1 := parseInt32(innerBytes) + if err1 == nil { + val.SetInt(int64(parsedInt)) + } + err = err1 + } else { + parsedInt, err1 := parseInt64(innerBytes) + if err1 == nil { + val.SetInt(parsedInt) + } + err = err1 + } + return + // TODO(dfc) Add support for the remaining integer types + case reflect.Struct: + structType := fieldType + + if structType.NumField() > 0 && + structType.Field(0).Type == rawContentsType { + bytes := bytes[initOffset:offset] + val.Field(0).Set(reflect.ValueOf(RawContent(bytes))) + } + + innerOffset := 0 + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + if i == 0 && field.Type == rawContentsType { + continue + } + innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) + if err != nil { + return + } + } + // We allow extra bytes at the end of the SEQUENCE because + // adding elements to the end has been used in X.509 as the + // version numbers have increased. + return + case reflect.Slice: + sliceType := fieldType + if sliceType.Elem().Kind() == reflect.Uint8 { + val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) + reflect.Copy(val, reflect.ValueOf(innerBytes)) + return + } + newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) + if err1 == nil { + val.Set(newSlice) + } + err = err1 + return + case reflect.String: + var v string + switch universalTag { + case tagPrintableString: + v, err = parsePrintableString(innerBytes) + case tagIA5String: + v, err = parseIA5String(innerBytes) + case tagT61String: + v, err = parseT61String(innerBytes) + case tagUTF8String: + v, err = parseUTF8String(innerBytes) + case tagGeneralString: + // GeneralString is specified in ISO-2022/ECMA-35, + // A brief review suggests that it includes structures + // that allow the encoding to change midstring and + // such. We give up and pass it as an 8-bit string. + v, err = parseT61String(innerBytes) + default: + err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)} + } + if err == nil { + val.SetString(v) + } + return + } + err = StructuralError{"unsupported: " + v.Type().String()} + return +} + +// setDefaultValue is used to install a default value, from a tag string, into +// a Value. It is successful is the field was optional, even if a default value +// wasn't provided or it failed to install it into the Value. +func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { + if !params.optional { + return + } + ok = true + if params.defaultValue == nil { + return + } + switch val := v; val.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + val.SetInt(*params.defaultValue) + } + return +} + +// Unmarshal parses the DER-encoded ASN.1 data structure b +// and uses the reflect package to fill in an arbitrary value pointed at by val. +// Because Unmarshal uses the reflect package, the structs +// being written to must use upper case field names. +// +// An ASN.1 INTEGER can be written to an int, int32, int64, +// or *big.Int (from the math/big package). +// If the encoded value does not fit in the Go type, +// Unmarshal returns a parse error. +// +// An ASN.1 BIT STRING can be written to a BitString. +// +// An ASN.1 OCTET STRING can be written to a []byte. +// +// An ASN.1 OBJECT IDENTIFIER can be written to an +// ObjectIdentifier. +// +// An ASN.1 ENUMERATED can be written to an Enumerated. +// +// An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. +// +// An ASN.1 PrintableString or IA5String can be written to a string. +// +// Any of the above ASN.1 values can be written to an interface{}. +// The value stored in the interface has the corresponding Go type. +// For integers, that type is int64. +// +// An ASN.1 SEQUENCE OF x or SET OF x can be written +// to a slice if an x can be written to the slice's element type. +// +// An ASN.1 SEQUENCE or SET can be written to a struct +// if each of the elements in the sequence can be +// written to the corresponding element in the struct. +// +// The following tags on struct fields have special meaning to Unmarshal: +// +// optional marks the field as ASN.1 OPTIONAL +// [explicit] tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC +// default:x sets the default value for optional integer fields +// +// If the type of the first field of a structure is RawContent then the raw +// ASN1 contents of the struct will be stored in it. +// +// Other ASN.1 types are not supported; if it encounters them, +// Unmarshal returns a parse error. +func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { + return UnmarshalWithParams(b, val, "") +} + +// UnmarshalWithParams allows field parameters to be specified for the +// top-level element. The form of the params is the same as the field tags. +func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { + v := reflect.ValueOf(val).Elem() + offset, err := parseField(v, b, 0, parseFieldParameters(params)) + if err != nil { + return nil, err + } + return b[offset:], nil +} diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/common.go b/vendor/github.com/google/certificate-transparency/go/asn1/common.go new file mode 100755 index 000000000000..33a117ece195 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/asn1/common.go @@ -0,0 +1,163 @@ +// Copyright 2009 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 asn1 + +import ( + "reflect" + "strconv" + "strings" +) + +// ASN.1 objects have metadata preceding them: +// the tag: the type of the object +// a flag denoting if this object is compound or not +// the class type: the namespace of the tag +// the length of the object, in bytes + +// Here are some standard tags and classes + +const ( + tagBoolean = 1 + tagInteger = 2 + tagBitString = 3 + tagOctetString = 4 + tagOID = 6 + tagEnum = 10 + tagUTF8String = 12 + tagSequence = 16 + tagSet = 17 + tagPrintableString = 19 + tagT61String = 20 + tagIA5String = 22 + tagUTCTime = 23 + tagGeneralizedTime = 24 + tagGeneralString = 27 +) + +const ( + classUniversal = 0 + classApplication = 1 + classContextSpecific = 2 + classPrivate = 3 +) + +type tagAndLength struct { + class, tag, length int + isCompound bool +} + +// ASN.1 has IMPLICIT and EXPLICIT tags, which can be translated as "instead +// of" and "in addition to". When not specified, every primitive type has a +// default tag in the UNIVERSAL class. +// +// For example: a BIT STRING is tagged [UNIVERSAL 3] by default (although ASN.1 +// doesn't actually have a UNIVERSAL keyword). However, by saying [IMPLICIT +// CONTEXT-SPECIFIC 42], that means that the tag is replaced by another. +// +// On the other hand, if it said [EXPLICIT CONTEXT-SPECIFIC 10], then an +// /additional/ tag would wrap the default tag. This explicit tag will have the +// compound flag set. +// +// (This is used in order to remove ambiguity with optional elements.) +// +// You can layer EXPLICIT and IMPLICIT tags to an arbitrary depth, however we +// don't support that here. We support a single layer of EXPLICIT or IMPLICIT +// tagging with tag strings on the fields of a structure. + +// fieldParameters is the parsed representation of tag string from a structure field. +type fieldParameters struct { + optional bool // true iff the field is OPTIONAL + explicit bool // true iff an EXPLICIT tag is in use. + application bool // true iff an APPLICATION tag is in use. + defaultValue *int64 // a default value for INTEGER typed fields (maybe nil). + tag *int // the EXPLICIT or IMPLICIT tag (maybe nil). + stringType int // the string tag to use when marshaling. + set bool // true iff this should be encoded as a SET + omitEmpty bool // true iff this should be omitted if empty when marshaling. + + // Invariants: + // if explicit is set, tag is non-nil. +} + +// Given a tag string with the format specified in the package comment, +// parseFieldParameters will parse it into a fieldParameters structure, +// ignoring unknown parts of the string. +func parseFieldParameters(str string) (ret fieldParameters) { + for _, part := range strings.Split(str, ",") { + switch { + case part == "optional": + ret.optional = true + case part == "explicit": + ret.explicit = true + if ret.tag == nil { + ret.tag = new(int) + } + case part == "ia5": + ret.stringType = tagIA5String + case part == "printable": + ret.stringType = tagPrintableString + case part == "utf8": + ret.stringType = tagUTF8String + case strings.HasPrefix(part, "default:"): + i, err := strconv.ParseInt(part[8:], 10, 64) + if err == nil { + ret.defaultValue = new(int64) + *ret.defaultValue = i + } + case strings.HasPrefix(part, "tag:"): + i, err := strconv.Atoi(part[4:]) + if err == nil { + ret.tag = new(int) + *ret.tag = i + } + case part == "set": + ret.set = true + case part == "application": + ret.application = true + if ret.tag == nil { + ret.tag = new(int) + } + case part == "omitempty": + ret.omitEmpty = true + } + } + return +} + +// Given a reflected Go type, getUniversalType returns the default tag number +// and expected compound flag. +func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) { + switch t { + case objectIdentifierType: + return tagOID, false, true + case bitStringType: + return tagBitString, false, true + case timeType: + return tagUTCTime, false, true + case enumeratedType: + return tagEnum, false, true + case bigIntType: + return tagInteger, false, true + } + switch t.Kind() { + case reflect.Bool: + return tagBoolean, false, true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return tagInteger, false, true + case reflect.Struct: + return tagSequence, true, true + case reflect.Slice: + if t.Elem().Kind() == reflect.Uint8 { + return tagOctetString, false, true + } + if strings.HasSuffix(t.Name(), "SET") { + return tagSet, true, true + } + return tagSequence, true, true + case reflect.String: + return tagPrintableString, false, true + } + return 0, false, false +} diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go b/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go new file mode 100755 index 000000000000..ed17e41a55cf --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go @@ -0,0 +1,581 @@ +// Copyright 2009 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 asn1 + +import ( + "bytes" + "errors" + "fmt" + "io" + "math/big" + "reflect" + "time" + "unicode/utf8" +) + +// A forkableWriter is an in-memory buffer that can be +// 'forked' to create new forkableWriters that bracket the +// original. After +// pre, post := w.fork(); +// the overall sequence of bytes represented is logically w+pre+post. +type forkableWriter struct { + *bytes.Buffer + pre, post *forkableWriter +} + +func newForkableWriter() *forkableWriter { + return &forkableWriter{new(bytes.Buffer), nil, nil} +} + +func (f *forkableWriter) fork() (pre, post *forkableWriter) { + if f.pre != nil || f.post != nil { + panic("have already forked") + } + f.pre = newForkableWriter() + f.post = newForkableWriter() + return f.pre, f.post +} + +func (f *forkableWriter) Len() (l int) { + l += f.Buffer.Len() + if f.pre != nil { + l += f.pre.Len() + } + if f.post != nil { + l += f.post.Len() + } + return +} + +func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) { + n, err = out.Write(f.Bytes()) + if err != nil { + return + } + + var nn int + + if f.pre != nil { + nn, err = f.pre.writeTo(out) + n += nn + if err != nil { + return + } + } + + if f.post != nil { + nn, err = f.post.writeTo(out) + n += nn + } + return +} + +func marshalBase128Int(out *forkableWriter, n int64) (err error) { + if n == 0 { + err = out.WriteByte(0) + return + } + + l := 0 + for i := n; i > 0; i >>= 7 { + l++ + } + + for i := l - 1; i >= 0; i-- { + o := byte(n >> uint(i*7)) + o &= 0x7f + if i != 0 { + o |= 0x80 + } + err = out.WriteByte(o) + if err != nil { + return + } + } + + return nil +} + +func marshalInt64(out *forkableWriter, i int64) (err error) { + n := int64Length(i) + + for ; n > 0; n-- { + err = out.WriteByte(byte(i >> uint((n-1)*8))) + if err != nil { + return + } + } + + return nil +} + +func int64Length(i int64) (numBytes int) { + numBytes = 1 + + for i > 127 { + numBytes++ + i >>= 8 + } + + for i < -128 { + numBytes++ + i >>= 8 + } + + return +} + +func marshalBigInt(out *forkableWriter, n *big.Int) (err error) { + if n.Sign() < 0 { + // A negative number has to be converted to two's-complement + // form. So we'll subtract 1 and invert. If the + // most-significant-bit isn't set then we'll need to pad the + // beginning with 0xff in order to keep the number negative. + nMinus1 := new(big.Int).Neg(n) + nMinus1.Sub(nMinus1, bigOne) + bytes := nMinus1.Bytes() + for i := range bytes { + bytes[i] ^= 0xff + } + if len(bytes) == 0 || bytes[0]&0x80 == 0 { + err = out.WriteByte(0xff) + if err != nil { + return + } + } + _, err = out.Write(bytes) + } else if n.Sign() == 0 { + // Zero is written as a single 0 zero rather than no bytes. + err = out.WriteByte(0x00) + } else { + bytes := n.Bytes() + if len(bytes) > 0 && bytes[0]&0x80 != 0 { + // We'll have to pad this with 0x00 in order to stop it + // looking like a negative number. + err = out.WriteByte(0) + if err != nil { + return + } + } + _, err = out.Write(bytes) + } + return +} + +func marshalLength(out *forkableWriter, i int) (err error) { + n := lengthLength(i) + + for ; n > 0; n-- { + err = out.WriteByte(byte(i >> uint((n-1)*8))) + if err != nil { + return + } + } + + return nil +} + +func lengthLength(i int) (numBytes int) { + numBytes = 1 + for i > 255 { + numBytes++ + i >>= 8 + } + return +} + +func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) { + b := uint8(t.class) << 6 + if t.isCompound { + b |= 0x20 + } + if t.tag >= 31 { + b |= 0x1f + err = out.WriteByte(b) + if err != nil { + return + } + err = marshalBase128Int(out, int64(t.tag)) + if err != nil { + return + } + } else { + b |= uint8(t.tag) + err = out.WriteByte(b) + if err != nil { + return + } + } + + if t.length >= 128 { + l := lengthLength(t.length) + err = out.WriteByte(0x80 | byte(l)) + if err != nil { + return + } + err = marshalLength(out, t.length) + if err != nil { + return + } + } else { + err = out.WriteByte(byte(t.length)) + if err != nil { + return + } + } + + return nil +} + +func marshalBitString(out *forkableWriter, b BitString) (err error) { + paddingBits := byte((8 - b.BitLength%8) % 8) + err = out.WriteByte(paddingBits) + if err != nil { + return + } + _, err = out.Write(b.Bytes) + return +} + +func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) { + if len(oid) < 2 || oid[0] > 2 || (oid[0] < 2 && oid[1] >= 40) { + return StructuralError{"invalid object identifier"} + } + + err = marshalBase128Int(out, int64(oid[0]*40+oid[1])) + if err != nil { + return + } + for i := 2; i < len(oid); i++ { + err = marshalBase128Int(out, int64(oid[i])) + if err != nil { + return + } + } + + return +} + +func marshalPrintableString(out *forkableWriter, s string) (err error) { + b := []byte(s) + for _, c := range b { + if !isPrintable(c) { + return StructuralError{"PrintableString contains invalid character"} + } + } + + _, err = out.Write(b) + return +} + +func marshalIA5String(out *forkableWriter, s string) (err error) { + b := []byte(s) + for _, c := range b { + if c > 127 { + return StructuralError{"IA5String contains invalid character"} + } + } + + _, err = out.Write(b) + return +} + +func marshalUTF8String(out *forkableWriter, s string) (err error) { + _, err = out.Write([]byte(s)) + return +} + +func marshalTwoDigits(out *forkableWriter, v int) (err error) { + err = out.WriteByte(byte('0' + (v/10)%10)) + if err != nil { + return + } + return out.WriteByte(byte('0' + v%10)) +} + +func marshalUTCTime(out *forkableWriter, t time.Time) (err error) { + year, month, day := t.Date() + + switch { + case 1950 <= year && year < 2000: + err = marshalTwoDigits(out, int(year-1900)) + case 2000 <= year && year < 2050: + err = marshalTwoDigits(out, int(year-2000)) + default: + return StructuralError{"cannot represent time as UTCTime"} + } + if err != nil { + return + } + + err = marshalTwoDigits(out, int(month)) + if err != nil { + return + } + + err = marshalTwoDigits(out, day) + if err != nil { + return + } + + hour, min, sec := t.Clock() + + err = marshalTwoDigits(out, hour) + if err != nil { + return + } + + err = marshalTwoDigits(out, min) + if err != nil { + return + } + + err = marshalTwoDigits(out, sec) + if err != nil { + return + } + + _, offset := t.Zone() + + switch { + case offset/60 == 0: + err = out.WriteByte('Z') + return + case offset > 0: + err = out.WriteByte('+') + case offset < 0: + err = out.WriteByte('-') + } + + if err != nil { + return + } + + offsetMinutes := offset / 60 + if offsetMinutes < 0 { + offsetMinutes = -offsetMinutes + } + + err = marshalTwoDigits(out, offsetMinutes/60) + if err != nil { + return + } + + err = marshalTwoDigits(out, offsetMinutes%60) + return +} + +func stripTagAndLength(in []byte) []byte { + _, offset, err := parseTagAndLength(in, 0) + if err != nil { + return in + } + return in[offset:] +} + +func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) { + switch value.Type() { + case timeType: + return marshalUTCTime(out, value.Interface().(time.Time)) + case bitStringType: + return marshalBitString(out, value.Interface().(BitString)) + case objectIdentifierType: + return marshalObjectIdentifier(out, value.Interface().(ObjectIdentifier)) + case bigIntType: + return marshalBigInt(out, value.Interface().(*big.Int)) + } + + switch v := value; v.Kind() { + case reflect.Bool: + if v.Bool() { + return out.WriteByte(255) + } else { + return out.WriteByte(0) + } + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return marshalInt64(out, int64(v.Int())) + case reflect.Struct: + t := v.Type() + + startingField := 0 + + // If the first element of the structure is a non-empty + // RawContents, then we don't bother serializing the rest. + if t.NumField() > 0 && t.Field(0).Type == rawContentsType { + s := v.Field(0) + if s.Len() > 0 { + bytes := make([]byte, s.Len()) + for i := 0; i < s.Len(); i++ { + bytes[i] = uint8(s.Index(i).Uint()) + } + /* The RawContents will contain the tag and + * length fields but we'll also be writing + * those ourselves, so we strip them out of + * bytes */ + _, err = out.Write(stripTagAndLength(bytes)) + return + } else { + startingField = 1 + } + } + + for i := startingField; i < t.NumField(); i++ { + var pre *forkableWriter + pre, out = out.fork() + err = marshalField(pre, v.Field(i), parseFieldParameters(t.Field(i).Tag.Get("asn1"))) + if err != nil { + return + } + } + return + case reflect.Slice: + sliceType := v.Type() + if sliceType.Elem().Kind() == reflect.Uint8 { + bytes := make([]byte, v.Len()) + for i := 0; i < v.Len(); i++ { + bytes[i] = uint8(v.Index(i).Uint()) + } + _, err = out.Write(bytes) + return + } + + var fp fieldParameters + for i := 0; i < v.Len(); i++ { + var pre *forkableWriter + pre, out = out.fork() + err = marshalField(pre, v.Index(i), fp) + if err != nil { + return + } + } + return + case reflect.String: + switch params.stringType { + case tagIA5String: + return marshalIA5String(out, v.String()) + case tagPrintableString: + return marshalPrintableString(out, v.String()) + default: + return marshalUTF8String(out, v.String()) + } + } + + return StructuralError{"unknown Go type"} +} + +func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) { + // If the field is an interface{} then recurse into it. + if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 { + return marshalField(out, v.Elem(), params) + } + + if v.Kind() == reflect.Slice && v.Len() == 0 && params.omitEmpty { + return + } + + if params.optional && reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) { + return + } + + if v.Type() == rawValueType { + rv := v.Interface().(RawValue) + if len(rv.FullBytes) != 0 { + _, err = out.Write(rv.FullBytes) + } else { + err = marshalTagAndLength(out, tagAndLength{rv.Class, rv.Tag, len(rv.Bytes), rv.IsCompound}) + if err != nil { + return + } + _, err = out.Write(rv.Bytes) + } + return + } + + tag, isCompound, ok := getUniversalType(v.Type()) + if !ok { + err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())} + return + } + class := classUniversal + + if params.stringType != 0 && tag != tagPrintableString { + return StructuralError{"explicit string type given to non-string member"} + } + + if tag == tagPrintableString { + if params.stringType == 0 { + // This is a string without an explicit string type. We'll use + // a PrintableString if the character set in the string is + // sufficiently limited, otherwise we'll use a UTF8String. + for _, r := range v.String() { + if r >= utf8.RuneSelf || !isPrintable(byte(r)) { + if !utf8.ValidString(v.String()) { + return errors.New("asn1: string not valid UTF-8") + } + tag = tagUTF8String + break + } + } + } else { + tag = params.stringType + } + } + + if params.set { + if tag != tagSequence { + return StructuralError{"non sequence tagged as set"} + } + tag = tagSet + } + + tags, body := out.fork() + + err = marshalBody(body, v, params) + if err != nil { + return + } + + bodyLen := body.Len() + + var explicitTag *forkableWriter + if params.explicit { + explicitTag, tags = tags.fork() + } + + if !params.explicit && params.tag != nil { + // implicit tag. + tag = *params.tag + class = classContextSpecific + } + + err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound}) + if err != nil { + return + } + + if params.explicit { + err = marshalTagAndLength(explicitTag, tagAndLength{ + class: classContextSpecific, + tag: *params.tag, + length: bodyLen + tags.Len(), + isCompound: true, + }) + } + + return nil +} + +// Marshal returns the ASN.1 encoding of val. +func Marshal(val interface{}) ([]byte, error) { + var out bytes.Buffer + v := reflect.ValueOf(val) + f := newForkableWriter() + err := marshalField(f, v, fieldParameters{}) + if err != nil { + return nil, err + } + _, err = f.writeTo(&out) + return out.Bytes(), nil +} diff --git a/vendor/github.com/google/certificate-transparency/go/client/logclient.go b/vendor/github.com/google/certificate-transparency/go/client/logclient.go new file mode 100644 index 000000000000..e9c7f216806f --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/client/logclient.go @@ -0,0 +1,358 @@ +// Package client is a CT log client implementation and contains types and code +// for interacting with RFC6962-compliant CT Log instances. +// See http://tools.ietf.org/html/rfc6962 for details +package client + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "log" + "net/http" + "strconv" + "time" + + "github.com/google/certificate-transparency/go" + "github.com/mreiferson/go-httpclient" + "golang.org/x/net/context" +) + +// URI paths for CT Log endpoints +const ( + AddChainPath = "/ct/v1/add-chain" + AddPreChainPath = "/ct/v1/add-pre-chain" + GetSTHPath = "/ct/v1/get-sth" + GetEntriesPath = "/ct/v1/get-entries" +) + +// LogClient represents a client for a given CT Log instance +type LogClient struct { + uri string // the base URI of the log. e.g. http://ct.googleapis/pilot + httpClient *http.Client // used to interact with the log via HTTP +} + +////////////////////////////////////////////////////////////////////////////////// +// JSON structures follow. +// These represent the structures returned by the CT Log server. +////////////////////////////////////////////////////////////////////////////////// + +// addChainRequest represents the JSON request body sent to the add-chain CT +// method. +type addChainRequest struct { + Chain []string `json:"chain"` +} + +// addChainResponse represents the JSON response to the add-chain CT method. +// An SCT represents a Log's promise to integrate a [pre-]certificate into the +// log within a defined period of time. +type addChainResponse struct { + SCTVersion ct.Version `json:"sct_version"` // SCT structure version + ID string `json:"id"` // Log ID + Timestamp uint64 `json:"timestamp"` // Timestamp of issuance + Extensions string `json:"extensions"` // Holder for any CT extensions + Signature string `json:"signature"` // Log signature for this SCT +} + +// getSTHResponse respresents the JSON response to the get-sth CT method +type getSTHResponse struct { + TreeSize uint64 `json:"tree_size"` // Number of certs in the current tree + Timestamp uint64 `json:"timestamp"` // Time that the tree was created + SHA256RootHash string `json:"sha256_root_hash"` // Root hash of the tree + TreeHeadSignature string `json:"tree_head_signature"` // Log signature for this STH +} + +// base64LeafEntry respresents a Base64 encoded leaf entry +type base64LeafEntry struct { + LeafInput string `json:"leaf_input"` + ExtraData string `json:"extra_data"` +} + +// getEntriesReponse respresents the JSON response to the CT get-entries method +type getEntriesResponse struct { + Entries []base64LeafEntry `json:"entries"` // the list of returned entries +} + +// getConsistencyProofResponse represents the JSON response to the CT get-consistency-proof method +type getConsistencyProofResponse struct { + Consistency []string `json:"consistency"` +} + +// getAuditProofResponse represents the JSON response to the CT get-audit-proof method +type getAuditProofResponse struct { + Hash []string `json:"hash"` // the hashes which make up the proof + TreeSize uint64 `json:"tree_size"` // the tree size against which this proof is constructed +} + +// getAcceptedRootsResponse represents the JSON response to the CT get-roots method. +type getAcceptedRootsResponse struct { + Certificates []string `json:"certificates"` +} + +// getEntryAndProodReponse represents the JSON response to the CT get-entry-and-proof method +type getEntryAndProofResponse struct { + LeafInput string `json:"leaf_input"` // the entry itself + ExtraData string `json:"extra_data"` // any chain provided when the entry was added to the log + AuditPath []string `json:"audit_path"` // the corresponding proof +} + +// New constructs a new LogClient instance. +// |uri| is the base URI of the CT log instance to interact with, e.g. +// http://ct.googleapis.com/pilot +func New(uri string) *LogClient { + var c LogClient + c.uri = uri + transport := &httpclient.Transport{ + ConnectTimeout: 10 * time.Second, + RequestTimeout: 30 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 10, + DisableKeepAlives: false, + } + c.httpClient = &http.Client{Transport: transport} + return &c +} + +// Makes a HTTP call to |uri|, and attempts to parse the response as a JSON +// representation of the structure in |res|. +// Returns a non-nil |error| if there was a problem. +func (c *LogClient) fetchAndParse(uri string, res interface{}) error { + req, err := http.NewRequest("GET", uri, nil) + if err != nil { + return err + } + req.Header.Set("Keep-Alive", "timeout=15, max=100") + resp, err := c.httpClient.Do(req) + var body []byte + if resp != nil { + body, err = ioutil.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return err + } + } + if err != nil { + return err + } + if err = json.Unmarshal(body, &res); err != nil { + return err + } + return nil +} + +// Makes a HTTP POST call to |uri|, and attempts to parse the response as a JSON +// representation of the structure in |res|. +// Returns a non-nil |error| if there was a problem. +func (c *LogClient) postAndParse(uri string, req interface{}, res interface{}) (*http.Response, string, error) { + postBody, err := json.Marshal(req) + if err != nil { + return nil, "", err + } + httpReq, err := http.NewRequest("POST", uri, bytes.NewReader(postBody)) + if err != nil { + return nil, "", err + } + httpReq.Header.Set("Keep-Alive", "timeout=15, max=100") + httpReq.Header.Set("Content-Type", "application/json") + resp, err := c.httpClient.Do(httpReq) + // Read all of the body, if there is one, so that the http.Client can do + // Keep-Alive: + var body []byte + if resp != nil { + body, err = ioutil.ReadAll(resp.Body) + resp.Body.Close() + } + if err != nil { + return resp, string(body), err + } + if resp.StatusCode == 200 { + if err != nil { + return resp, string(body), err + } + if err = json.Unmarshal(body, &res); err != nil { + return resp, string(body), err + } + } + return resp, string(body), nil +} + +func backoffForRetry(ctx context.Context, d time.Duration) error { + backoffTimer := time.NewTimer(d) + if ctx != nil { + select { + case <-ctx.Done(): + return ctx.Err() + case <-backoffTimer.C: + } + } else { + <-backoffTimer.C + } + return nil +} + +// Attempts to add |chain| to the log, using the api end-point specified by +// |path|. If provided context expires before submission is complete an +// error will be returned. +func (c *LogClient) addChainWithRetry(ctx context.Context, path string, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) { + var resp addChainResponse + var req addChainRequest + for _, link := range chain { + req.Chain = append(req.Chain, base64.StdEncoding.EncodeToString(link)) + } + httpStatus := "Unknown" + backoffSeconds := 0 + done := false + for !done { + if backoffSeconds > 0 { + log.Printf("Got %s, backing-off %d seconds", httpStatus, backoffSeconds) + } + err := backoffForRetry(ctx, time.Second*time.Duration(backoffSeconds)) + if err != nil { + return nil, err + } + if backoffSeconds > 0 { + backoffSeconds = 0 + } + httpResp, errorBody, err := c.postAndParse(c.uri+path, &req, &resp) + if err != nil { + backoffSeconds = 10 + continue + } + switch { + case httpResp.StatusCode == 200: + done = true + case httpResp.StatusCode == 408: + // request timeout, retry immediately + case httpResp.StatusCode == 503: + // Retry + backoffSeconds = 10 + if retryAfter := httpResp.Header.Get("Retry-After"); retryAfter != "" { + if seconds, err := strconv.Atoi(retryAfter); err == nil { + backoffSeconds = seconds + } + } + default: + return nil, fmt.Errorf("got HTTP Status %s: %s", httpResp.Status, errorBody) + } + httpStatus = httpResp.Status + } + + rawLogID, err := base64.StdEncoding.DecodeString(resp.ID) + if err != nil { + return nil, err + } + rawSignature, err := base64.StdEncoding.DecodeString(resp.Signature) + if err != nil { + return nil, err + } + ds, err := ct.UnmarshalDigitallySigned(bytes.NewReader(rawSignature)) + if err != nil { + return nil, err + } + var logID ct.SHA256Hash + copy(logID[:], rawLogID) + return &ct.SignedCertificateTimestamp{ + SCTVersion: resp.SCTVersion, + LogID: logID, + Timestamp: resp.Timestamp, + Extensions: ct.CTExtensions(resp.Extensions), + Signature: *ds}, nil +} + +// AddChain adds the (DER represented) X509 |chain| to the log. +func (c *LogClient) AddChain(chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) { + return c.addChainWithRetry(nil, AddChainPath, chain) +} + +// AddPreChain adds the (DER represented) Precertificate |chain| to the log. +func (c *LogClient) AddPreChain(chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) { + return c.addChainWithRetry(nil, AddPreChainPath, chain) +} + +// AddChainWithContext adds the (DER represented) X509 |chain| to the log and +// fails if the provided context expires before the chain is submitted. +func (c *LogClient) AddChainWithContext(ctx context.Context, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) { + return c.addChainWithRetry(ctx, AddChainPath, chain) +} + +// GetSTH retrieves the current STH from the log. +// Returns a populated SignedTreeHead, or a non-nil error. +func (c *LogClient) GetSTH() (sth *ct.SignedTreeHead, err error) { + var resp getSTHResponse + if err = c.fetchAndParse(c.uri+GetSTHPath, &resp); err != nil { + return + } + sth = &ct.SignedTreeHead{ + TreeSize: resp.TreeSize, + Timestamp: resp.Timestamp, + } + + rawRootHash, err := base64.StdEncoding.DecodeString(resp.SHA256RootHash) + if err != nil { + return nil, fmt.Errorf("invalid base64 encoding in sha256_root_hash: %v", err) + } + if len(rawRootHash) != sha256.Size { + return nil, fmt.Errorf("sha256_root_hash is invalid length, expected %d got %d", sha256.Size, len(rawRootHash)) + } + copy(sth.SHA256RootHash[:], rawRootHash) + + rawSignature, err := base64.StdEncoding.DecodeString(resp.TreeHeadSignature) + if err != nil { + return nil, errors.New("invalid base64 encoding in tree_head_signature") + } + ds, err := ct.UnmarshalDigitallySigned(bytes.NewReader(rawSignature)) + if err != nil { + return nil, err + } + // TODO(alcutter): Verify signature + sth.TreeHeadSignature = *ds + return +} + +// GetEntries attempts to retrieve the entries in the sequence [|start|, |end|] from the CT +// log server. (see section 4.6.) +// Returns a slice of LeafInputs or a non-nil error. +func (c *LogClient) GetEntries(start, end int64) ([]ct.LogEntry, error) { + if end < 0 { + return nil, errors.New("end should be >= 0") + } + if end < start { + return nil, errors.New("start should be <= end") + } + var resp getEntriesResponse + err := c.fetchAndParse(fmt.Sprintf("%s%s?start=%d&end=%d", c.uri, GetEntriesPath, start, end), &resp) + if err != nil { + return nil, err + } + entries := make([]ct.LogEntry, len(resp.Entries)) + for index, entry := range resp.Entries { + leafBytes, err := base64.StdEncoding.DecodeString(entry.LeafInput) + leaf, err := ct.ReadMerkleTreeLeaf(bytes.NewBuffer(leafBytes)) + if err != nil { + return nil, err + } + entries[index].Leaf = *leaf + chainBytes, err := base64.StdEncoding.DecodeString(entry.ExtraData) + + var chain []ct.ASN1Cert + switch leaf.TimestampedEntry.EntryType { + case ct.X509LogEntryType: + chain, err = ct.UnmarshalX509ChainArray(chainBytes) + + case ct.PrecertLogEntryType: + chain, err = ct.UnmarshalPrecertChainArray(chainBytes) + + default: + return nil, fmt.Errorf("saw unknown entry type: %v", leaf.TimestampedEntry.EntryType) + } + if err != nil { + return nil, err + } + entries[index].Chain = chain + entries[index].Index = start + int64(index) + } + return entries, nil +} diff --git a/vendor/github.com/google/certificate-transparency/go/serialization.go b/vendor/github.com/google/certificate-transparency/go/serialization.go new file mode 100644 index 000000000000..aab3a3f20c8e --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/serialization.go @@ -0,0 +1,512 @@ +package ct + +import ( + "bytes" + "container/list" + "crypto" + "encoding/binary" + "errors" + "fmt" + "io" +) + +// Variable size structure prefix-header byte lengths +const ( + CertificateLengthBytes = 3 + PreCertificateLengthBytes = 3 + ExtensionsLengthBytes = 2 + CertificateChainLengthBytes = 3 + SignatureLengthBytes = 2 +) + +// Max lengths +const ( + MaxCertificateLength = (1 << 24) - 1 + MaxExtensionsLength = (1 << 16) - 1 +) + +func writeUint(w io.Writer, value uint64, numBytes int) error { + buf := make([]uint8, numBytes) + for i := 0; i < numBytes; i++ { + buf[numBytes-i-1] = uint8(value & 0xff) + value >>= 8 + } + if value != 0 { + return errors.New("numBytes was insufficiently large to represent value") + } + if _, err := w.Write(buf); err != nil { + return err + } + return nil +} + +func writeVarBytes(w io.Writer, value []byte, numLenBytes int) error { + if err := writeUint(w, uint64(len(value)), numLenBytes); err != nil { + return err + } + if _, err := w.Write(value); err != nil { + return err + } + return nil +} + +func readUint(r io.Reader, numBytes int) (uint64, error) { + var l uint64 + for i := 0; i < numBytes; i++ { + l <<= 8 + var t uint8 + if err := binary.Read(r, binary.BigEndian, &t); err != nil { + return 0, err + } + l |= uint64(t) + } + return l, nil +} + +// Reads a variable length array of bytes from |r|. |numLenBytes| specifies the +// number of (BigEndian) prefix-bytes which contain the length of the actual +// array data bytes that follow. +// Allocates an array to hold the contents and returns a slice view into it if +// the read was successful, or an error otherwise. +func readVarBytes(r io.Reader, numLenBytes int) ([]byte, error) { + switch { + case numLenBytes > 8: + return nil, fmt.Errorf("numLenBytes too large (%d)", numLenBytes) + case numLenBytes == 0: + return nil, errors.New("numLenBytes should be > 0") + } + l, err := readUint(r, numLenBytes) + if err != nil { + return nil, err + } + data := make([]byte, l) + n, err := r.Read(data) + if err != nil { + return nil, err + } + if n != int(l) { + return nil, fmt.Errorf("short read: expected %d but got %d", l, n) + } + return data, nil +} + +// Reads a list of ASN1Cert types from |r| +func readASN1CertList(r io.Reader, totalLenBytes int, elementLenBytes int) ([]ASN1Cert, error) { + listBytes, err := readVarBytes(r, totalLenBytes) + if err != nil { + return []ASN1Cert{}, err + } + list := list.New() + listReader := bytes.NewReader(listBytes) + var entry []byte + for err == nil { + entry, err = readVarBytes(listReader, elementLenBytes) + if err != nil { + if err != io.EOF { + return []ASN1Cert{}, err + } + } else { + list.PushBack(entry) + } + } + ret := make([]ASN1Cert, list.Len()) + i := 0 + for e := list.Front(); e != nil; e = e.Next() { + ret[i] = e.Value.([]byte) + i++ + } + return ret, nil +} + +// ReadTimestampedEntryInto parses the byte-stream representation of a +// TimestampedEntry from |r| and populates the struct |t| with the data. See +// RFC section 3.4 for details on the format. +// Returns a non-nil error if there was a problem. +func ReadTimestampedEntryInto(r io.Reader, t *TimestampedEntry) error { + var err error + if err = binary.Read(r, binary.BigEndian, &t.Timestamp); err != nil { + return err + } + if err = binary.Read(r, binary.BigEndian, &t.EntryType); err != nil { + return err + } + switch t.EntryType { + case X509LogEntryType: + if t.X509Entry, err = readVarBytes(r, CertificateLengthBytes); err != nil { + return err + } + case PrecertLogEntryType: + if err := binary.Read(r, binary.BigEndian, &t.PrecertEntry.IssuerKeyHash); err != nil { + return err + } + if t.PrecertEntry.TBSCertificate, err = readVarBytes(r, PreCertificateLengthBytes); err != nil { + return err + } + default: + return fmt.Errorf("unknown EntryType: %d", t.EntryType) + } + t.Extensions, err = readVarBytes(r, ExtensionsLengthBytes) + return nil +} + +// ReadMerkleTreeLeaf parses the byte-stream representation of a MerkleTreeLeaf +// and returns a pointer to a new MerkleTreeLeaf structure containing the +// parsed data. +// See RFC section 3.4 for details on the format. +// Returns a pointer to a new MerkleTreeLeaf or non-nil error if there was a +// problem +func ReadMerkleTreeLeaf(r io.Reader) (*MerkleTreeLeaf, error) { + var m MerkleTreeLeaf + if err := binary.Read(r, binary.BigEndian, &m.Version); err != nil { + return nil, err + } + if m.Version != V1 { + return nil, fmt.Errorf("unknown Version %d", m.Version) + } + if err := binary.Read(r, binary.BigEndian, &m.LeafType); err != nil { + return nil, err + } + if m.LeafType != TimestampedEntryLeafType { + return nil, fmt.Errorf("unknown LeafType %d", m.LeafType) + } + if err := ReadTimestampedEntryInto(r, &m.TimestampedEntry); err != nil { + return nil, err + } + return &m, nil +} + +// UnmarshalX509ChainArray unmarshalls the contents of the "chain:" entry in a +// GetEntries response in the case where the entry refers to an X509 leaf. +func UnmarshalX509ChainArray(b []byte) ([]ASN1Cert, error) { + return readASN1CertList(bytes.NewReader(b), CertificateChainLengthBytes, CertificateLengthBytes) +} + +// UnmarshalPrecertChainArray unmarshalls the contents of the "chain:" entry in +// a GetEntries response in the case where the entry refers to a Precertificate +// leaf. +func UnmarshalPrecertChainArray(b []byte) ([]ASN1Cert, error) { + var chain []ASN1Cert + + reader := bytes.NewReader(b) + // read the pre-cert entry: + precert, err := readVarBytes(reader, CertificateLengthBytes) + if err != nil { + return chain, err + } + chain = append(chain, precert) + // and then read and return the chain up to the root: + remainingChain, err := readASN1CertList(reader, CertificateChainLengthBytes, CertificateLengthBytes) + if err != nil { + return chain, err + } + chain = append(chain, remainingChain...) + return chain, nil +} + +// UnmarshalDigitallySigned reconstructs a DigitallySigned structure from a Reader +func UnmarshalDigitallySigned(r io.Reader) (*DigitallySigned, error) { + var h byte + if err := binary.Read(r, binary.BigEndian, &h); err != nil { + return nil, fmt.Errorf("failed to read HashAlgorithm: %v", err) + } + + var s byte + if err := binary.Read(r, binary.BigEndian, &s); err != nil { + return nil, fmt.Errorf("failed to read SignatureAlgorithm: %v", err) + } + + sig, err := readVarBytes(r, SignatureLengthBytes) + if err != nil { + return nil, fmt.Errorf("failed to read Signature bytes: %v", err) + } + + return &DigitallySigned{ + HashAlgorithm: HashAlgorithm(h), + SignatureAlgorithm: SignatureAlgorithm(s), + Signature: sig, + }, nil +} + +func marshalDigitallySignedHere(ds DigitallySigned, here []byte) ([]byte, error) { + sigLen := len(ds.Signature) + dsOutLen := 2 + SignatureLengthBytes + sigLen + if here == nil { + here = make([]byte, dsOutLen) + } + if len(here) < dsOutLen { + return nil, ErrNotEnoughBuffer + } + here = here[0:dsOutLen] + + here[0] = byte(ds.HashAlgorithm) + here[1] = byte(ds.SignatureAlgorithm) + binary.BigEndian.PutUint16(here[2:4], uint16(sigLen)) + copy(here[4:], ds.Signature) + + return here, nil +} + +// MarshalDigitallySigned marshalls a DigitallySigned structure into a byte array +func MarshalDigitallySigned(ds DigitallySigned) ([]byte, error) { + return marshalDigitallySignedHere(ds, nil) +} + +func checkCertificateFormat(cert ASN1Cert) error { + if len(cert) == 0 { + return errors.New("certificate is zero length") + } + if len(cert) > MaxCertificateLength { + return errors.New("certificate too large") + } + return nil +} + +func checkExtensionsFormat(ext CTExtensions) error { + if len(ext) > MaxExtensionsLength { + return errors.New("extensions too large") + } + return nil +} + +func serializeV1CertSCTSignatureInput(timestamp uint64, cert ASN1Cert, ext CTExtensions) ([]byte, error) { + if err := checkCertificateFormat(cert); err != nil { + return nil, err + } + if err := checkExtensionsFormat(ext); err != nil { + return nil, err + } + var buf bytes.Buffer + if err := binary.Write(&buf, binary.BigEndian, V1); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, X509LogEntryType); err != nil { + return nil, err + } + if err := writeVarBytes(&buf, cert, CertificateLengthBytes); err != nil { + return nil, err + } + if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func serializeV1PrecertSCTSignatureInput(timestamp uint64, issuerKeyHash [issuerKeyHashLength]byte, tbs []byte, ext CTExtensions) ([]byte, error) { + if err := checkCertificateFormat(tbs); err != nil { + return nil, err + } + if err := checkExtensionsFormat(ext); err != nil { + return nil, err + } + var buf bytes.Buffer + if err := binary.Write(&buf, binary.BigEndian, V1); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, PrecertLogEntryType); err != nil { + return nil, err + } + if _, err := buf.Write(issuerKeyHash[:]); err != nil { + return nil, err + } + if err := writeVarBytes(&buf, tbs, CertificateLengthBytes); err != nil { + return nil, err + } + if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func serializeV1SCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) { + if sct.SCTVersion != V1 { + return nil, fmt.Errorf("unsupported SCT version, expected V1, but got %s", sct.SCTVersion) + } + if entry.Leaf.LeafType != TimestampedEntryLeafType { + return nil, fmt.Errorf("Unsupported leaf type %s", entry.Leaf.LeafType) + } + switch entry.Leaf.TimestampedEntry.EntryType { + case X509LogEntryType: + return serializeV1CertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.X509Entry, entry.Leaf.TimestampedEntry.Extensions) + case PrecertLogEntryType: + return serializeV1PrecertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.PrecertEntry.IssuerKeyHash, + entry.Leaf.TimestampedEntry.PrecertEntry.TBSCertificate, + entry.Leaf.TimestampedEntry.Extensions) + default: + return nil, fmt.Errorf("unknown TimestampedEntryLeafType %s", entry.Leaf.TimestampedEntry.EntryType) + } +} + +// SerializeSCTSignatureInput serializes the passed in sct and log entry into +// the correct format for signing. +func SerializeSCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) { + switch sct.SCTVersion { + case V1: + return serializeV1SCTSignatureInput(sct, entry) + default: + return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion) + } +} + +// SerializedLength will return the space (in bytes) +func (sct SignedCertificateTimestamp) SerializedLength() (int, error) { + switch sct.SCTVersion { + case V1: + extLen := len(sct.Extensions) + sigLen := len(sct.Signature.Signature) + return 1 + 32 + 8 + 2 + extLen + 2 + 2 + sigLen, nil + default: + return 0, ErrInvalidVersion + } +} + +func serializeV1SCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) { + if sct.SCTVersion != V1 { + return nil, ErrInvalidVersion + } + sctLen, err := sct.SerializedLength() + if err != nil { + return nil, err + } + if here == nil { + here = make([]byte, sctLen) + } + if len(here) < sctLen { + return nil, ErrNotEnoughBuffer + } + if err := checkExtensionsFormat(sct.Extensions); err != nil { + return nil, err + } + + here = here[0:sctLen] + + // Write Version + here[0] = byte(sct.SCTVersion) + + // Write LogID + copy(here[1:33], sct.LogID[:]) + + // Write Timestamp + binary.BigEndian.PutUint64(here[33:41], sct.Timestamp) + + // Write Extensions + extLen := len(sct.Extensions) + binary.BigEndian.PutUint16(here[41:43], uint16(extLen)) + n := 43 + extLen + copy(here[43:n], sct.Extensions) + + // Write Signature + _, err = marshalDigitallySignedHere(sct.Signature, here[n:]) + if err != nil { + return nil, err + } + return here, nil +} + +// SerializeSCTHere serializes the passed in sct into the format specified +// by RFC6962 section 3.2. +// If a bytes slice here is provided then it will attempt to serialize into the +// provided byte slice, ErrNotEnoughBuffer will be returned if the buffer is +// too small. +// If a nil byte slice is provided, a buffer for will be allocated for you +// The returned slice will be sliced to the correct length. +func SerializeSCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) { + switch sct.SCTVersion { + case V1: + return serializeV1SCTHere(sct, here) + default: + return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion) + } +} + +// SerializeSCT serializes the passed in sct into the format specified +// by RFC6962 section 3.2 +// Equivalent to SerializeSCTHere(sct, nil) +func SerializeSCT(sct SignedCertificateTimestamp) ([]byte, error) { + return SerializeSCTHere(sct, nil) +} + +func deserializeSCTV1(r io.Reader, sct *SignedCertificateTimestamp) error { + if err := binary.Read(r, binary.BigEndian, &sct.LogID); err != nil { + return err + } + if err := binary.Read(r, binary.BigEndian, &sct.Timestamp); err != nil { + return err + } + ext, err := readVarBytes(r, ExtensionsLengthBytes) + if err != nil { + return err + } + sct.Extensions = ext + ds, err := UnmarshalDigitallySigned(r) + if err != nil { + return err + } + sct.Signature = *ds + return nil +} + +func DeserializeSCT(r io.Reader) (*SignedCertificateTimestamp, error) { + var sct SignedCertificateTimestamp + if err := binary.Read(r, binary.BigEndian, &sct.SCTVersion); err != nil { + return nil, err + } + switch sct.SCTVersion { + case V1: + return &sct, deserializeSCTV1(r, &sct) + default: + return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion) + } +} + +func serializeV1STHSignatureInput(sth SignedTreeHead) ([]byte, error) { + if sth.Version != V1 { + return nil, fmt.Errorf("invalid STH version %d", sth.Version) + } + if sth.TreeSize < 0 { + return nil, fmt.Errorf("invalid tree size %d", sth.TreeSize) + } + if len(sth.SHA256RootHash) != crypto.SHA256.Size() { + return nil, fmt.Errorf("invalid TreeHash length, got %d expected %d", len(sth.SHA256RootHash), crypto.SHA256.Size()) + } + + var buf bytes.Buffer + if err := binary.Write(&buf, binary.BigEndian, V1); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, TreeHashSignatureType); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, sth.Timestamp); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, sth.TreeSize); err != nil { + return nil, err + } + if err := binary.Write(&buf, binary.BigEndian, sth.SHA256RootHash); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// SerializeSTHSignatureInput serializes the passed in sth into the correct +// format for signing. +func SerializeSTHSignatureInput(sth SignedTreeHead) ([]byte, error) { + switch sth.Version { + case V1: + return serializeV1STHSignatureInput(sth) + default: + return nil, fmt.Errorf("unsupported STH version %d", sth.Version) + } +} diff --git a/vendor/github.com/google/certificate-transparency/go/signatures.go b/vendor/github.com/google/certificate-transparency/go/signatures.go new file mode 100644 index 000000000000..600db245493b --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/signatures.go @@ -0,0 +1,131 @@ +package ct + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/asn1" + "encoding/pem" + "errors" + "flag" + "fmt" + "log" + "math/big" +) + +var allowVerificationWithNonCompliantKeys = flag.Bool("allow_verification_with_non_compliant_keys", false, + "Allow a SignatureVerifier to use keys which are technically non-compliant with RFC6962.") + +// PublicKeyFromPEM parses a PEM formatted block and returns the public key contained within and any remaining unread bytes, or an error. +func PublicKeyFromPEM(b []byte) (crypto.PublicKey, SHA256Hash, []byte, error) { + p, rest := pem.Decode(b) + if p == nil { + return nil, [sha256.Size]byte{}, rest, fmt.Errorf("no PEM block found in %s", string(b)) + } + k, err := x509.ParsePKIXPublicKey(p.Bytes) + return k, sha256.Sum256(p.Bytes), rest, err +} + +// SignatureVerifier can verify signatures on SCTs and STHs +type SignatureVerifier struct { + pubKey crypto.PublicKey +} + +// NewSignatureVerifier creates a new SignatureVerifier using the passed in PublicKey. +func NewSignatureVerifier(pk crypto.PublicKey) (*SignatureVerifier, error) { + switch pkType := pk.(type) { + case *rsa.PublicKey: + if pkType.N.BitLen() < 2048 { + e := fmt.Errorf("public key is RSA with < 2048 bits (size:%d)", pkType.N.BitLen()) + if !(*allowVerificationWithNonCompliantKeys) { + return nil, e + } + log.Printf("WARNING: %v", e) + } + case *ecdsa.PublicKey: + params := *(pkType.Params()) + if params != *elliptic.P256().Params() { + e := fmt.Errorf("public is ECDSA, but not on the P256 curve") + if !(*allowVerificationWithNonCompliantKeys) { + return nil, e + } + log.Printf("WARNING: %v", e) + + } + default: + return nil, fmt.Errorf("Unsupported public key type %v", pkType) + } + + return &SignatureVerifier{ + pubKey: pk, + }, nil +} + +// verifySignature verifies that the passed in signature over data was created by our PublicKey. +// Currently, only SHA256 is supported as a HashAlgorithm, and only ECDSA and RSA signatures are supported. +func (s SignatureVerifier) verifySignature(data []byte, sig DigitallySigned) error { + if sig.HashAlgorithm != SHA256 { + return fmt.Errorf("unsupported HashAlgorithm in signature: %v", sig.HashAlgorithm) + } + + hasherType := crypto.SHA256 + hasher := hasherType.New() + if _, err := hasher.Write(data); err != nil { + return fmt.Errorf("failed to write to hasher: %v", err) + } + hash := hasher.Sum([]byte{}) + + switch sig.SignatureAlgorithm { + case RSA: + rsaKey, ok := s.pubKey.(*rsa.PublicKey) + if !ok { + return fmt.Errorf("cannot verify RSA signature with %T key", s.pubKey) + } + if err := rsa.VerifyPKCS1v15(rsaKey, hasherType, hash, sig.Signature); err != nil { + return fmt.Errorf("failed to verify rsa signature: %v", err) + } + case ECDSA: + ecdsaKey, ok := s.pubKey.(*ecdsa.PublicKey) + if !ok { + return fmt.Errorf("cannot verify ECDSA signature with %T key", s.pubKey) + } + var ecdsaSig struct { + R, S *big.Int + } + rest, err := asn1.Unmarshal(sig.Signature, &ecdsaSig) + if err != nil { + return fmt.Errorf("failed to unmarshal ECDSA signature: %v", err) + } + if len(rest) != 0 { + log.Printf("Garbage following signature %v", rest) + } + + if !ecdsa.Verify(ecdsaKey, hash, ecdsaSig.R, ecdsaSig.S) { + return errors.New("failed to verify ecdsa signature") + } + default: + return fmt.Errorf("unsupported signature type %v", sig.SignatureAlgorithm) + } + return nil +} + +// VerifySCTSignature verifies that the SCT's signature is valid for the given LogEntry +func (s SignatureVerifier) VerifySCTSignature(sct SignedCertificateTimestamp, entry LogEntry) error { + sctData, err := SerializeSCTSignatureInput(sct, entry) + if err != nil { + return err + } + return s.verifySignature(sctData, sct.Signature) +} + +// VerifySTHSignature verifies that the STH's signature is valid. +func (s SignatureVerifier) VerifySTHSignature(sth SignedTreeHead) error { + sthData, err := SerializeSTHSignatureInput(sth) + if err != nil { + return err + } + return s.verifySignature(sthData, sth.TreeHeadSignature) +} diff --git a/vendor/github.com/google/certificate-transparency/go/types.go b/vendor/github.com/google/certificate-transparency/go/types.go new file mode 100644 index 000000000000..8a63e98e60a2 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/types.go @@ -0,0 +1,363 @@ +package ct + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + + "github.com/google/certificate-transparency/go/x509" +) + +const ( + issuerKeyHashLength = 32 +) + +/////////////////////////////////////////////////////////////////////////////// +// The following structures represent those outlined in the RFC6962 document: +/////////////////////////////////////////////////////////////////////////////// + +// LogEntryType represents the LogEntryType enum from section 3.1 of the RFC: +// enum { x509_entry(0), precert_entry(1), (65535) } LogEntryType; +type LogEntryType uint16 + +func (e LogEntryType) String() string { + switch e { + case X509LogEntryType: + return "X509LogEntryType" + case PrecertLogEntryType: + return "PrecertLogEntryType" + } + panic(fmt.Sprintf("No string defined for LogEntryType constant value %d", e)) +} + +// LogEntryType constants, see section 3.1 of RFC6962. +const ( + X509LogEntryType LogEntryType = 0 + PrecertLogEntryType LogEntryType = 1 +) + +// MerkleLeafType represents the MerkleLeafType enum from section 3.4 of the +// RFC: enum { timestamped_entry(0), (255) } MerkleLeafType; +type MerkleLeafType uint8 + +func (m MerkleLeafType) String() string { + switch m { + case TimestampedEntryLeafType: + return "TimestampedEntryLeafType" + default: + return fmt.Sprintf("UnknownLeafType(%d)", m) + } +} + +// MerkleLeafType constants, see section 3.4 of the RFC. +const ( + TimestampedEntryLeafType MerkleLeafType = 0 // Entry type for an SCT +) + +// Version represents the Version enum from section 3.2 of the RFC: +// enum { v1(0), (255) } Version; +type Version uint8 + +func (v Version) String() string { + switch v { + case V1: + return "V1" + default: + return fmt.Sprintf("UnknownVersion(%d)", v) + } +} + +// CT Version constants, see section 3.2 of the RFC. +const ( + V1 Version = 0 +) + +// SignatureType differentiates STH signatures from SCT signatures, see RFC +// section 3.2 +type SignatureType uint8 + +func (st SignatureType) String() string { + switch st { + case CertificateTimestampSignatureType: + return "CertificateTimestamp" + case TreeHashSignatureType: + return "TreeHash" + default: + return fmt.Sprintf("UnknownSignatureType(%d)", st) + } +} + +// SignatureType constants, see RFC section 3.2 +const ( + CertificateTimestampSignatureType SignatureType = 0 + TreeHashSignatureType SignatureType = 1 +) + +// ASN1Cert type for holding the raw DER bytes of an ASN.1 Certificate +// (section 3.1) +type ASN1Cert []byte + +// PreCert represents a Precertificate (section 3.2) +type PreCert struct { + IssuerKeyHash [issuerKeyHashLength]byte + TBSCertificate []byte +} + +// CTExtensions is a representation of the raw bytes of any CtExtension +// structure (see section 3.2) +type CTExtensions []byte + +// MerkleTreeNode represents an internal node in the CT tree +type MerkleTreeNode []byte + +// ConsistencyProof represents a CT consistency proof (see sections 2.1.2 and +// 4.4) +type ConsistencyProof []MerkleTreeNode + +// AuditPath represents a CT inclusion proof (see sections 2.1.1 and 4.5) +type AuditPath []MerkleTreeNode + +// LeafInput represents a serialized MerkleTreeLeaf structure +type LeafInput []byte + +// HashAlgorithm from the DigitallySigned struct +type HashAlgorithm byte + +// HashAlgorithm constants +const ( + None HashAlgorithm = 0 + MD5 HashAlgorithm = 1 + SHA1 HashAlgorithm = 2 + SHA224 HashAlgorithm = 3 + SHA256 HashAlgorithm = 4 + SHA384 HashAlgorithm = 5 + SHA512 HashAlgorithm = 6 +) + +func (h HashAlgorithm) String() string { + switch h { + case None: + return "None" + case MD5: + return "MD5" + case SHA1: + return "SHA1" + case SHA224: + return "SHA224" + case SHA256: + return "SHA256" + case SHA384: + return "SHA384" + case SHA512: + return "SHA512" + default: + return fmt.Sprintf("UNKNOWN(%d)", h) + } +} + +// SignatureAlgorithm from the the DigitallySigned struct +type SignatureAlgorithm byte + +// SignatureAlgorithm constants +const ( + Anonymous SignatureAlgorithm = 0 + RSA SignatureAlgorithm = 1 + DSA SignatureAlgorithm = 2 + ECDSA SignatureAlgorithm = 3 +) + +func (s SignatureAlgorithm) String() string { + switch s { + case Anonymous: + return "Anonymous" + case RSA: + return "RSA" + case DSA: + return "DSA" + case ECDSA: + return "ECDSA" + default: + return fmt.Sprintf("UNKNOWN(%d)", s) + } +} + +// DigitallySigned represents an RFC5246 DigitallySigned structure +type DigitallySigned struct { + HashAlgorithm HashAlgorithm + SignatureAlgorithm SignatureAlgorithm + Signature []byte +} + +// FromBase64String populates the DigitallySigned structure from the base64 data passed in. +// Returns an error if the base64 data is invalid. +func (d *DigitallySigned) FromBase64String(b64 string) error { + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + return fmt.Errorf("failed to unbase64 DigitallySigned: %v", err) + } + ds, err := UnmarshalDigitallySigned(bytes.NewReader(raw)) + if err != nil { + return fmt.Errorf("failed to unmarshal DigitallySigned: %v", err) + } + *d = *ds + return nil +} + +// Base64String returns the base64 representation of the DigitallySigned struct. +func (d DigitallySigned) Base64String() (string, error) { + b, err := MarshalDigitallySigned(d) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(b), nil +} + +// MarshalJSON implements the json.Marshaller interface. +func (d DigitallySigned) MarshalJSON() ([]byte, error) { + b64, err := d.Base64String() + if err != nil { + return []byte{}, err + } + return []byte(`"` + b64 + `"`), nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface. +func (d *DigitallySigned) UnmarshalJSON(b []byte) error { + var content string + if err := json.Unmarshal(b, &content); err != nil { + return fmt.Errorf("failed to unmarshal DigitallySigned: %v", err) + } + return d.FromBase64String(content) +} + +// LogEntry represents the contents of an entry in a CT log, see section 3.1. +type LogEntry struct { + Index int64 + Leaf MerkleTreeLeaf + X509Cert *x509.Certificate + Precert *Precertificate + Chain []ASN1Cert +} + +// SHA256Hash represents the output from the SHA256 hash function. +type SHA256Hash [sha256.Size]byte + +// FromBase64String populates the SHA256 struct with the contents of the base64 data passed in. +func (s *SHA256Hash) FromBase64String(b64 string) error { + bs, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + return fmt.Errorf("failed to unbase64 LogID: %v", err) + } + if len(bs) != sha256.Size { + return fmt.Errorf("invalid SHA256 length, expected 32 but got %d", len(bs)) + } + copy(s[:], bs) + return nil +} + +// Base64String returns the base64 representation of this SHA256Hash. +func (s SHA256Hash) Base64String() string { + return base64.StdEncoding.EncodeToString(s[:]) +} + +// MarshalJSON implements the json.Marshaller interface for SHA256Hash. +func (s SHA256Hash) MarshalJSON() ([]byte, error) { + return []byte(`"` + s.Base64String() + `"`), nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface. +func (s *SHA256Hash) UnmarshalJSON(b []byte) error { + var content string + if err := json.Unmarshal(b, &content); err != nil { + return fmt.Errorf("failed to unmarshal SHA256Hash: %v", err) + } + return s.FromBase64String(content) +} + +// SignedTreeHead represents the structure returned by the get-sth CT method +// after base64 decoding. See sections 3.5 and 4.3 in the RFC) +type SignedTreeHead struct { + Version Version `json:"sth_version"` // The version of the protocol to which the STH conforms + TreeSize uint64 `json:"tree_size"` // The number of entries in the new tree + Timestamp uint64 `json:"timestamp"` // The time at which the STH was created + SHA256RootHash SHA256Hash `json:"sha256_root_hash"` // The root hash of the log's Merkle tree + TreeHeadSignature DigitallySigned `json:"tree_head_signature"` // The Log's signature for this STH (see RFC section 3.5) + LogID SHA256Hash `json:"log_id"` // The SHA256 hash of the log's public key +} + +// SignedCertificateTimestamp represents the structure returned by the +// add-chain and add-pre-chain methods after base64 decoding. (see RFC sections +// 3.2 ,4.1 and 4.2) +type SignedCertificateTimestamp struct { + SCTVersion Version // The version of the protocol to which the SCT conforms + LogID SHA256Hash // the SHA-256 hash of the log's public key, calculated over + // the DER encoding of the key represented as SubjectPublicKeyInfo. + Timestamp uint64 // Timestamp (in ms since unix epoc) at which the SCT was issued + Extensions CTExtensions // For future extensions to the protocol + Signature DigitallySigned // The Log's signature for this SCT +} + +func (s SignedCertificateTimestamp) String() string { + return fmt.Sprintf("{Version:%d LogId:%s Timestamp:%d Extensions:'%s' Signature:%v}", s.SCTVersion, + base64.StdEncoding.EncodeToString(s.LogID[:]), + s.Timestamp, + s.Extensions, + s.Signature) +} + +// TimestampedEntry is part of the MerkleTreeLeaf structure. +// See RFC section 3.4 +type TimestampedEntry struct { + Timestamp uint64 + EntryType LogEntryType + X509Entry ASN1Cert + PrecertEntry PreCert + Extensions CTExtensions +} + +// MerkleTreeLeaf represents the deserialized sructure of the hash input for the +// leaves of a log's Merkle tree. See RFC section 3.4 +type MerkleTreeLeaf struct { + Version Version // the version of the protocol to which the MerkleTreeLeaf corresponds + LeafType MerkleLeafType // The type of the leaf input, currently only TimestampedEntry can exist + TimestampedEntry TimestampedEntry // The entry data itself +} + +// Precertificate represents the parsed CT Precertificate structure. +type Precertificate struct { + // Raw DER bytes of the precert + Raw []byte + // SHA256 hash of the issuing key + IssuerKeyHash [issuerKeyHashLength]byte + // Parsed TBSCertificate structure (held in an x509.Certificate for ease of + // access. + TBSCertificate x509.Certificate +} + +// X509Certificate returns the X.509 Certificate contained within the +// MerkleTreeLeaf. +// Returns a pointer to an x509.Certificate or a non-nil error. +func (m *MerkleTreeLeaf) X509Certificate() (*x509.Certificate, error) { + return x509.ParseCertificate(m.TimestampedEntry.X509Entry) +} + +type sctError int + +// Preallocate errors for performance +var ( + ErrInvalidVersion error = sctError(1) + ErrNotEnoughBuffer error = sctError(2) +) + +func (e sctError) Error() string { + switch e { + case ErrInvalidVersion: + return "invalid SCT version detected" + case ErrNotEnoughBuffer: + return "provided buffer was too small" + default: + return "unknown error" + } +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go b/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go new file mode 100755 index 000000000000..babe94d41c55 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go @@ -0,0 +1,116 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package x509 + +import ( + "encoding/pem" +) + +// CertPool is a set of certificates. +type CertPool struct { + bySubjectKeyId map[string][]int + byName map[string][]int + certs []*Certificate +} + +// NewCertPool returns a new, empty CertPool. +func NewCertPool() *CertPool { + return &CertPool{ + make(map[string][]int), + make(map[string][]int), + nil, + } +} + +// findVerifiedParents attempts to find certificates in s which have signed the +// given certificate. If any candidates were rejected then errCert will be set +// to one of them, arbitrarily, and err will contain the reason that it was +// rejected. +func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) { + if s == nil { + return + } + var candidates []int + + if len(cert.AuthorityKeyId) > 0 { + candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)] + } + if len(candidates) == 0 { + candidates = s.byName[string(cert.RawIssuer)] + } + + for _, c := range candidates { + if err = cert.CheckSignatureFrom(s.certs[c]); err == nil { + parents = append(parents, c) + } else { + errCert = s.certs[c] + } + } + + return +} + +// AddCert adds a certificate to a pool. +func (s *CertPool) AddCert(cert *Certificate) { + if cert == nil { + panic("adding nil Certificate to CertPool") + } + + // Check that the certificate isn't being added twice. + for _, c := range s.certs { + if c.Equal(cert) { + return + } + } + + n := len(s.certs) + s.certs = append(s.certs, cert) + + if len(cert.SubjectKeyId) > 0 { + keyId := string(cert.SubjectKeyId) + s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n) + } + name := string(cert.RawSubject) + s.byName[name] = append(s.byName[name], n) +} + +// AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. +// It appends any certificates found to s and returns true if any certificates +// were successfully parsed. +// +// On many Linux systems, /etc/ssl/cert.pem will contain the system wide set +// of root CAs in a format suitable for this function. +func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) { + for len(pemCerts) > 0 { + var block *pem.Block + block, pemCerts = pem.Decode(pemCerts) + if block == nil { + break + } + if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { + continue + } + + cert, err := ParseCertificate(block.Bytes) + if err != nil { + continue + } + + s.AddCert(cert) + ok = true + } + + return +} + +// Subjects returns a list of the DER-encoded subjects of +// all of the certificates in the pool. +func (s *CertPool) Subjects() (res [][]byte) { + res = make([][]byte, len(s.certs)) + for i, c := range s.certs { + res[i] = c.RawSubject + } + return +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go b/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go new file mode 100755 index 000000000000..194c81bf688c --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go @@ -0,0 +1,233 @@ +// Copyright 2012 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 x509 + +// RFC 1423 describes the encryption of PEM blocks. The algorithm used to +// generate a key from the password was derived by looking at the OpenSSL +// implementation. + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/md5" + "encoding/hex" + "encoding/pem" + "errors" + "io" + "strings" +) + +type PEMCipher int + +// Possible values for the EncryptPEMBlock encryption algorithm. +const ( + _ PEMCipher = iota + PEMCipherDES + PEMCipher3DES + PEMCipherAES128 + PEMCipherAES192 + PEMCipherAES256 +) + +// rfc1423Algo holds a method for enciphering a PEM block. +type rfc1423Algo struct { + cipher PEMCipher + name string + cipherFunc func(key []byte) (cipher.Block, error) + keySize int + blockSize int +} + +// rfc1423Algos holds a slice of the possible ways to encrypt a PEM +// block. The ivSize numbers were taken from the OpenSSL source. +var rfc1423Algos = []rfc1423Algo{{ + cipher: PEMCipherDES, + name: "DES-CBC", + cipherFunc: des.NewCipher, + keySize: 8, + blockSize: des.BlockSize, +}, { + cipher: PEMCipher3DES, + name: "DES-EDE3-CBC", + cipherFunc: des.NewTripleDESCipher, + keySize: 24, + blockSize: des.BlockSize, +}, { + cipher: PEMCipherAES128, + name: "AES-128-CBC", + cipherFunc: aes.NewCipher, + keySize: 16, + blockSize: aes.BlockSize, +}, { + cipher: PEMCipherAES192, + name: "AES-192-CBC", + cipherFunc: aes.NewCipher, + keySize: 24, + blockSize: aes.BlockSize, +}, { + cipher: PEMCipherAES256, + name: "AES-256-CBC", + cipherFunc: aes.NewCipher, + keySize: 32, + blockSize: aes.BlockSize, +}, +} + +// deriveKey uses a key derivation function to stretch the password into a key +// with the number of bits our cipher requires. This algorithm was derived from +// the OpenSSL source. +func (c rfc1423Algo) deriveKey(password, salt []byte) []byte { + hash := md5.New() + out := make([]byte, c.keySize) + var digest []byte + + for i := 0; i < len(out); i += len(digest) { + hash.Reset() + hash.Write(digest) + hash.Write(password) + hash.Write(salt) + digest = hash.Sum(digest[:0]) + copy(out[i:], digest) + } + return out +} + +// IsEncryptedPEMBlock returns if the PEM block is password encrypted. +func IsEncryptedPEMBlock(b *pem.Block) bool { + _, ok := b.Headers["DEK-Info"] + return ok +} + +// IncorrectPasswordError is returned when an incorrect password is detected. +var IncorrectPasswordError = errors.New("x509: decryption password incorrect") + +// DecryptPEMBlock takes a password encrypted PEM block and the password used to +// encrypt it and returns a slice of decrypted DER encoded bytes. It inspects +// the DEK-Info header to determine the algorithm used for decryption. If no +// DEK-Info header is present, an error is returned. If an incorrect password +// is detected an IncorrectPasswordError is returned. +func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error) { + dek, ok := b.Headers["DEK-Info"] + if !ok { + return nil, errors.New("x509: no DEK-Info header in block") + } + + idx := strings.Index(dek, ",") + if idx == -1 { + return nil, errors.New("x509: malformed DEK-Info header") + } + + mode, hexIV := dek[:idx], dek[idx+1:] + ciph := cipherByName(mode) + if ciph == nil { + return nil, errors.New("x509: unknown encryption mode") + } + iv, err := hex.DecodeString(hexIV) + if err != nil { + return nil, err + } + if len(iv) != ciph.blockSize { + return nil, errors.New("x509: incorrect IV size") + } + + // Based on the OpenSSL implementation. The salt is the first 8 bytes + // of the initialization vector. + key := ciph.deriveKey(password, iv[:8]) + block, err := ciph.cipherFunc(key) + if err != nil { + return nil, err + } + + data := make([]byte, len(b.Bytes)) + dec := cipher.NewCBCDecrypter(block, iv) + dec.CryptBlocks(data, b.Bytes) + + // Blocks are padded using a scheme where the last n bytes of padding are all + // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423. + // For example: + // [x y z 2 2] + // [x y 7 7 7 7 7 7 7] + // If we detect a bad padding, we assume it is an invalid password. + dlen := len(data) + if dlen == 0 || dlen%ciph.blockSize != 0 { + return nil, errors.New("x509: invalid padding") + } + last := int(data[dlen-1]) + if dlen < last { + return nil, IncorrectPasswordError + } + if last == 0 || last > ciph.blockSize { + return nil, IncorrectPasswordError + } + for _, val := range data[dlen-last:] { + if int(val) != last { + return nil, IncorrectPasswordError + } + } + return data[:dlen-last], nil +} + +// EncryptPEMBlock returns a PEM block of the specified type holding the +// given DER-encoded data encrypted with the specified algorithm and +// password. +func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error) { + ciph := cipherByKey(alg) + if ciph == nil { + return nil, errors.New("x509: unknown encryption mode") + } + iv := make([]byte, ciph.blockSize) + if _, err := io.ReadFull(rand, iv); err != nil { + return nil, errors.New("x509: cannot generate IV: " + err.Error()) + } + // The salt is the first 8 bytes of the initialization vector, + // matching the key derivation in DecryptPEMBlock. + key := ciph.deriveKey(password, iv[:8]) + block, err := ciph.cipherFunc(key) + if err != nil { + return nil, err + } + enc := cipher.NewCBCEncrypter(block, iv) + pad := ciph.blockSize - len(data)%ciph.blockSize + encrypted := make([]byte, len(data), len(data)+pad) + // We could save this copy by encrypting all the whole blocks in + // the data separately, but it doesn't seem worth the additional + // code. + copy(encrypted, data) + // See RFC 1423, section 1.1 + for i := 0; i < pad; i++ { + encrypted = append(encrypted, byte(pad)) + } + enc.CryptBlocks(encrypted, encrypted) + + return &pem.Block{ + Type: blockType, + Headers: map[string]string{ + "Proc-Type": "4,ENCRYPTED", + "DEK-Info": ciph.name + "," + hex.EncodeToString(iv), + }, + Bytes: encrypted, + }, nil +} + +func cipherByName(name string) *rfc1423Algo { + for i := range rfc1423Algos { + alg := &rfc1423Algos[i] + if alg.name == name { + return alg + } + } + return nil +} + +func cipherByKey(key PEMCipher) *rfc1423Algo { + for i := range rfc1423Algos { + alg := &rfc1423Algos[i] + if alg.cipher == key { + return alg + } + } + return nil +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go b/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go new file mode 100755 index 000000000000..638bc6714685 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go @@ -0,0 +1,124 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package x509 + +import ( + "crypto/rsa" + // START CT CHANGES + "github.com/google/certificate-transparency/go/asn1" + // END CT CHANGES + "errors" + "math/big" +) + +// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key. +type pkcs1PrivateKey struct { + Version int + N *big.Int + E int + D *big.Int + P *big.Int + Q *big.Int + // We ignore these values, if present, because rsa will calculate them. + Dp *big.Int `asn1:"optional"` + Dq *big.Int `asn1:"optional"` + Qinv *big.Int `asn1:"optional"` + + AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"` +} + +type pkcs1AdditionalRSAPrime struct { + Prime *big.Int + + // We ignore these values because rsa will calculate them. + Exp *big.Int + Coeff *big.Int +} + +// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form. +func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error) { + var priv pkcs1PrivateKey + rest, err := asn1.Unmarshal(der, &priv) + if len(rest) > 0 { + err = asn1.SyntaxError{Msg: "trailing data"} + return + } + if err != nil { + return + } + + if priv.Version > 1 { + return nil, errors.New("x509: unsupported private key version") + } + + if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 { + return nil, errors.New("x509: private key contains zero or negative value") + } + + key = new(rsa.PrivateKey) + key.PublicKey = rsa.PublicKey{ + E: priv.E, + N: priv.N, + } + + key.D = priv.D + key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes)) + key.Primes[0] = priv.P + key.Primes[1] = priv.Q + for i, a := range priv.AdditionalPrimes { + if a.Prime.Sign() <= 0 { + return nil, errors.New("x509: private key contains zero or negative prime") + } + key.Primes[i+2] = a.Prime + // We ignore the other two values because rsa will calculate + // them as needed. + } + + err = key.Validate() + if err != nil { + return nil, err + } + key.Precompute() + + return +} + +// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. +func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte { + key.Precompute() + + version := 0 + if len(key.Primes) > 2 { + version = 1 + } + + priv := pkcs1PrivateKey{ + Version: version, + N: key.N, + E: key.PublicKey.E, + D: key.D, + P: key.Primes[0], + Q: key.Primes[1], + Dp: key.Precomputed.Dp, + Dq: key.Precomputed.Dq, + Qinv: key.Precomputed.Qinv, + } + + priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues)) + for i, values := range key.Precomputed.CRTValues { + priv.AdditionalPrimes[i].Prime = key.Primes[2+i] + priv.AdditionalPrimes[i].Exp = values.Exp + priv.AdditionalPrimes[i].Coeff = values.Coeff + } + + b, _ := asn1.Marshal(priv) + return b +} + +// rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key. +type rsaPublicKey struct { + N *big.Int + E int +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go b/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go new file mode 100755 index 000000000000..c6ad70b3e6fb --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go @@ -0,0 +1,56 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package x509 + +import ( + // START CT CHANGES + "github.com/google/certificate-transparency/go/asn1" + "github.com/google/certificate-transparency/go/x509/pkix" + // END CT CHANGES + "errors" + "fmt" +) + +// pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See +// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn +// and RFC5208. +type pkcs8 struct { + Version int + Algo pkix.AlgorithmIdentifier + PrivateKey []byte + // optional attributes omitted. +} + +// ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See +// http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208. +func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) { + var privKey pkcs8 + if _, err := asn1.Unmarshal(der, &privKey); err != nil { + return nil, err + } + switch { + case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA): + key, err = ParsePKCS1PrivateKey(privKey.PrivateKey) + if err != nil { + return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error()) + } + return key, nil + + case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA): + bytes := privKey.Algo.Parameters.FullBytes + namedCurveOID := new(asn1.ObjectIdentifier) + if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil { + namedCurveOID = nil + } + key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey) + if err != nil { + return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error()) + } + return key, nil + + default: + return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm) + } +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go b/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go new file mode 100755 index 000000000000..67db6ae5e3ee --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go @@ -0,0 +1,173 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package pkix contains shared, low level structures used for ASN.1 parsing +// and serialization of X.509 certificates, CRL and OCSP. +package pkix + +import ( + // START CT CHANGES + "github.com/google/certificate-transparency/go/asn1" + // END CT CHANGES + "math/big" + "time" +) + +// AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC +// 5280, section 4.1.1.2. +type AlgorithmIdentifier struct { + Algorithm asn1.ObjectIdentifier + Parameters asn1.RawValue `asn1:"optional"` +} + +type RDNSequence []RelativeDistinguishedNameSET + +type RelativeDistinguishedNameSET []AttributeTypeAndValue + +// AttributeTypeAndValue mirrors the ASN.1 structure of the same name in +// http://tools.ietf.org/html/rfc5280#section-4.1.2.4 +type AttributeTypeAndValue struct { + Type asn1.ObjectIdentifier + Value interface{} +} + +// Extension represents the ASN.1 structure of the same name. See RFC +// 5280, section 4.2. +type Extension struct { + Id asn1.ObjectIdentifier + Critical bool `asn1:"optional"` + Value []byte +} + +// Name represents an X.509 distinguished name. This only includes the common +// elements of a DN. Additional elements in the name are ignored. +type Name struct { + Country, Organization, OrganizationalUnit []string + Locality, Province []string + StreetAddress, PostalCode []string + SerialNumber, CommonName string + + Names []AttributeTypeAndValue +} + +func (n *Name) FillFromRDNSequence(rdns *RDNSequence) { + for _, rdn := range *rdns { + if len(rdn) == 0 { + continue + } + atv := rdn[0] + n.Names = append(n.Names, atv) + value, ok := atv.Value.(string) + if !ok { + continue + } + + t := atv.Type + if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 { + switch t[3] { + case 3: + n.CommonName = value + case 5: + n.SerialNumber = value + case 6: + n.Country = append(n.Country, value) + case 7: + n.Locality = append(n.Locality, value) + case 8: + n.Province = append(n.Province, value) + case 9: + n.StreetAddress = append(n.StreetAddress, value) + case 10: + n.Organization = append(n.Organization, value) + case 11: + n.OrganizationalUnit = append(n.OrganizationalUnit, value) + case 17: + n.PostalCode = append(n.PostalCode, value) + } + } + } +} + +var ( + oidCountry = []int{2, 5, 4, 6} + oidOrganization = []int{2, 5, 4, 10} + oidOrganizationalUnit = []int{2, 5, 4, 11} + oidCommonName = []int{2, 5, 4, 3} + oidSerialNumber = []int{2, 5, 4, 5} + oidLocality = []int{2, 5, 4, 7} + oidProvince = []int{2, 5, 4, 8} + oidStreetAddress = []int{2, 5, 4, 9} + oidPostalCode = []int{2, 5, 4, 17} +) + +// appendRDNs appends a relativeDistinguishedNameSET to the given RDNSequence +// and returns the new value. The relativeDistinguishedNameSET contains an +// attributeTypeAndValue for each of the given values. See RFC 5280, A.1, and +// search for AttributeTypeAndValue. +func appendRDNs(in RDNSequence, values []string, oid asn1.ObjectIdentifier) RDNSequence { + if len(values) == 0 { + return in + } + + s := make([]AttributeTypeAndValue, len(values)) + for i, value := range values { + s[i].Type = oid + s[i].Value = value + } + + return append(in, s) +} + +func (n Name) ToRDNSequence() (ret RDNSequence) { + ret = appendRDNs(ret, n.Country, oidCountry) + ret = appendRDNs(ret, n.Organization, oidOrganization) + ret = appendRDNs(ret, n.OrganizationalUnit, oidOrganizationalUnit) + ret = appendRDNs(ret, n.Locality, oidLocality) + ret = appendRDNs(ret, n.Province, oidProvince) + ret = appendRDNs(ret, n.StreetAddress, oidStreetAddress) + ret = appendRDNs(ret, n.PostalCode, oidPostalCode) + if len(n.CommonName) > 0 { + ret = appendRDNs(ret, []string{n.CommonName}, oidCommonName) + } + if len(n.SerialNumber) > 0 { + ret = appendRDNs(ret, []string{n.SerialNumber}, oidSerialNumber) + } + + return ret +} + +// CertificateList represents the ASN.1 structure of the same name. See RFC +// 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the +// signature. +type CertificateList struct { + TBSCertList TBSCertificateList + SignatureAlgorithm AlgorithmIdentifier + SignatureValue asn1.BitString +} + +// HasExpired reports whether now is past the expiry time of certList. +func (certList *CertificateList) HasExpired(now time.Time) bool { + return now.After(certList.TBSCertList.NextUpdate) +} + +// TBSCertificateList represents the ASN.1 structure of the same name. See RFC +// 5280, section 5.1. +type TBSCertificateList struct { + Raw asn1.RawContent + Version int `asn1:"optional,default:2"` + Signature AlgorithmIdentifier + Issuer RDNSequence + ThisUpdate time.Time + NextUpdate time.Time + RevokedCertificates []RevokedCertificate `asn1:"optional"` + Extensions []Extension `asn1:"tag:0,optional,explicit"` +} + +// RevokedCertificate represents the ASN.1 structure of the same name. See RFC +// 5280, section 5.1. +type RevokedCertificate struct { + SerialNumber *big.Int + RevocationTime time.Time + Extensions []Extension `asn1:"optional"` +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root.go b/vendor/github.com/google/certificate-transparency/go/x509/root.go new file mode 100755 index 000000000000..8aae14e09ee7 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root.go @@ -0,0 +1,17 @@ +// Copyright 2012 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 x509 + +import "sync" + +var ( + once sync.Once + systemRoots *CertPool +) + +func systemRootsPool() *CertPool { + once.Do(initSystemRoots) + return systemRoots +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go b/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go new file mode 100755 index 000000000000..3d3fa4e4d19b --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go @@ -0,0 +1,83 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build darwin,cgo + +package x509 + +/* +#cgo CFLAGS: -mmacosx-version-min=10.6 -D__MAC_OS_X_VERSION_MAX_ALLOWED=1060 +#cgo LDFLAGS: -framework CoreFoundation -framework Security + +#include +#include + +// FetchPEMRootsCTX509 fetches the system's list of trusted X.509 root certificates. +// +// On success it returns 0 and fills pemRoots with a CFDataRef that contains the extracted root +// certificates of the system. On failure, the function returns -1. +// +// Note: The CFDataRef returned in pemRoots must be released (using CFRelease) after +// we've consumed its content. +int FetchPEMRootsCTX509(CFDataRef *pemRoots) { + if (pemRoots == NULL) { + return -1; + } + + CFArrayRef certs = NULL; + OSStatus err = SecTrustCopyAnchorCertificates(&certs); + if (err != noErr) { + return -1; + } + + CFMutableDataRef combinedData = CFDataCreateMutable(kCFAllocatorDefault, 0); + int i, ncerts = CFArrayGetCount(certs); + for (i = 0; i < ncerts; i++) { + CFDataRef data = NULL; + SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, i); + if (cert == NULL) { + continue; + } + + // Note: SecKeychainItemExport is deprecated as of 10.7 in favor of SecItemExport. + // Once we support weak imports via cgo we should prefer that, and fall back to this + // for older systems. + err = SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data); + if (err != noErr) { + continue; + } + + if (data != NULL) { + CFDataAppendBytes(combinedData, CFDataGetBytePtr(data), CFDataGetLength(data)); + CFRelease(data); + } + } + + CFRelease(certs); + + *pemRoots = combinedData; + return 0; +} +*/ +import "C" +import "unsafe" + +func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { + return nil, nil +} + +func initSystemRoots() { + roots := NewCertPool() + + var data C.CFDataRef = nil + err := C.FetchPEMRootsCTX509(&data) + if err == -1 { + return + } + + defer C.CFRelease(C.CFTypeRef(data)) + buf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data))) + roots.AppendCertsFromPEM(buf) + systemRoots = roots +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go b/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go new file mode 100755 index 000000000000..9965caadee3a --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go @@ -0,0 +1,33 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build plan9 + +package x509 + +import "io/ioutil" + +// Possible certificate files; stop after finding one. +var certFiles = []string{ + "/sys/lib/tls/ca.pem", +} + +func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { + return nil, nil +} + +func initSystemRoots() { + roots := NewCertPool() + for _, file := range certFiles { + data, err := ioutil.ReadFile(file) + if err == nil { + roots.AppendCertsFromPEM(data) + systemRoots = roots + return + } + } + + // All of the files failed to load. systemRoots will be nil which will + // trigger a specific error at verification time. +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go b/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go new file mode 100755 index 000000000000..4c742ccc3715 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go @@ -0,0 +1,14 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build darwin,!cgo + +package x509 + +func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { + return nil, nil +} + +func initSystemRoots() { +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go b/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go new file mode 100755 index 000000000000..324f855b135c --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go @@ -0,0 +1,37 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build dragonfly freebsd linux openbsd netbsd + +package x509 + +import "io/ioutil" + +// Possible certificate files; stop after finding one. +var certFiles = []string{ + "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc. + "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL + "/etc/ssl/ca-bundle.pem", // OpenSUSE + "/etc/ssl/cert.pem", // OpenBSD + "/usr/local/share/certs/ca-root-nss.crt", // FreeBSD/DragonFly +} + +func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { + return nil, nil +} + +func initSystemRoots() { + roots := NewCertPool() + for _, file := range certFiles { + data, err := ioutil.ReadFile(file) + if err == nil { + roots.AppendCertsFromPEM(data) + systemRoots = roots + return + } + } + + // All of the files failed to load. systemRoots will be nil which will + // trigger a specific error at verification time. +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go b/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go new file mode 100755 index 000000000000..81018b78fe66 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go @@ -0,0 +1,229 @@ +// Copyright 2012 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 x509 + +import ( + "errors" + "syscall" + "unsafe" +) + +// Creates a new *syscall.CertContext representing the leaf certificate in an in-memory +// certificate store containing itself and all of the intermediate certificates specified +// in the opts.Intermediates CertPool. +// +// A pointer to the in-memory store is available in the returned CertContext's Store field. +// The store is automatically freed when the CertContext is freed using +// syscall.CertFreeCertificateContext. +func createStoreContext(leaf *Certificate, opts *VerifyOptions) (*syscall.CertContext, error) { + var storeCtx *syscall.CertContext + + leafCtx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &leaf.Raw[0], uint32(len(leaf.Raw))) + if err != nil { + return nil, err + } + defer syscall.CertFreeCertificateContext(leafCtx) + + handle, err := syscall.CertOpenStore(syscall.CERT_STORE_PROV_MEMORY, 0, 0, syscall.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 0) + if err != nil { + return nil, err + } + defer syscall.CertCloseStore(handle, 0) + + err = syscall.CertAddCertificateContextToStore(handle, leafCtx, syscall.CERT_STORE_ADD_ALWAYS, &storeCtx) + if err != nil { + return nil, err + } + + if opts.Intermediates != nil { + for _, intermediate := range opts.Intermediates.certs { + ctx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &intermediate.Raw[0], uint32(len(intermediate.Raw))) + if err != nil { + return nil, err + } + + err = syscall.CertAddCertificateContextToStore(handle, ctx, syscall.CERT_STORE_ADD_ALWAYS, nil) + syscall.CertFreeCertificateContext(ctx) + if err != nil { + return nil, err + } + } + } + + return storeCtx, nil +} + +// extractSimpleChain extracts the final certificate chain from a CertSimpleChain. +func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) { + if simpleChain == nil || count == 0 { + return nil, errors.New("x509: invalid simple chain") + } + + simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:] + lastChain := simpleChains[count-1] + elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:] + for i := 0; i < int(lastChain.NumElements); i++ { + // Copy the buf, since ParseCertificate does not create its own copy. + cert := elements[i].CertContext + encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:] + buf := make([]byte, cert.Length) + copy(buf, encodedCert[:]) + parsedCert, err := ParseCertificate(buf) + if err != nil { + return nil, err + } + chain = append(chain, parsedCert) + } + + return chain, nil +} + +// checkChainTrustStatus checks the trust status of the certificate chain, translating +// any errors it finds into Go errors in the process. +func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error { + if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR { + status := chainCtx.TrustStatus.ErrorStatus + switch status { + case syscall.CERT_TRUST_IS_NOT_TIME_VALID: + return CertificateInvalidError{c, Expired} + default: + return UnknownAuthorityError{c, nil, nil} + } + } + return nil +} + +// checkChainSSLServerPolicy checks that the certificate chain in chainCtx is valid for +// use as a certificate chain for a SSL/TLS server. +func checkChainSSLServerPolicy(c *Certificate, chainCtx *syscall.CertChainContext, opts *VerifyOptions) error { + servernamep, err := syscall.UTF16PtrFromString(opts.DNSName) + if err != nil { + return err + } + sslPara := &syscall.SSLExtraCertChainPolicyPara{ + AuthType: syscall.AUTHTYPE_SERVER, + ServerName: servernamep, + } + sslPara.Size = uint32(unsafe.Sizeof(*sslPara)) + + para := &syscall.CertChainPolicyPara{ + ExtraPolicyPara: uintptr(unsafe.Pointer(sslPara)), + } + para.Size = uint32(unsafe.Sizeof(*para)) + + status := syscall.CertChainPolicyStatus{} + err = syscall.CertVerifyCertificateChainPolicy(syscall.CERT_CHAIN_POLICY_SSL, chainCtx, para, &status) + if err != nil { + return err + } + + // TODO(mkrautz): use the lChainIndex and lElementIndex fields + // of the CertChainPolicyStatus to provide proper context, instead + // using c. + if status.Error != 0 { + switch status.Error { + case syscall.CERT_E_EXPIRED: + return CertificateInvalidError{c, Expired} + case syscall.CERT_E_CN_NO_MATCH: + return HostnameError{c, opts.DNSName} + case syscall.CERT_E_UNTRUSTEDROOT: + return UnknownAuthorityError{c, nil, nil} + default: + return UnknownAuthorityError{c, nil, nil} + } + } + + return nil +} + +// systemVerify is like Verify, except that it uses CryptoAPI calls +// to build certificate chains and verify them. +func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { + hasDNSName := opts != nil && len(opts.DNSName) > 0 + + storeCtx, err := createStoreContext(c, opts) + if err != nil { + return nil, err + } + defer syscall.CertFreeCertificateContext(storeCtx) + + para := new(syscall.CertChainPara) + para.Size = uint32(unsafe.Sizeof(*para)) + + // If there's a DNSName set in opts, assume we're verifying + // a certificate from a TLS server. + if hasDNSName { + oids := []*byte{ + &syscall.OID_PKIX_KP_SERVER_AUTH[0], + // Both IE and Chrome allow certificates with + // Server Gated Crypto as well. Some certificates + // in the wild require them. + &syscall.OID_SERVER_GATED_CRYPTO[0], + &syscall.OID_SGC_NETSCAPE[0], + } + para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_OR + para.RequestedUsage.Usage.Length = uint32(len(oids)) + para.RequestedUsage.Usage.UsageIdentifiers = &oids[0] + } else { + para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_AND + para.RequestedUsage.Usage.Length = 0 + para.RequestedUsage.Usage.UsageIdentifiers = nil + } + + var verifyTime *syscall.Filetime + if opts != nil && !opts.CurrentTime.IsZero() { + ft := syscall.NsecToFiletime(opts.CurrentTime.UnixNano()) + verifyTime = &ft + } + + // CertGetCertificateChain will traverse Windows's root stores + // in an attempt to build a verified certificate chain. Once + // it has found a verified chain, it stops. MSDN docs on + // CERT_CHAIN_CONTEXT: + // + // When a CERT_CHAIN_CONTEXT is built, the first simple chain + // begins with an end certificate and ends with a self-signed + // certificate. If that self-signed certificate is not a root + // or otherwise trusted certificate, an attempt is made to + // build a new chain. CTLs are used to create the new chain + // beginning with the self-signed certificate from the original + // chain as the end certificate of the new chain. This process + // continues building additional simple chains until the first + // self-signed certificate is a trusted certificate or until + // an additional simple chain cannot be built. + // + // The result is that we'll only get a single trusted chain to + // return to our caller. + var chainCtx *syscall.CertChainContext + err = syscall.CertGetCertificateChain(syscall.Handle(0), storeCtx, verifyTime, storeCtx.Store, para, 0, 0, &chainCtx) + if err != nil { + return nil, err + } + defer syscall.CertFreeCertificateChain(chainCtx) + + err = checkChainTrustStatus(c, chainCtx) + if err != nil { + return nil, err + } + + if hasDNSName { + err = checkChainSSLServerPolicy(c, chainCtx, opts) + if err != nil { + return nil, err + } + } + + chain, err := extractSimpleChain(chainCtx.Chains, int(chainCtx.ChainCount)) + if err != nil { + return nil, err + } + + chains = append(chains, chain) + + return chains, nil +} + +func initSystemRoots() { +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/sec1.go b/vendor/github.com/google/certificate-transparency/go/x509/sec1.go new file mode 100755 index 000000000000..dbc255f0caa9 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/sec1.go @@ -0,0 +1,85 @@ +// Copyright 2012 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 x509 + +import ( + "crypto/ecdsa" + "crypto/elliptic" + // START CT CHANGES + "github.com/google/certificate-transparency/go/asn1" + // START CT CHANGES + "errors" + "fmt" + "math/big" +) + +const ecPrivKeyVersion = 1 + +// ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure. +// References: +// RFC5915 +// SEC1 - http://www.secg.org/download/aid-780/sec1-v2.pdf +// Per RFC5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in +// most cases it is not. +type ecPrivateKey struct { + Version int + PrivateKey []byte + NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"` + PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"` +} + +// ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. +func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error) { + return parseECPrivateKey(nil, der) +} + +// MarshalECPrivateKey marshals an EC private key into ASN.1, DER format. +func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) { + oid, ok := oidFromNamedCurve(key.Curve) + if !ok { + return nil, errors.New("x509: unknown elliptic curve") + } + return asn1.Marshal(ecPrivateKey{ + Version: 1, + PrivateKey: key.D.Bytes(), + NamedCurveOID: oid, + PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)}, + }) +} + +// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. +// The OID for the named curve may be provided from another source (such as +// the PKCS8 container) - if it is provided then use this instead of the OID +// that may exist in the EC private key structure. +func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) { + var privKey ecPrivateKey + if _, err := asn1.Unmarshal(der, &privKey); err != nil { + return nil, errors.New("x509: failed to parse EC private key: " + err.Error()) + } + if privKey.Version != ecPrivKeyVersion { + return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version) + } + + var curve elliptic.Curve + if namedCurveOID != nil { + curve = namedCurveFromOID(*namedCurveOID) + } else { + curve = namedCurveFromOID(privKey.NamedCurveOID) + } + if curve == nil { + return nil, errors.New("x509: unknown elliptic curve") + } + + k := new(big.Int).SetBytes(privKey.PrivateKey) + if k.Cmp(curve.Params().N) >= 0 { + return nil, errors.New("x509: invalid elliptic curve private key value") + } + priv := new(ecdsa.PrivateKey) + priv.Curve = curve + priv.D = k + priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey) + + return priv, nil +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/verify.go b/vendor/github.com/google/certificate-transparency/go/x509/verify.go new file mode 100755 index 000000000000..e82dbc12b0b6 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/verify.go @@ -0,0 +1,476 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package x509 + +import ( + "fmt" + "net" + "runtime" + "strings" + "time" + "unicode/utf8" +) + +type InvalidReason int + +const ( + // NotAuthorizedToSign results when a certificate is signed by another + // which isn't marked as a CA certificate. + NotAuthorizedToSign InvalidReason = iota + // Expired results when a certificate has expired, based on the time + // given in the VerifyOptions. + Expired + // CANotAuthorizedForThisName results when an intermediate or root + // certificate has a name constraint which doesn't include the name + // being checked. + CANotAuthorizedForThisName + // TooManyIntermediates results when a path length constraint is + // violated. + TooManyIntermediates + // IncompatibleUsage results when the certificate's key usage indicates + // that it may only be used for a different purpose. + IncompatibleUsage +) + +// CertificateInvalidError results when an odd error occurs. Users of this +// library probably want to handle all these errors uniformly. +type CertificateInvalidError struct { + Cert *Certificate + Reason InvalidReason +} + +func (e CertificateInvalidError) Error() string { + switch e.Reason { + case NotAuthorizedToSign: + return "x509: certificate is not authorized to sign other certificates" + case Expired: + return "x509: certificate has expired or is not yet valid" + case CANotAuthorizedForThisName: + return "x509: a root or intermediate certificate is not authorized to sign in this domain" + case TooManyIntermediates: + return "x509: too many intermediates for path length constraint" + case IncompatibleUsage: + return "x509: certificate specifies an incompatible key usage" + } + return "x509: unknown error" +} + +// HostnameError results when the set of authorized names doesn't match the +// requested name. +type HostnameError struct { + Certificate *Certificate + Host string +} + +func (h HostnameError) Error() string { + c := h.Certificate + + var valid string + if ip := net.ParseIP(h.Host); ip != nil { + // Trying to validate an IP + if len(c.IPAddresses) == 0 { + return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs" + } + for _, san := range c.IPAddresses { + if len(valid) > 0 { + valid += ", " + } + valid += san.String() + } + } else { + if len(c.DNSNames) > 0 { + valid = strings.Join(c.DNSNames, ", ") + } else { + valid = c.Subject.CommonName + } + } + return "x509: certificate is valid for " + valid + ", not " + h.Host +} + +// UnknownAuthorityError results when the certificate issuer is unknown +type UnknownAuthorityError struct { + cert *Certificate + // hintErr contains an error that may be helpful in determining why an + // authority wasn't found. + hintErr error + // hintCert contains a possible authority certificate that was rejected + // because of the error in hintErr. + hintCert *Certificate +} + +func (e UnknownAuthorityError) Error() string { + s := "x509: certificate signed by unknown authority" + if e.hintErr != nil { + certName := e.hintCert.Subject.CommonName + if len(certName) == 0 { + if len(e.hintCert.Subject.Organization) > 0 { + certName = e.hintCert.Subject.Organization[0] + } + certName = "serial:" + e.hintCert.SerialNumber.String() + } + s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName) + } + return s +} + +// SystemRootsError results when we fail to load the system root certificates. +type SystemRootsError struct { +} + +func (e SystemRootsError) Error() string { + return "x509: failed to load system roots and no roots provided" +} + +// VerifyOptions contains parameters for Certificate.Verify. It's a structure +// because other PKIX verification APIs have ended up needing many options. +type VerifyOptions struct { + DNSName string + Intermediates *CertPool + Roots *CertPool // if nil, the system roots are used + CurrentTime time.Time // if zero, the current time is used + DisableTimeChecks bool + // KeyUsage specifies which Extended Key Usage values are acceptable. + // An empty list means ExtKeyUsageServerAuth. Key usage is considered a + // constraint down the chain which mirrors Windows CryptoAPI behaviour, + // but not the spec. To accept any key usage, include ExtKeyUsageAny. + KeyUsages []ExtKeyUsage +} + +const ( + leafCertificate = iota + intermediateCertificate + rootCertificate +) + +// isValid performs validity checks on the c. +func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error { + if !opts.DisableTimeChecks { + now := opts.CurrentTime + if now.IsZero() { + now = time.Now() + } + if now.Before(c.NotBefore) || now.After(c.NotAfter) { + return CertificateInvalidError{c, Expired} + } + } + + if len(c.PermittedDNSDomains) > 0 { + ok := false + for _, domain := range c.PermittedDNSDomains { + if opts.DNSName == domain || + (strings.HasSuffix(opts.DNSName, domain) && + len(opts.DNSName) >= 1+len(domain) && + opts.DNSName[len(opts.DNSName)-len(domain)-1] == '.') { + ok = true + break + } + } + + if !ok { + return CertificateInvalidError{c, CANotAuthorizedForThisName} + } + } + + // KeyUsage status flags are ignored. From Engineering Security, Peter + // Gutmann: A European government CA marked its signing certificates as + // being valid for encryption only, but no-one noticed. Another + // European CA marked its signature keys as not being valid for + // signatures. A different CA marked its own trusted root certificate + // as being invalid for certificate signing. Another national CA + // distributed a certificate to be used to encrypt data for the + // country’s tax authority that was marked as only being usable for + // digital signatures but not for encryption. Yet another CA reversed + // the order of the bit flags in the keyUsage due to confusion over + // encoding endianness, essentially setting a random keyUsage in + // certificates that it issued. Another CA created a self-invalidating + // certificate by adding a certificate policy statement stipulating + // that the certificate had to be used strictly as specified in the + // keyUsage, and a keyUsage containing a flag indicating that the RSA + // encryption key could only be used for Diffie-Hellman key agreement. + + if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { + return CertificateInvalidError{c, NotAuthorizedToSign} + } + + if c.BasicConstraintsValid && c.MaxPathLen >= 0 { + numIntermediates := len(currentChain) - 1 + if numIntermediates > c.MaxPathLen { + return CertificateInvalidError{c, TooManyIntermediates} + } + } + + return nil +} + +// Verify attempts to verify c by building one or more chains from c to a +// certificate in opts.Roots, using certificates in opts.Intermediates if +// needed. If successful, it returns one or more chains where the first +// element of the chain is c and the last element is from opts.Roots. +// +// WARNING: this doesn't do any revocation checking. +func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) { + // Use Windows's own verification and chain building. + if opts.Roots == nil && runtime.GOOS == "windows" { + return c.systemVerify(&opts) + } + + if opts.Roots == nil { + opts.Roots = systemRootsPool() + if opts.Roots == nil { + return nil, SystemRootsError{} + } + } + + err = c.isValid(leafCertificate, nil, &opts) + if err != nil { + return + } + + if len(opts.DNSName) > 0 { + err = c.VerifyHostname(opts.DNSName) + if err != nil { + return + } + } + + candidateChains, err := c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts) + if err != nil { + return + } + + keyUsages := opts.KeyUsages + if len(keyUsages) == 0 { + keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth} + } + + // If any key usage is acceptable then we're done. + for _, usage := range keyUsages { + if usage == ExtKeyUsageAny { + chains = candidateChains + return + } + } + + for _, candidate := range candidateChains { + if checkChainForKeyUsage(candidate, keyUsages) { + chains = append(chains, candidate) + } + } + + if len(chains) == 0 { + err = CertificateInvalidError{c, IncompatibleUsage} + } + + return +} + +func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate { + n := make([]*Certificate, len(chain)+1) + copy(n, chain) + n[len(chain)] = cert + return n +} + +func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) { + possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c) + for _, rootNum := range possibleRoots { + root := opts.Roots.certs[rootNum] + err = root.isValid(rootCertificate, currentChain, opts) + if err != nil { + continue + } + chains = append(chains, appendToFreshChain(currentChain, root)) + } + + possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c) +nextIntermediate: + for _, intermediateNum := range possibleIntermediates { + intermediate := opts.Intermediates.certs[intermediateNum] + for _, cert := range currentChain { + if cert == intermediate { + continue nextIntermediate + } + } + err = intermediate.isValid(intermediateCertificate, currentChain, opts) + if err != nil { + continue + } + var childChains [][]*Certificate + childChains, ok := cache[intermediateNum] + if !ok { + childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts) + cache[intermediateNum] = childChains + } + chains = append(chains, childChains...) + } + + if len(chains) > 0 { + err = nil + } + + if len(chains) == 0 && err == nil { + hintErr := rootErr + hintCert := failedRoot + if hintErr == nil { + hintErr = intermediateErr + hintCert = failedIntermediate + } + err = UnknownAuthorityError{c, hintErr, hintCert} + } + + return +} + +func matchHostnames(pattern, host string) bool { + if len(pattern) == 0 || len(host) == 0 { + return false + } + + patternParts := strings.Split(pattern, ".") + hostParts := strings.Split(host, ".") + + if len(patternParts) != len(hostParts) { + return false + } + + for i, patternPart := range patternParts { + if patternPart == "*" { + continue + } + if patternPart != hostParts[i] { + return false + } + } + + return true +} + +// toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use +// an explicitly ASCII function to avoid any sharp corners resulting from +// performing Unicode operations on DNS labels. +func toLowerCaseASCII(in string) string { + // If the string is already lower-case then there's nothing to do. + isAlreadyLowerCase := true + for _, c := range in { + if c == utf8.RuneError { + // If we get a UTF-8 error then there might be + // upper-case ASCII bytes in the invalid sequence. + isAlreadyLowerCase = false + break + } + if 'A' <= c && c <= 'Z' { + isAlreadyLowerCase = false + break + } + } + + if isAlreadyLowerCase { + return in + } + + out := []byte(in) + for i, c := range out { + if 'A' <= c && c <= 'Z' { + out[i] += 'a' - 'A' + } + } + return string(out) +} + +// VerifyHostname returns nil if c is a valid certificate for the named host. +// Otherwise it returns an error describing the mismatch. +func (c *Certificate) VerifyHostname(h string) error { + // IP addresses may be written in [ ]. + candidateIP := h + if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' { + candidateIP = h[1 : len(h)-1] + } + if ip := net.ParseIP(candidateIP); ip != nil { + // We only match IP addresses against IP SANs. + // https://tools.ietf.org/html/rfc6125#appendix-B.2 + for _, candidate := range c.IPAddresses { + if ip.Equal(candidate) { + return nil + } + } + return HostnameError{c, candidateIP} + } + + lowered := toLowerCaseASCII(h) + + if len(c.DNSNames) > 0 { + for _, match := range c.DNSNames { + if matchHostnames(toLowerCaseASCII(match), lowered) { + return nil + } + } + // If Subject Alt Name is given, we ignore the common name. + } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { + return nil + } + + return HostnameError{c, h} +} + +func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool { + usages := make([]ExtKeyUsage, len(keyUsages)) + copy(usages, keyUsages) + + if len(chain) == 0 { + return false + } + + usagesRemaining := len(usages) + + // We walk down the list and cross out any usages that aren't supported + // by each certificate. If we cross out all the usages, then the chain + // is unacceptable. + + for i := len(chain) - 1; i >= 0; i-- { + cert := chain[i] + if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 { + // The certificate doesn't have any extended key usage specified. + continue + } + + for _, usage := range cert.ExtKeyUsage { + if usage == ExtKeyUsageAny { + // The certificate is explicitly good for any usage. + continue + } + } + + const invalidUsage ExtKeyUsage = -1 + + NextRequestedUsage: + for i, requestedUsage := range usages { + if requestedUsage == invalidUsage { + continue + } + + for _, usage := range cert.ExtKeyUsage { + if requestedUsage == usage { + continue NextRequestedUsage + } else if requestedUsage == ExtKeyUsageServerAuth && + (usage == ExtKeyUsageNetscapeServerGatedCrypto || + usage == ExtKeyUsageMicrosoftServerGatedCrypto) { + // In order to support COMODO + // certificate chains, we have to + // accept Netscape or Microsoft SGC + // usages as equal to ServerAuth. + continue NextRequestedUsage + } + } + + usages[i] = invalidUsage + usagesRemaining-- + if usagesRemaining == 0 { + return false + } + } + } + + return true +} diff --git a/vendor/github.com/google/certificate-transparency/go/x509/x509.go b/vendor/github.com/google/certificate-transparency/go/x509/x509.go new file mode 100755 index 000000000000..cda72200f8d8 --- /dev/null +++ b/vendor/github.com/google/certificate-transparency/go/x509/x509.go @@ -0,0 +1,1622 @@ +// Copyright 2009 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 x509 parses X.509-encoded keys and certificates. +// +// START CT CHANGES +// This is a fork of the go library crypto/x509 package, it's more relaxed +// about certificates that it'll accept, and exports the TBSCertificate +// structure. +// END CT CHANGES +package x509 + +import ( + "bytes" + "crypto" + "crypto/dsa" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rsa" + "crypto/sha1" + // START CT CHANGES + "github.com/google/certificate-transparency/go/asn1" + "github.com/google/certificate-transparency/go/x509/pkix" + // END CT CHANGES + "encoding/pem" + "errors" + // START CT CHANGES + "fmt" + // END CT CHANGES + "io" + "math/big" + "net" + "time" +) + +// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo +// in RFC 3280. +type pkixPublicKey struct { + Algo pkix.AlgorithmIdentifier + BitString asn1.BitString +} + +// ParsePKIXPublicKey parses a DER encoded public key. These values are +// typically found in PEM blocks with "BEGIN PUBLIC KEY". +func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { + var pki publicKeyInfo + if _, err = asn1.Unmarshal(derBytes, &pki); err != nil { + return + } + algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) + if algo == UnknownPublicKeyAlgorithm { + return nil, errors.New("x509: unknown public key algorithm") + } + return parsePublicKey(algo, &pki) +} + +func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { + switch pub := pub.(type) { + case *rsa.PublicKey: + publicKeyBytes, err = asn1.Marshal(rsaPublicKey{ + N: pub.N, + E: pub.E, + }) + publicKeyAlgorithm.Algorithm = oidPublicKeyRSA + // This is a NULL parameters value which is technically + // superfluous, but most other code includes it and, by + // doing this, we match their public key hashes. + publicKeyAlgorithm.Parameters = asn1.RawValue{ + Tag: 5, + } + case *ecdsa.PublicKey: + publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) + oid, ok := oidFromNamedCurve(pub.Curve) + if !ok { + return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") + } + publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA + var paramBytes []byte + paramBytes, err = asn1.Marshal(oid) + if err != nil { + return + } + publicKeyAlgorithm.Parameters.FullBytes = paramBytes + default: + return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported") + } + + return publicKeyBytes, publicKeyAlgorithm, nil +} + +// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. +func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { + var publicKeyBytes []byte + var publicKeyAlgorithm pkix.AlgorithmIdentifier + var err error + + if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { + return nil, err + } + + pkix := pkixPublicKey{ + Algo: publicKeyAlgorithm, + BitString: asn1.BitString{ + Bytes: publicKeyBytes, + BitLength: 8 * len(publicKeyBytes), + }, + } + + ret, _ := asn1.Marshal(pkix) + return ret, nil +} + +// These structures reflect the ASN.1 structure of X.509 certificates.: + +type certificate struct { + Raw asn1.RawContent + TBSCertificate tbsCertificate + SignatureAlgorithm pkix.AlgorithmIdentifier + SignatureValue asn1.BitString +} + +type tbsCertificate struct { + Raw asn1.RawContent + Version int `asn1:"optional,explicit,default:1,tag:0"` + SerialNumber *big.Int + SignatureAlgorithm pkix.AlgorithmIdentifier + Issuer asn1.RawValue + Validity validity + Subject asn1.RawValue + PublicKey publicKeyInfo + UniqueId asn1.BitString `asn1:"optional,tag:1"` + SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` + Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` +} + +type dsaAlgorithmParameters struct { + P, Q, G *big.Int +} + +type dsaSignature struct { + R, S *big.Int +} + +type ecdsaSignature dsaSignature + +type validity struct { + NotBefore, NotAfter time.Time +} + +type publicKeyInfo struct { + Raw asn1.RawContent + Algorithm pkix.AlgorithmIdentifier + PublicKey asn1.BitString +} + +// RFC 5280, 4.2.1.1 +type authKeyId struct { + Id []byte `asn1:"optional,tag:0"` +} + +type SignatureAlgorithm int + +const ( + UnknownSignatureAlgorithm SignatureAlgorithm = iota + MD2WithRSA + MD5WithRSA + SHA1WithRSA + SHA256WithRSA + SHA384WithRSA + SHA512WithRSA + DSAWithSHA1 + DSAWithSHA256 + ECDSAWithSHA1 + ECDSAWithSHA256 + ECDSAWithSHA384 + ECDSAWithSHA512 +) + +type PublicKeyAlgorithm int + +const ( + UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota + RSA + DSA + ECDSA +) + +// OIDs for signature algorithms +// +// pkcs-1 OBJECT IDENTIFIER ::= { +// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } +// +// +// RFC 3279 2.2.1 RSA Signature Algorithms +// +// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } +// +// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } +// +// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } +// +// dsaWithSha1 OBJECT IDENTIFIER ::= { +// iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } +// +// RFC 3279 2.2.3 ECDSA Signature Algorithm +// +// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { +// iso(1) member-body(2) us(840) ansi-x962(10045) +// signatures(4) ecdsa-with-SHA1(1)} +// +// +// RFC 4055 5 PKCS #1 Version 1.5 +// +// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } +// +// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } +// +// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } +// +// +// RFC 5758 3.1 DSA Signature Algorithms +// +// dsaWithSha256 OBJECT IDENTIFIER ::= { +// joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) +// csor(3) algorithms(4) id-dsa-with-sha2(3) 2} +// +// RFC 5758 3.2 ECDSA Signature Algorithm +// +// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) +// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } +// +// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) +// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } +// +// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) +// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } + +var ( + oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} + oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} + oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} + oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} + oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} + oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} + oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} + oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2} + oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} + oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} + oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} + oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} +) + +func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm { + switch { + case oid.Equal(oidSignatureMD2WithRSA): + return MD2WithRSA + case oid.Equal(oidSignatureMD5WithRSA): + return MD5WithRSA + case oid.Equal(oidSignatureSHA1WithRSA): + return SHA1WithRSA + case oid.Equal(oidSignatureSHA256WithRSA): + return SHA256WithRSA + case oid.Equal(oidSignatureSHA384WithRSA): + return SHA384WithRSA + case oid.Equal(oidSignatureSHA512WithRSA): + return SHA512WithRSA + case oid.Equal(oidSignatureDSAWithSHA1): + return DSAWithSHA1 + case oid.Equal(oidSignatureDSAWithSHA256): + return DSAWithSHA256 + case oid.Equal(oidSignatureECDSAWithSHA1): + return ECDSAWithSHA1 + case oid.Equal(oidSignatureECDSAWithSHA256): + return ECDSAWithSHA256 + case oid.Equal(oidSignatureECDSAWithSHA384): + return ECDSAWithSHA384 + case oid.Equal(oidSignatureECDSAWithSHA512): + return ECDSAWithSHA512 + } + return UnknownSignatureAlgorithm +} + +// RFC 3279, 2.3 Public Key Algorithms +// +// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) +// rsadsi(113549) pkcs(1) 1 } +// +// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } +// +// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) +// x9-57(10040) x9cm(4) 1 } +// +// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters +// +// id-ecPublicKey OBJECT IDENTIFIER ::= { +// iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } +var ( + oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} + oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} + oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} +) + +func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { + switch { + case oid.Equal(oidPublicKeyRSA): + return RSA + case oid.Equal(oidPublicKeyDSA): + return DSA + case oid.Equal(oidPublicKeyECDSA): + return ECDSA + } + return UnknownPublicKeyAlgorithm +} + +// RFC 5480, 2.1.1.1. Named Curve +// +// secp224r1 OBJECT IDENTIFIER ::= { +// iso(1) identified-organization(3) certicom(132) curve(0) 33 } +// +// secp256r1 OBJECT IDENTIFIER ::= { +// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) +// prime(1) 7 } +// +// secp384r1 OBJECT IDENTIFIER ::= { +// iso(1) identified-organization(3) certicom(132) curve(0) 34 } +// +// secp521r1 OBJECT IDENTIFIER ::= { +// iso(1) identified-organization(3) certicom(132) curve(0) 35 } +// +// NB: secp256r1 is equivalent to prime256v1 +var ( + oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} + oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} + oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} + oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} +) + +func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { + switch { + case oid.Equal(oidNamedCurveP224): + return elliptic.P224() + case oid.Equal(oidNamedCurveP256): + return elliptic.P256() + case oid.Equal(oidNamedCurveP384): + return elliptic.P384() + case oid.Equal(oidNamedCurveP521): + return elliptic.P521() + } + return nil +} + +func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { + switch curve { + case elliptic.P224(): + return oidNamedCurveP224, true + case elliptic.P256(): + return oidNamedCurveP256, true + case elliptic.P384(): + return oidNamedCurveP384, true + case elliptic.P521(): + return oidNamedCurveP521, true + } + + return nil, false +} + +// KeyUsage represents the set of actions that are valid for a given key. It's +// a bitmap of the KeyUsage* constants. +type KeyUsage int + +const ( + KeyUsageDigitalSignature KeyUsage = 1 << iota + KeyUsageContentCommitment + KeyUsageKeyEncipherment + KeyUsageDataEncipherment + KeyUsageKeyAgreement + KeyUsageCertSign + KeyUsageCRLSign + KeyUsageEncipherOnly + KeyUsageDecipherOnly +) + +// RFC 5280, 4.2.1.12 Extended Key Usage +// +// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } +// +// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } +// +// id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } +// id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } +// id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } +// id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } +// id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } +// id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } +var ( + oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} + oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} + oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} + oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} + oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} + oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} + oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} + oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} + oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} + oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} + oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} + oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} +) + +// ExtKeyUsage represents an extended set of actions that are valid for a given key. +// Each of the ExtKeyUsage* constants define a unique action. +type ExtKeyUsage int + +const ( + ExtKeyUsageAny ExtKeyUsage = iota + ExtKeyUsageServerAuth + ExtKeyUsageClientAuth + ExtKeyUsageCodeSigning + ExtKeyUsageEmailProtection + ExtKeyUsageIPSECEndSystem + ExtKeyUsageIPSECTunnel + ExtKeyUsageIPSECUser + ExtKeyUsageTimeStamping + ExtKeyUsageOCSPSigning + ExtKeyUsageMicrosoftServerGatedCrypto + ExtKeyUsageNetscapeServerGatedCrypto +) + +// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. +var extKeyUsageOIDs = []struct { + extKeyUsage ExtKeyUsage + oid asn1.ObjectIdentifier +}{ + {ExtKeyUsageAny, oidExtKeyUsageAny}, + {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, + {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, + {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, + {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, + {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, + {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, + {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, + {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, + {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, + {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, + {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, +} + +func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { + for _, pair := range extKeyUsageOIDs { + if oid.Equal(pair.oid) { + return pair.extKeyUsage, true + } + } + return +} + +func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { + for _, pair := range extKeyUsageOIDs { + if eku == pair.extKeyUsage { + return pair.oid, true + } + } + return +} + +// A Certificate represents an X.509 certificate. +type Certificate struct { + Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature). + RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content. + RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. + RawSubject []byte // DER encoded Subject + RawIssuer []byte // DER encoded Issuer + + Signature []byte + SignatureAlgorithm SignatureAlgorithm + + PublicKeyAlgorithm PublicKeyAlgorithm + PublicKey interface{} + + Version int + SerialNumber *big.Int + Issuer pkix.Name + Subject pkix.Name + NotBefore, NotAfter time.Time // Validity bounds. + KeyUsage KeyUsage + + // Extensions contains raw X.509 extensions. When parsing certificates, + // this can be used to extract non-critical extensions that are not + // parsed by this package. When marshaling certificates, the Extensions + // field is ignored, see ExtraExtensions. + Extensions []pkix.Extension + + // ExtraExtensions contains extensions to be copied, raw, into any + // marshaled certificates. Values override any extensions that would + // otherwise be produced based on the other fields. The ExtraExtensions + // field is not populated when parsing certificates, see Extensions. + ExtraExtensions []pkix.Extension + + ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. + UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. + + BasicConstraintsValid bool // if true then the next two fields are valid. + IsCA bool + MaxPathLen int + + SubjectKeyId []byte + AuthorityKeyId []byte + + // RFC 5280, 4.2.2.1 (Authority Information Access) + OCSPServer []string + IssuingCertificateURL []string + + // Subject Alternate Name values + DNSNames []string + EmailAddresses []string + IPAddresses []net.IP + + // Name constraints + PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. + PermittedDNSDomains []string + + // CRL Distribution Points + CRLDistributionPoints []string + + PolicyIdentifiers []asn1.ObjectIdentifier +} + +// ErrUnsupportedAlgorithm results from attempting to perform an operation that +// involves algorithms that are not currently implemented. +var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") + +// ConstraintViolationError results when a requested usage is not permitted by +// a certificate. For example: checking a signature when the public key isn't a +// certificate signing key. +type ConstraintViolationError struct{} + +func (ConstraintViolationError) Error() string { + return "x509: invalid signature: parent certificate cannot sign this kind of certificate" +} + +func (c *Certificate) Equal(other *Certificate) bool { + return bytes.Equal(c.Raw, other.Raw) +} + +// Entrust have a broken root certificate (CN=Entrust.net Certification +// Authority (2048)) which isn't marked as a CA certificate and is thus invalid +// according to PKIX. +// We recognise this certificate by its SubjectPublicKeyInfo and exempt it +// from the Basic Constraints requirement. +// See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 +// +// TODO(agl): remove this hack once their reissued root is sufficiently +// widespread. +var entrustBrokenSPKI = []byte{ + 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, + 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, + 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, + 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, + 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, + 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, + 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, + 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, + 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, + 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, + 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, + 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, + 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, + 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, + 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, + 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, + 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, + 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, + 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, + 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, + 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, + 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, + 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, + 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, + 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, + 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, + 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, + 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, + 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, + 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, + 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, + 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, + 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, + 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, + 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, +} + +// CheckSignatureFrom verifies that the signature on c is a valid signature +// from parent. +func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) { + // RFC 5280, 4.2.1.9: + // "If the basic constraints extension is not present in a version 3 + // certificate, or the extension is present but the cA boolean is not + // asserted, then the certified public key MUST NOT be used to verify + // certificate signatures." + // (except for Entrust, see comment above entrustBrokenSPKI) + if (parent.Version == 3 && !parent.BasicConstraintsValid || + parent.BasicConstraintsValid && !parent.IsCA) && + !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { + return ConstraintViolationError{} + } + + if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { + return ConstraintViolationError{} + } + + if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { + return ErrUnsupportedAlgorithm + } + + // TODO(agl): don't ignore the path length constraint. + + return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) +} + +// CheckSignature verifies that signature is a valid signature over signed from +// c's public key. +func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) { + var hashType crypto.Hash + + switch algo { + case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1: + hashType = crypto.SHA1 + case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256: + hashType = crypto.SHA256 + case SHA384WithRSA, ECDSAWithSHA384: + hashType = crypto.SHA384 + case SHA512WithRSA, ECDSAWithSHA512: + hashType = crypto.SHA512 + default: + return ErrUnsupportedAlgorithm + } + + if !hashType.Available() { + return ErrUnsupportedAlgorithm + } + h := hashType.New() + + h.Write(signed) + digest := h.Sum(nil) + + switch pub := c.PublicKey.(type) { + case *rsa.PublicKey: + return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) + case *dsa.PublicKey: + dsaSig := new(dsaSignature) + if _, err := asn1.Unmarshal(signature, dsaSig); err != nil { + return err + } + if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { + return errors.New("x509: DSA signature contained zero or negative values") + } + if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { + return errors.New("x509: DSA verification failure") + } + return + case *ecdsa.PublicKey: + ecdsaSig := new(ecdsaSignature) + if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { + return err + } + if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { + return errors.New("x509: ECDSA signature contained zero or negative values") + } + if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { + return errors.New("x509: ECDSA verification failure") + } + return + } + return ErrUnsupportedAlgorithm +} + +// CheckCRLSignature checks that the signature in crl is from c. +func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) { + algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm) + return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) +} + +// START CT CHANGES +type UnhandledCriticalExtension struct { + ID asn1.ObjectIdentifier +} + +func (h UnhandledCriticalExtension) Error() string { + return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID) +} + +// END CT CHANGES + +type basicConstraints struct { + IsCA bool `asn1:"optional"` + MaxPathLen int `asn1:"optional,default:-1"` +} + +// RFC 5280 4.2.1.4 +type policyInformation struct { + Policy asn1.ObjectIdentifier + // policyQualifiers omitted +} + +// RFC 5280, 4.2.1.10 +type nameConstraints struct { + Permitted []generalSubtree `asn1:"optional,tag:0"` + Excluded []generalSubtree `asn1:"optional,tag:1"` +} + +type generalSubtree struct { + Name string `asn1:"tag:2,optional,ia5"` +} + +// RFC 5280, 4.2.2.1 +type authorityInfoAccess struct { + Method asn1.ObjectIdentifier + Location asn1.RawValue +} + +// RFC 5280, 4.2.1.14 +type distributionPoint struct { + DistributionPoint distributionPointName `asn1:"optional,tag:0"` + Reason asn1.BitString `asn1:"optional,tag:1"` + CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` +} + +type distributionPointName struct { + FullName asn1.RawValue `asn1:"optional,tag:0"` + RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` +} + +func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { + asn1Data := keyData.PublicKey.RightAlign() + switch algo { + case RSA: + p := new(rsaPublicKey) + _, err := asn1.Unmarshal(asn1Data, p) + if err != nil { + return nil, err + } + + if p.N.Sign() <= 0 { + return nil, errors.New("x509: RSA modulus is not a positive number") + } + if p.E <= 0 { + return nil, errors.New("x509: RSA public exponent is not a positive number") + } + + pub := &rsa.PublicKey{ + E: p.E, + N: p.N, + } + return pub, nil + case DSA: + var p *big.Int + _, err := asn1.Unmarshal(asn1Data, &p) + if err != nil { + return nil, err + } + paramsData := keyData.Algorithm.Parameters.FullBytes + params := new(dsaAlgorithmParameters) + _, err = asn1.Unmarshal(paramsData, params) + if err != nil { + return nil, err + } + if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { + return nil, errors.New("x509: zero or negative DSA parameter") + } + pub := &dsa.PublicKey{ + Parameters: dsa.Parameters{ + P: params.P, + Q: params.Q, + G: params.G, + }, + Y: p, + } + return pub, nil + case ECDSA: + paramsData := keyData.Algorithm.Parameters.FullBytes + namedCurveOID := new(asn1.ObjectIdentifier) + _, err := asn1.Unmarshal(paramsData, namedCurveOID) + if err != nil { + return nil, err + } + namedCurve := namedCurveFromOID(*namedCurveOID) + if namedCurve == nil { + return nil, errors.New("x509: unsupported elliptic curve") + } + x, y := elliptic.Unmarshal(namedCurve, asn1Data) + if x == nil { + return nil, errors.New("x509: failed to unmarshal elliptic curve point") + } + pub := &ecdsa.PublicKey{ + Curve: namedCurve, + X: x, + Y: y, + } + return pub, nil + default: + return nil, nil + } +} + +// START CT CHANGES + +// NonFatalErrors is an error type which can hold a number of other errors. +// It's used to collect a range of non-fatal errors which occur while parsing +// a certificate, that way we can still match on certs which technically are +// invalid. +type NonFatalErrors struct { + Errors []error +} + +// Adds an error to the list of errors contained by NonFatalErrors. +func (e *NonFatalErrors) AddError(err error) { + e.Errors = append(e.Errors, err) +} + +// Returns a string consisting of the values of Error() from all of the errors +// contained in |e| +func (e NonFatalErrors) Error() string { + r := "NonFatalErrors: " + for _, err := range e.Errors { + r += err.Error() + "; " + } + return r +} + +// Returns true if |e| contains at least one error +func (e *NonFatalErrors) HasError() bool { + return len(e.Errors) > 0 +} + +// END CT CHANGES + +func parseCertificate(in *certificate) (*Certificate, error) { + // START CT CHANGES + var nfe NonFatalErrors + // END CT CHANGES + + out := new(Certificate) + out.Raw = in.Raw + out.RawTBSCertificate = in.TBSCertificate.Raw + out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw + out.RawSubject = in.TBSCertificate.Subject.FullBytes + out.RawIssuer = in.TBSCertificate.Issuer.FullBytes + + out.Signature = in.SignatureValue.RightAlign() + out.SignatureAlgorithm = + getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm) + + out.PublicKeyAlgorithm = + getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) + var err error + out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey) + if err != nil { + return nil, err + } + + if in.TBSCertificate.SerialNumber.Sign() < 0 { + // START CT CHANGES + nfe.AddError(errors.New("x509: negative serial number")) + // END CT CHANGES + } + + out.Version = in.TBSCertificate.Version + 1 + out.SerialNumber = in.TBSCertificate.SerialNumber + + var issuer, subject pkix.RDNSequence + if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { + return nil, err + } + if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { + return nil, err + } + + out.Issuer.FillFromRDNSequence(&issuer) + out.Subject.FillFromRDNSequence(&subject) + + out.NotBefore = in.TBSCertificate.Validity.NotBefore + out.NotAfter = in.TBSCertificate.Validity.NotAfter + + for _, e := range in.TBSCertificate.Extensions { + out.Extensions = append(out.Extensions, e) + + if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { + switch e.Id[3] { + case 15: + // RFC 5280, 4.2.1.3 + var usageBits asn1.BitString + _, err := asn1.Unmarshal(e.Value, &usageBits) + + if err == nil { + var usage int + for i := 0; i < 9; i++ { + if usageBits.At(i) != 0 { + usage |= 1 << uint(i) + } + } + out.KeyUsage = KeyUsage(usage) + continue + } + case 19: + // RFC 5280, 4.2.1.9 + var constraints basicConstraints + _, err := asn1.Unmarshal(e.Value, &constraints) + + if err == nil { + out.BasicConstraintsValid = true + out.IsCA = constraints.IsCA + out.MaxPathLen = constraints.MaxPathLen + continue + } + case 17: + // RFC 5280, 4.2.1.6 + + // SubjectAltName ::= GeneralNames + // + // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + // + // GeneralName ::= CHOICE { + // otherName [0] OtherName, + // rfc822Name [1] IA5String, + // dNSName [2] IA5String, + // x400Address [3] ORAddress, + // directoryName [4] Name, + // ediPartyName [5] EDIPartyName, + // uniformResourceIdentifier [6] IA5String, + // iPAddress [7] OCTET STRING, + // registeredID [8] OBJECT IDENTIFIER } + var seq asn1.RawValue + _, err := asn1.Unmarshal(e.Value, &seq) + if err != nil { + return nil, err + } + if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { + return nil, asn1.StructuralError{Msg: "bad SAN sequence"} + } + + parsedName := false + + rest := seq.Bytes + for len(rest) > 0 { + var v asn1.RawValue + rest, err = asn1.Unmarshal(rest, &v) + if err != nil { + return nil, err + } + switch v.Tag { + case 1: + out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes)) + parsedName = true + case 2: + out.DNSNames = append(out.DNSNames, string(v.Bytes)) + parsedName = true + case 7: + switch len(v.Bytes) { + case net.IPv4len, net.IPv6len: + out.IPAddresses = append(out.IPAddresses, v.Bytes) + default: + // START CT CHANGES + nfe.AddError(fmt.Errorf("x509: certificate contained IP address of length %d : %v", len(v.Bytes), v.Bytes)) + // END CT CHANGES + } + } + } + + if parsedName { + continue + } + // If we didn't parse any of the names then we + // fall through to the critical check below. + + case 30: + // RFC 5280, 4.2.1.10 + + // NameConstraints ::= SEQUENCE { + // permittedSubtrees [0] GeneralSubtrees OPTIONAL, + // excludedSubtrees [1] GeneralSubtrees OPTIONAL } + // + // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree + // + // GeneralSubtree ::= SEQUENCE { + // base GeneralName, + // minimum [0] BaseDistance DEFAULT 0, + // maximum [1] BaseDistance OPTIONAL } + // + // BaseDistance ::= INTEGER (0..MAX) + + var constraints nameConstraints + _, err := asn1.Unmarshal(e.Value, &constraints) + if err != nil { + return nil, err + } + + if len(constraints.Excluded) > 0 && e.Critical { + // START CT CHANGES + nfe.AddError(UnhandledCriticalExtension{e.Id}) + // END CT CHANGES + } + + for _, subtree := range constraints.Permitted { + if len(subtree.Name) == 0 { + if e.Critical { + // START CT CHANGES + nfe.AddError(UnhandledCriticalExtension{e.Id}) + // END CT CHANGES + } + continue + } + out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name) + } + continue + + case 31: + // RFC 5280, 4.2.1.14 + + // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint + // + // DistributionPoint ::= SEQUENCE { + // distributionPoint [0] DistributionPointName OPTIONAL, + // reasons [1] ReasonFlags OPTIONAL, + // cRLIssuer [2] GeneralNames OPTIONAL } + // + // DistributionPointName ::= CHOICE { + // fullName [0] GeneralNames, + // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } + + var cdp []distributionPoint + _, err := asn1.Unmarshal(e.Value, &cdp) + if err != nil { + return nil, err + } + + for _, dp := range cdp { + var n asn1.RawValue + _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n) + if err != nil { + return nil, err + } + + if n.Tag == 6 { + out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) + } + } + continue + + case 35: + // RFC 5280, 4.2.1.1 + var a authKeyId + _, err = asn1.Unmarshal(e.Value, &a) + if err != nil { + return nil, err + } + out.AuthorityKeyId = a.Id + continue + + case 37: + // RFC 5280, 4.2.1.12. Extended Key Usage + + // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } + // + // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId + // + // KeyPurposeId ::= OBJECT IDENTIFIER + + var keyUsage []asn1.ObjectIdentifier + _, err = asn1.Unmarshal(e.Value, &keyUsage) + if err != nil { + return nil, err + } + + for _, u := range keyUsage { + if extKeyUsage, ok := extKeyUsageFromOID(u); ok { + out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) + } else { + out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) + } + } + + continue + + case 14: + // RFC 5280, 4.2.1.2 + var keyid []byte + _, err = asn1.Unmarshal(e.Value, &keyid) + if err != nil { + return nil, err + } + out.SubjectKeyId = keyid + continue + + case 32: + // RFC 5280 4.2.1.4: Certificate Policies + var policies []policyInformation + if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { + return nil, err + } + out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) + for i, policy := range policies { + out.PolicyIdentifiers[i] = policy.Policy + } + } + } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { + // RFC 5280 4.2.2.1: Authority Information Access + var aia []authorityInfoAccess + if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { + return nil, err + } + + for _, v := range aia { + // GeneralName: uniformResourceIdentifier [6] IA5String + if v.Location.Tag != 6 { + continue + } + if v.Method.Equal(oidAuthorityInfoAccessOcsp) { + out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) + } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { + out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) + } + } + } + + if e.Critical { + // START CT CHANGES + nfe.AddError(UnhandledCriticalExtension{e.Id}) + // END CT CHANGES + } + } + // START CT CHANGES + if nfe.HasError() { + return out, nfe + } + // END CT CHANGES + return out, nil +} + +// START CT CHANGES + +// ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data. +// The parsed data is returned in a Certificate struct for ease of access. +func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) { + var tbsCert tbsCertificate + rest, err := asn1.Unmarshal(asn1Data, &tbsCert) + if err != nil { + return nil, err + } + if len(rest) > 0 { + return nil, asn1.SyntaxError{Msg: "trailing data"} + } + return parseCertificate(&certificate{ + Raw: tbsCert.Raw, + TBSCertificate: tbsCert}) +} + +// END CT CHANGES + +// ParseCertificate parses a single certificate from the given ASN.1 DER data. +func ParseCertificate(asn1Data []byte) (*Certificate, error) { + var cert certificate + rest, err := asn1.Unmarshal(asn1Data, &cert) + if err != nil { + return nil, err + } + if len(rest) > 0 { + return nil, asn1.SyntaxError{Msg: "trailing data"} + } + + return parseCertificate(&cert) +} + +// ParseCertificates parses one or more certificates from the given ASN.1 DER +// data. The certificates must be concatenated with no intermediate padding. +func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { + var v []*certificate + + for len(asn1Data) > 0 { + cert := new(certificate) + var err error + asn1Data, err = asn1.Unmarshal(asn1Data, cert) + if err != nil { + return nil, err + } + v = append(v, cert) + } + + ret := make([]*Certificate, len(v)) + for i, ci := range v { + cert, err := parseCertificate(ci) + if err != nil { + return nil, err + } + ret[i] = cert + } + + return ret, nil +} + +func reverseBitsInAByte(in byte) byte { + b1 := in>>4 | in<<4 + b2 := b1>>2&0x33 | b1<<2&0xcc + b3 := b2>>1&0x55 | b2<<1&0xaa + return b3 +} + +var ( + oidExtensionSubjectKeyId = []int{2, 5, 29, 14} + oidExtensionKeyUsage = []int{2, 5, 29, 15} + oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} + oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} + oidExtensionBasicConstraints = []int{2, 5, 29, 19} + oidExtensionSubjectAltName = []int{2, 5, 29, 17} + oidExtensionCertificatePolicies = []int{2, 5, 29, 32} + oidExtensionNameConstraints = []int{2, 5, 29, 30} + oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} + oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} +) + +var ( + oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} + oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} +) + +// oidNotInExtensions returns whether an extension with the given oid exists in +// extensions. +func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { + for _, e := range extensions { + if e.Id.Equal(oid) { + return true + } + } + return false +} + +func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) { + ret = make([]pkix.Extension, 10 /* maximum number of elements. */) + n := 0 + + if template.KeyUsage != 0 && + !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { + ret[n].Id = oidExtensionKeyUsage + ret[n].Critical = true + + var a [2]byte + a[0] = reverseBitsInAByte(byte(template.KeyUsage)) + a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) + + l := 1 + if a[1] != 0 { + l = 2 + } + + ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8}) + if err != nil { + return + } + n++ + } + + if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && + !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { + ret[n].Id = oidExtensionExtendedKeyUsage + + var oids []asn1.ObjectIdentifier + for _, u := range template.ExtKeyUsage { + if oid, ok := oidFromExtKeyUsage(u); ok { + oids = append(oids, oid) + } else { + panic("internal error") + } + } + + oids = append(oids, template.UnknownExtKeyUsage...) + + ret[n].Value, err = asn1.Marshal(oids) + if err != nil { + return + } + n++ + } + + if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { + ret[n].Id = oidExtensionBasicConstraints + ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen}) + ret[n].Critical = true + if err != nil { + return + } + n++ + } + + if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { + ret[n].Id = oidExtensionSubjectKeyId + ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) + if err != nil { + return + } + n++ + } + + if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { + ret[n].Id = oidExtensionAuthorityKeyId + ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) + if err != nil { + return + } + n++ + } + + if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && + !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { + ret[n].Id = oidExtensionAuthorityInfoAccess + var aiaValues []authorityInfoAccess + for _, name := range template.OCSPServer { + aiaValues = append(aiaValues, authorityInfoAccess{ + Method: oidAuthorityInfoAccessOcsp, + Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, + }) + } + for _, name := range template.IssuingCertificateURL { + aiaValues = append(aiaValues, authorityInfoAccess{ + Method: oidAuthorityInfoAccessIssuers, + Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, + }) + } + ret[n].Value, err = asn1.Marshal(aiaValues) + if err != nil { + return + } + n++ + } + + if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && + !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { + ret[n].Id = oidExtensionSubjectAltName + var rawValues []asn1.RawValue + for _, name := range template.DNSNames { + rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) + } + for _, email := range template.EmailAddresses { + rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) + } + for _, rawIP := range template.IPAddresses { + // If possible, we always want to encode IPv4 addresses in 4 bytes. + ip := rawIP.To4() + if ip == nil { + ip = rawIP + } + rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) + } + ret[n].Value, err = asn1.Marshal(rawValues) + if err != nil { + return + } + n++ + } + + if len(template.PolicyIdentifiers) > 0 && + !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { + ret[n].Id = oidExtensionCertificatePolicies + policies := make([]policyInformation, len(template.PolicyIdentifiers)) + for i, policy := range template.PolicyIdentifiers { + policies[i].Policy = policy + } + ret[n].Value, err = asn1.Marshal(policies) + if err != nil { + return + } + n++ + } + + if len(template.PermittedDNSDomains) > 0 && + !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { + ret[n].Id = oidExtensionNameConstraints + ret[n].Critical = template.PermittedDNSDomainsCritical + + var out nameConstraints + out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains)) + for i, permitted := range template.PermittedDNSDomains { + out.Permitted[i] = generalSubtree{Name: permitted} + } + ret[n].Value, err = asn1.Marshal(out) + if err != nil { + return + } + n++ + } + + if len(template.CRLDistributionPoints) > 0 && + !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { + ret[n].Id = oidExtensionCRLDistributionPoints + + var crlDp []distributionPoint + for _, name := range template.CRLDistributionPoints { + rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) + + dp := distributionPoint{ + DistributionPoint: distributionPointName{ + FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName}, + }, + } + crlDp = append(crlDp, dp) + } + + ret[n].Value, err = asn1.Marshal(crlDp) + if err != nil { + return + } + n++ + } + + // Adding another extension here? Remember to update the maximum number + // of elements in the make() at the top of the function. + + return append(ret[:n], template.ExtraExtensions...), nil +} + +func subjectBytes(cert *Certificate) ([]byte, error) { + if len(cert.RawSubject) > 0 { + return cert.RawSubject, nil + } + + return asn1.Marshal(cert.Subject.ToRDNSequence()) +} + +// CreateCertificate creates a new certificate based on a template. The +// following members of template are used: SerialNumber, Subject, NotBefore, +// NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, +// IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, +// PermittedDNSDomains. +// +// The certificate is signed by parent. If parent is equal to template then the +// certificate is self-signed. The parameter pub is the public key of the +// signee and priv is the private key of the signer. +// +// The returned slice is the certificate in DER encoding. +// +// The only supported key types are RSA and ECDSA (*rsa.PublicKey or +// *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv). +func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) { + var publicKeyBytes []byte + var publicKeyAlgorithm pkix.AlgorithmIdentifier + + if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { + return nil, err + } + + var signatureAlgorithm pkix.AlgorithmIdentifier + var hashFunc crypto.Hash + + switch priv := priv.(type) { + case *rsa.PrivateKey: + signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA + hashFunc = crypto.SHA1 + case *ecdsa.PrivateKey: + switch priv.Curve { + case elliptic.P224(), elliptic.P256(): + hashFunc = crypto.SHA256 + signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256 + case elliptic.P384(): + hashFunc = crypto.SHA384 + signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384 + case elliptic.P521(): + hashFunc = crypto.SHA512 + signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512 + default: + return nil, errors.New("x509: unknown elliptic curve") + } + default: + return nil, errors.New("x509: only RSA and ECDSA private keys supported") + } + + if err != nil { + return + } + + if len(parent.SubjectKeyId) > 0 { + template.AuthorityKeyId = parent.SubjectKeyId + } + + extensions, err := buildExtensions(template) + if err != nil { + return + } + + asn1Issuer, err := subjectBytes(parent) + if err != nil { + return + } + + asn1Subject, err := subjectBytes(template) + if err != nil { + return + } + + encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} + c := tbsCertificate{ + Version: 2, + SerialNumber: template.SerialNumber, + SignatureAlgorithm: signatureAlgorithm, + Issuer: asn1.RawValue{FullBytes: asn1Issuer}, + Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, + Subject: asn1.RawValue{FullBytes: asn1Subject}, + PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, + Extensions: extensions, + } + + tbsCertContents, err := asn1.Marshal(c) + if err != nil { + return + } + + c.Raw = tbsCertContents + + h := hashFunc.New() + h.Write(tbsCertContents) + digest := h.Sum(nil) + + var signature []byte + + switch priv := priv.(type) { + case *rsa.PrivateKey: + signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) + case *ecdsa.PrivateKey: + var r, s *big.Int + if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { + signature, err = asn1.Marshal(ecdsaSignature{r, s}) + } + default: + panic("internal error") + } + + if err != nil { + return + } + + cert, err = asn1.Marshal(certificate{ + nil, + c, + signatureAlgorithm, + asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, + }) + return +} + +// pemCRLPrefix is the magic string that indicates that we have a PEM encoded +// CRL. +var pemCRLPrefix = []byte("-----BEGIN X509 CRL") + +// pemType is the type of a PEM encoded CRL. +var pemType = "X509 CRL" + +// ParseCRL parses a CRL from the given bytes. It's often the case that PEM +// encoded CRLs will appear where they should be DER encoded, so this function +// will transparently handle PEM encoding as long as there isn't any leading +// garbage. +func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) { + if bytes.HasPrefix(crlBytes, pemCRLPrefix) { + block, _ := pem.Decode(crlBytes) + if block != nil && block.Type == pemType { + crlBytes = block.Bytes + } + } + return ParseDERCRL(crlBytes) +} + +// ParseDERCRL parses a DER encoded CRL from the given bytes. +func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) { + certList = new(pkix.CertificateList) + _, err = asn1.Unmarshal(derBytes, certList) + if err != nil { + certList = nil + } + return +} + +// CreateCRL returns a DER encoded CRL, signed by this Certificate, that +// contains the given list of revoked certificates. +// +// The only supported key type is RSA (*rsa.PrivateKey for priv). +func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { + rsaPriv, ok := priv.(*rsa.PrivateKey) + if !ok { + return nil, errors.New("x509: non-RSA private keys not supported") + } + tbsCertList := pkix.TBSCertificateList{ + Version: 2, + Signature: pkix.AlgorithmIdentifier{ + Algorithm: oidSignatureSHA1WithRSA, + }, + Issuer: c.Subject.ToRDNSequence(), + ThisUpdate: now.UTC(), + NextUpdate: expiry.UTC(), + RevokedCertificates: revokedCerts, + } + + tbsCertListContents, err := asn1.Marshal(tbsCertList) + if err != nil { + return + } + + h := sha1.New() + h.Write(tbsCertListContents) + digest := h.Sum(nil) + + signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest) + if err != nil { + return + } + + return asn1.Marshal(pkix.CertificateList{ + TBSCertList: tbsCertList, + SignatureAlgorithm: pkix.AlgorithmIdentifier{ + Algorithm: oidSignatureSHA1WithRSA, + }, + SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, + }) +} diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md index 011d085f18db..83b4183eb80d 100644 --- a/vendor/github.com/miekg/dns/README.md +++ b/vendor/github.com/miekg/dns/README.md @@ -12,7 +12,7 @@ can build servers and resolvers with it. We try to keep the "master" branch as sane as possible and at the bleeding edge of standards, avoiding breaking changes wherever reasonable. We support the last -two versions of Go, currently: 1.4 and 1.5. +two versions of Go, currently: 1.5 and 1.6. # Goals @@ -48,6 +48,8 @@ A not-so-up-to-date-list-that-may-be-actually-current: * https://github.com/miekg/unbound * https://github.com/miekg/exdns * https://dnslookup.org +* https://github.com/looterz/grimd +* https://github.com/phamhongviet/serf-dns Send pull request if you want to be listed here. @@ -61,7 +63,7 @@ Send pull request if you want to be listed here. * Server side programming (mimicking the net/http package); * Client side programming; * DNSSEC: signing, validating and key generation for DSA, RSA and ECDSA; -* EDNS0, NSID; +* EDNS0, NSID, Cookies; * AXFR/IXFR; * TSIG, SIG(0); * DNS over TLS: optional encrypted connection between client and server; @@ -111,7 +113,6 @@ Example programs can be found in the `github.com/miekg/exdns` repository. * 340{1,2,3} - NAPTR record * 3445 - Limiting the scope of (DNS)KEY * 3597 - Unknown RRs -* 4025 - IPSECKEY * 403{3,4,5} - DNSSEC + validation functions * 4255 - SSHFP record * 4343 - Case insensitivity @@ -138,8 +139,9 @@ Example programs can be found in the `github.com/miekg/exdns` repository. * 7043 - EUI48/EUI64 records * 7314 - DNS (EDNS) EXPIRE Option * 7553 - URI record +* 7858 - DNS over TLS: Initiation and Performance Considerations (draft) +* 7873 - Domain Name System (DNS) Cookies (draft-ietf-dnsop-cookies) * xxxx - EDNS0 DNS Update Lease (draft) -* yyyy - DNS over TLS: Initiation and Performance Considerations (draft) ## Loosely based upon @@ -147,11 +149,3 @@ Example programs can be found in the `github.com/miekg/exdns` repository. * `NSD` * `Net::DNS` * `GRONG` - -## TODO - -* privatekey.Precompute() when signing? -* Last remaining RRs: APL, ATMA, A6, NSAP and NXT. -* Missing in parsing: ISDN, UNSPEC, NSAP and ATMA. -* NSEC(3) cover/match/closest enclose. -* Replies with TC bit are not parsed to the end. diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go index 7a05eb99cc78..1302e4e04c6d 100644 --- a/vendor/github.com/miekg/dns/client.go +++ b/vendor/github.com/miekg/dns/client.go @@ -5,6 +5,7 @@ package dns import ( "bytes" "crypto/tls" + "encoding/binary" "io" "net" "time" @@ -28,9 +29,10 @@ type Client struct { Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP) UDPSize uint16 // minimum receive buffer for UDP messages TLSConfig *tls.Config // TLS connection configuration - DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds - ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds + Timeout time.Duration // a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout and WriteTimeout when non-zero + DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds - overridden by Timeout when that value is non-zero + ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be fully qualified SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass group singleflight @@ -129,6 +131,9 @@ func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro } func (c *Client) dialTimeout() time.Duration { + if c.Timeout != 0 { + return c.Timeout + } if c.DialTimeout != 0 { return c.DialTimeout } @@ -170,6 +175,11 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro } } + var deadline time.Time + if c.Timeout != 0 { + deadline = time.Now().Add(c.Timeout) + } + if tls { co, err = DialTimeoutWithTLS(network, a, c.TLSConfig, c.dialTimeout()) } else { @@ -192,12 +202,12 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro } co.TsigSecret = c.TsigSecret - co.SetWriteDeadline(time.Now().Add(c.writeTimeout())) + co.SetWriteDeadline(deadlineOrTimeout(deadline, c.writeTimeout())) if err = co.WriteMsg(m); err != nil { return nil, 0, err } - co.SetReadDeadline(time.Now().Add(c.readTimeout())) + co.SetReadDeadline(deadlineOrTimeout(deadline, c.readTimeout())) r, err = co.ReadMsg() if err == nil && r.Id != m.Id { err = ErrId @@ -274,9 +284,11 @@ func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) { p = p[:n] if hdr != nil { - if _, err = UnpackStruct(hdr, p, 0); err != nil { + dh, _, err := unpackMsgHdr(p, 0) + if err != nil { return nil, err } + *hdr = dh } return p, err } @@ -291,7 +303,7 @@ func tcpMsgLen(t io.Reader) (int, error) { if n != 2 { return 0, ErrShortRead } - l, _ := unpackUint16(p, 0) + l := binary.BigEndian.Uint16(p) if l == 0 { return 0, ErrShortRead } @@ -383,7 +395,7 @@ func (co *Conn) Write(p []byte) (n int, err error) { return 0, &Error{err: "message too large"} } l := make([]byte, 2, lp+2) - l[0], l[1] = packUint16(uint16(lp)) + binary.BigEndian.PutUint16(l, uint16(lp)) p = append(l, p...) n, err := io.Copy(w, bytes.NewReader(p)) return int(n), err @@ -434,3 +446,10 @@ func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout } return conn, nil } + +func deadlineOrTimeout(deadline time.Time, timeout time.Duration) time.Time { + if deadline.IsZero() { + return time.Now().Add(timeout) + } + return deadline +} diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index 63165b4fa9ce..cf456165f435 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -142,9 +142,13 @@ func (dns *Msg) IsTsig() *TSIG { // record in the additional section will do. It returns the OPT record // found or nil. func (dns *Msg) IsEdns0() *OPT { - for _, r := range dns.Extra { - if r.Header().Rrtype == TypeOPT { - return r.(*OPT) + // EDNS0 is at the end of the additional section, start there. + // We might want to change this to *only* look at the last two + // records. So we see TSIG and/or OPT - this a slightly bigger + // change though. + for i := len(dns.Extra) - 1; i >= 0; i-- { + if dns.Extra[i].Header().Rrtype == TypeOPT { + return dns.Extra[i].(*OPT) } } return nil @@ -163,8 +167,8 @@ func IsDomainName(s string) (labels int, ok bool) { return labels, err == nil } -// IsSubDomain checks if child is indeed a child of the parent. Both child and -// parent are *not* downcased before doing the comparison. +// IsSubDomain checks if child is indeed a child of the parent. If child and parent +// are the same domain true is returned as well. func IsSubDomain(parent, child string) bool { // Entire child is contained in parent return CompareDomainName(parent, child) == CountLabel(parent) diff --git a/vendor/github.com/miekg/dns/dns.go b/vendor/github.com/miekg/dns/dns.go index a3e4a0efae55..b3292287ce75 100644 --- a/vendor/github.com/miekg/dns/dns.go +++ b/vendor/github.com/miekg/dns/dns.go @@ -3,17 +3,15 @@ package dns import "strconv" const ( - year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits. - // DefaultMsgSize is the standard default for messages larger than 512 bytes. - DefaultMsgSize = 4096 - // MinMsgSize is the minimal size of a DNS packet. - MinMsgSize = 512 - // MaxMsgSize is the largest possible DNS packet. - MaxMsgSize = 65535 - defaultTtl = 3600 // Default internal TTL. + year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits. + defaultTtl = 3600 // Default internal TTL. + + DefaultMsgSize = 4096 // DefaultMsgSize is the standard default for messages larger than 512 bytes. + MinMsgSize = 512 // MinMsgSize is the minimal size of a DNS packet. + MaxMsgSize = 65535 // MaxMsgSize is the largest possible DNS packet. ) -// Error represents a DNS error +// Error represents a DNS error. type Error struct{ err string } func (e *Error) Error() string { @@ -30,10 +28,13 @@ type RR interface { Header() *RR_Header // String returns the text representation of the resource record. String() string + // copy returns a copy of the RR copy() RR // len returns the length (in octets) of the uncompressed RR in wire format. len() int + // pack packs an RR into wire format. + pack([]byte, int, map[string]int, bool) (int, error) } // RR_Header is the header all DNS resource records share. @@ -42,13 +43,13 @@ type RR_Header struct { Rrtype uint16 Class uint16 Ttl uint32 - Rdlength uint16 // length of data after header + Rdlength uint16 // Length of data after header. } -// Header returns itself. This is here to make RR_Header implement the RR interface. +// Header returns itself. This is here to make RR_Header implements the RR interface. func (h *RR_Header) Header() *RR_Header { return h } -// Just to imlement the RR interface. +// Just to implement the RR interface. func (h *RR_Header) copy() RR { return nil } func (h *RR_Header) copyHeader() *RR_Header { @@ -82,19 +83,22 @@ func (h *RR_Header) len() int { return l } -// ToRFC3597 converts a known RR to the unknown RR representation -// from RFC 3597. +// ToRFC3597 converts a known RR to the unknown RR representation from RFC 3597. func (rr *RFC3597) ToRFC3597(r RR) error { buf := make([]byte, r.len()*2) - off, err := PackStruct(r, buf, 0) + off, err := PackRR(r, buf, 0, nil, false) if err != nil { return err } buf = buf[:off] - rawSetRdlength(buf, 0, off) - _, err = UnpackStruct(rr, buf, 0) + if int(r.Header().Rdlength) > off { + return ErrBuf + } + + rfc3597, _, err := unpackRFC3597(*r.Header(), buf, off-int(r.Header().Rdlength)) if err != nil { return err } + *rr = *rfc3597.(*RFC3597) return nil } diff --git a/vendor/github.com/miekg/dns/dnssec.go b/vendor/github.com/miekg/dns/dnssec.go index 84cb21421b9a..f5f3fbdd899f 100644 --- a/vendor/github.com/miekg/dns/dnssec.go +++ b/vendor/github.com/miekg/dns/dnssec.go @@ -13,6 +13,7 @@ import ( _ "crypto/sha256" _ "crypto/sha512" "encoding/asn1" + "encoding/binary" "encoding/hex" "math/big" "sort" @@ -103,9 +104,7 @@ const ( ZONE = 1 << 8 ) -// The RRSIG needs to be converted to wireformat with some of -// the rdata (the signature) missing. Use this struct to ease -// the conversion (and re-use the pack/unpack functions). +// The RRSIG needs to be converted to wireformat with some of the rdata (the signature) missing. type rrsigWireFmt struct { TypeCovered uint16 Algorithm uint8 @@ -144,7 +143,7 @@ func (k *DNSKEY) KeyTag() uint16 { // at the base64 values. But I'm lazy. modulus, _ := fromBase64([]byte(k.PublicKey)) if len(modulus) > 1 { - x, _ := unpackUint16(modulus, len(modulus)-2) + x := binary.BigEndian.Uint16(modulus[len(modulus)-2:]) keytag = int(x) } default: @@ -154,7 +153,7 @@ func (k *DNSKEY) KeyTag() uint16 { keywire.Algorithm = k.Algorithm keywire.PublicKey = k.PublicKey wire := make([]byte, DefaultMsgSize) - n, err := PackStruct(keywire, wire, 0) + n, err := packKeyWire(keywire, wire) if err != nil { return 0 } @@ -192,7 +191,7 @@ func (k *DNSKEY) ToDS(h uint8) *DS { keywire.Algorithm = k.Algorithm keywire.PublicKey = k.PublicKey wire := make([]byte, DefaultMsgSize) - n, err := PackStruct(keywire, wire, 0) + n, err := packKeyWire(keywire, wire) if err != nil { return nil } @@ -289,7 +288,7 @@ func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error { // Create the desired binary blob signdata := make([]byte, DefaultMsgSize) - n, err := PackStruct(sigwire, signdata, 0) + n, err := packSigWire(sigwire, signdata) if err != nil { return err } @@ -407,7 +406,7 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error { sigwire.SignerName = strings.ToLower(rr.SignerName) // Create the desired binary blob signeddata := make([]byte, DefaultMsgSize) - n, err := PackStruct(sigwire, signeddata, 0) + n, err := packSigWire(sigwire, signeddata) if err != nil { return err } @@ -662,3 +661,61 @@ func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) { } return buf, nil } + +func packSigWire(sw *rrsigWireFmt, msg []byte) (int, error) { + // copied from zmsg.go RRSIG packing + off, err := packUint16(sw.TypeCovered, msg, 0) + if err != nil { + return off, err + } + off, err = packUint8(sw.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(sw.Labels, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(sw.OrigTtl, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(sw.Expiration, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(sw.Inception, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(sw.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(sw.SignerName, msg, off, nil, false) + if err != nil { + return off, err + } + return off, nil +} + +func packKeyWire(dw *dnskeyWireFmt, msg []byte) (int, error) { + // copied from zmsg.go DNSKEY packing + off, err := packUint16(dw.Flags, msg, 0) + if err != nil { + return off, err + } + off, err = packUint8(dw.Protocol, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(dw.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(dw.PublicKey, msg, off) + if err != nil { + return off, err + } + return off, nil +} diff --git a/vendor/github.com/miekg/dns/dnssec_keyscan.go b/vendor/github.com/miekg/dns/dnssec_keyscan.go index 19a783389ab2..c0b54dc7640a 100644 --- a/vendor/github.com/miekg/dns/dnssec_keyscan.go +++ b/vendor/github.com/miekg/dns/dnssec_keyscan.go @@ -25,9 +25,9 @@ func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error) { // The public key must be known, because some cryptographic algorithms embed // the public inside the privatekey. func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error) { - m, e := parseKey(q, file) + m, err := parseKey(q, file) if m == nil { - return nil, e + return nil, err } if _, ok := m["private-key-format"]; !ok { return nil, ErrPrivKey @@ -42,16 +42,16 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er } switch uint8(algo) { case DSA: - priv, e := readPrivateKeyDSA(m) - if e != nil { - return nil, e + priv, err := readPrivateKeyDSA(m) + if err != nil { + return nil, err } pub := k.publicKeyDSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub - return priv, e + return priv, nil case RSAMD5: fallthrough case RSASHA1: @@ -61,31 +61,31 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er case RSASHA256: fallthrough case RSASHA512: - priv, e := readPrivateKeyRSA(m) - if e != nil { - return nil, e + priv, err := readPrivateKeyRSA(m) + if err != nil { + return nil, err } pub := k.publicKeyRSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub - return priv, e + return priv, nil case ECCGOST: return nil, ErrPrivKey case ECDSAP256SHA256: fallthrough case ECDSAP384SHA384: - priv, e := readPrivateKeyECDSA(m) - if e != nil { - return nil, e + priv, err := readPrivateKeyECDSA(m) + if err != nil { + return nil, err } pub := k.publicKeyECDSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub - return priv, e + return priv, nil default: return nil, ErrPrivKey } diff --git a/vendor/github.com/miekg/dns/edns.go b/vendor/github.com/miekg/dns/edns.go index 0c47f6ea5a40..7a58aa9b17b6 100644 --- a/vendor/github.com/miekg/dns/edns.go +++ b/vendor/github.com/miekg/dns/edns.go @@ -1,6 +1,7 @@ package dns import ( + "encoding/binary" "encoding/hex" "errors" "net" @@ -17,6 +18,7 @@ const ( EDNS0N3U = 0x7 // NSEC3 Hash Understood EDNS0SUBNET = 0x8 // client-subnet (RFC6891) EDNS0EXPIRE = 0x9 // EDNS0 expire + EDNS0COOKIE = 0xa // EDNS0 Cookie EDNS0SUBNETDRAFT = 0x50fa // Don't use! Use EDNS0SUBNET EDNS0LOCALSTART = 0xFDE9 // Beginning of range reserved for local/experimental use (RFC6891) EDNS0LOCALEND = 0xFFFE // End of range reserved for local/experimental use (RFC6891) @@ -56,6 +58,8 @@ func (rr *OPT) String() string { if o.(*EDNS0_SUBNET).DraftOption { s += " (draft)" } + case *EDNS0_COOKIE: + s += "\n; COOKIE: " + o.String() case *EDNS0_UL: s += "\n; UPDATE LEASE: " + o.String() case *EDNS0_LLQ: @@ -96,13 +100,16 @@ func (rr *OPT) SetVersion(v uint8) { } // ExtendedRcode returns the EDNS extended RCODE field (the upper 8 bits of the TTL). -func (rr *OPT) ExtendedRcode() uint8 { - return uint8((rr.Hdr.Ttl & 0xFF000000) >> 24) +func (rr *OPT) ExtendedRcode() int { + return int((rr.Hdr.Ttl&0xFF000000)>>24) + 15 } // SetExtendedRcode sets the EDNS extended RCODE field. func (rr *OPT) SetExtendedRcode(v uint8) { - rr.Hdr.Ttl = rr.Hdr.Ttl&0x00FFFFFF | (uint32(v) << 24) + if v < RcodeBadVers { // Smaller than 16.. Use the 4 bits you have! + return + } + rr.Hdr.Ttl = rr.Hdr.Ttl&0x00FFFFFF | (uint32(v-15) << 24) } // UDPSize returns the UDP buffer size. @@ -125,8 +132,7 @@ func (rr *OPT) SetDo() { rr.Hdr.Ttl |= _DO } -// EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to -// it. +// EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to it. type EDNS0 interface { // Option returns the option code for the option. Option() uint16 @@ -207,7 +213,7 @@ func (e *EDNS0_SUBNET) Option() uint16 { func (e *EDNS0_SUBNET) pack() ([]byte, error) { b := make([]byte, 4) - b[0], b[1] = packUint16(e.Family) + binary.BigEndian.PutUint16(b[0:], e.Family) b[2] = e.SourceNetmask b[3] = e.SourceScope switch e.Family { @@ -241,7 +247,7 @@ func (e *EDNS0_SUBNET) unpack(b []byte) error { if len(b) < 4 { return ErrBuf } - e.Family, _ = unpackUint16(b, 0) + e.Family = binary.BigEndian.Uint16(b) e.SourceNetmask = b[2] e.SourceScope = b[3] switch e.Family { @@ -283,6 +289,41 @@ func (e *EDNS0_SUBNET) String() (s string) { return } +// The Cookie EDNS0 option +// +// o := new(dns.OPT) +// o.Hdr.Name = "." +// o.Hdr.Rrtype = dns.TypeOPT +// e := new(dns.EDNS0_COOKIE) +// e.Code = dns.EDNS0COOKIE +// e.Cookie = "24a5ac.." +// o.Option = append(o.Option, e) +// +// The Cookie field consists out of a client cookie (RFC 7873 Section 4), that is +// always 8 bytes. It may then optionally be followed by the server cookie. The server +// cookie is of variable length, 8 to a maximum of 32 bytes. In other words: +// +// cCookie := o.Cookie[:16] +// sCookie := o.Cookie[16:] +// +// There is no guarantee that the Cookie string has a specific length. +type EDNS0_COOKIE struct { + Code uint16 // Always EDNS0COOKIE + Cookie string // Hex-encoded cookie data +} + +func (e *EDNS0_COOKIE) pack() ([]byte, error) { + h, err := hex.DecodeString(e.Cookie) + if err != nil { + return nil, err + } + return h, nil +} + +func (e *EDNS0_COOKIE) Option() uint16 { return EDNS0COOKIE } +func (e *EDNS0_COOKIE) unpack(b []byte) error { e.Cookie = hex.EncodeToString(b); return nil } +func (e *EDNS0_COOKIE) String() string { return e.Cookie } + // The EDNS0_UL (Update Lease) (draft RFC) option is used to tell the server to set // an expiration on an update RR. This is helpful for clients that cannot clean // up after themselves. This is a draft RFC and more information can be found at @@ -306,10 +347,7 @@ func (e *EDNS0_UL) String() string { return strconv.FormatUint(uint64(e.Lease), // Copied: http://golang.org/src/pkg/net/dnsmsg.go func (e *EDNS0_UL) pack() ([]byte, error) { b := make([]byte, 4) - b[0] = byte(e.Lease >> 24) - b[1] = byte(e.Lease >> 16) - b[2] = byte(e.Lease >> 8) - b[3] = byte(e.Lease) + binary.BigEndian.PutUint32(b, e.Lease) return b, nil } @@ -317,7 +355,7 @@ func (e *EDNS0_UL) unpack(b []byte) error { if len(b) < 4 { return ErrBuf } - e.Lease = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) + e.Lease = binary.BigEndian.Uint32(b) return nil } @@ -336,21 +374,11 @@ func (e *EDNS0_LLQ) Option() uint16 { return EDNS0LLQ } func (e *EDNS0_LLQ) pack() ([]byte, error) { b := make([]byte, 18) - b[0], b[1] = packUint16(e.Version) - b[2], b[3] = packUint16(e.Opcode) - b[4], b[5] = packUint16(e.Error) - b[6] = byte(e.Id >> 56) - b[7] = byte(e.Id >> 48) - b[8] = byte(e.Id >> 40) - b[9] = byte(e.Id >> 32) - b[10] = byte(e.Id >> 24) - b[11] = byte(e.Id >> 16) - b[12] = byte(e.Id >> 8) - b[13] = byte(e.Id) - b[14] = byte(e.LeaseLife >> 24) - b[15] = byte(e.LeaseLife >> 16) - b[16] = byte(e.LeaseLife >> 8) - b[17] = byte(e.LeaseLife) + binary.BigEndian.PutUint16(b[0:], e.Version) + binary.BigEndian.PutUint16(b[2:], e.Opcode) + binary.BigEndian.PutUint16(b[4:], e.Error) + binary.BigEndian.PutUint64(b[6:], e.Id) + binary.BigEndian.PutUint32(b[14:], e.LeaseLife) return b, nil } @@ -358,12 +386,11 @@ func (e *EDNS0_LLQ) unpack(b []byte) error { if len(b) < 18 { return ErrBuf } - e.Version, _ = unpackUint16(b, 0) - e.Opcode, _ = unpackUint16(b, 2) - e.Error, _ = unpackUint16(b, 4) - e.Id = uint64(b[6])<<56 | uint64(b[6+1])<<48 | uint64(b[6+2])<<40 | - uint64(b[6+3])<<32 | uint64(b[6+4])<<24 | uint64(b[6+5])<<16 | uint64(b[6+6])<<8 | uint64(b[6+7]) - e.LeaseLife = uint32(b[14])<<24 | uint32(b[14+1])<<16 | uint32(b[14+2])<<8 | uint32(b[14+3]) + e.Version = binary.BigEndian.Uint16(b[0:]) + e.Opcode = binary.BigEndian.Uint16(b[2:]) + e.Error = binary.BigEndian.Uint16(b[4:]) + e.Id = binary.BigEndian.Uint64(b[6:]) + e.LeaseLife = binary.BigEndian.Uint32(b[14:]) return nil } @@ -459,7 +486,7 @@ func (e *EDNS0_EXPIRE) unpack(b []byte) error { if len(b) < 4 { return ErrBuf } - e.Expire = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]) + e.Expire = binary.BigEndian.Uint32(b) return nil } diff --git a/vendor/github.com/miekg/dns/format.go b/vendor/github.com/miekg/dns/format.go index 1ac1664fe29f..3f5303c20138 100644 --- a/vendor/github.com/miekg/dns/format.go +++ b/vendor/github.com/miekg/dns/format.go @@ -69,15 +69,6 @@ func Field(r RR, i int) string { s += " " + Type(d.Index(i).Uint()).String() } return s - case `dns:"wks"`: - if d.Len() == 0 { - return "" - } - s := strconv.Itoa(int(d.Index(0).Uint())) - for i := 0; i < d.Len(); i++ { - s += " " + strconv.Itoa(int(d.Index(i).Uint())) - } - return s default: // if it does not have a tag its a string slice fallthrough diff --git a/vendor/github.com/miekg/dns/zgenerate.go b/vendor/github.com/miekg/dns/generate.go similarity index 83% rename from vendor/github.com/miekg/dns/zgenerate.go rename to vendor/github.com/miekg/dns/generate.go index ce7b540a5d83..e4481a4b0d8d 100644 --- a/vendor/github.com/miekg/dns/zgenerate.go +++ b/vendor/github.com/miekg/dns/generate.go @@ -2,6 +2,7 @@ package dns import ( "bytes" + "errors" "fmt" "strconv" "strings" @@ -25,7 +26,7 @@ func generate(l lex, c chan lex, t chan *Token, o string) string { if i+1 == len(l.token) { return "bad step in $GENERATE range" } - if s, e := strconv.Atoi(l.token[i+1:]); e == nil { + if s, err := strconv.Atoi(l.token[i+1:]); err == nil { if s < 0 { return "bad step in $GENERATE range" } @@ -65,7 +66,7 @@ BuildRR: escape bool dom bytes.Buffer mod string - err string + err error offset int ) @@ -104,8 +105,8 @@ BuildRR: return "bad modifier in $GENERATE" } mod, offset, err = modToPrintf(s[j+2 : j+2+sep]) - if err != "" { - return err + if err != nil { + return err.Error() } j += 2 + sep // Jump to it } @@ -119,9 +120,9 @@ BuildRR: } } // Re-parse the RR and send it on the current channel t - rx, e := NewRR("$ORIGIN " + o + "\n" + dom.String()) - if e != nil { - return e.(*ParseError).err + rx, err := NewRR("$ORIGIN " + o + "\n" + dom.String()) + if err != nil { + return err.Error() } t <- &Token{RR: rx} // Its more efficient to first built the rrlist and then parse it in @@ -131,28 +132,28 @@ BuildRR: } // Convert a $GENERATE modifier 0,0,d to something Printf can deal with. -func modToPrintf(s string) (string, int, string) { +func modToPrintf(s string) (string, int, error) { xs := strings.SplitN(s, ",", 3) if len(xs) != 3 { - return "", 0, "bad modifier in $GENERATE" + return "", 0, errors.New("bad modifier in $GENERATE") } // xs[0] is offset, xs[1] is width, xs[2] is base if xs[2] != "o" && xs[2] != "d" && xs[2] != "x" && xs[2] != "X" { - return "", 0, "bad base in $GENERATE" + return "", 0, errors.New("bad base in $GENERATE") } offset, err := strconv.Atoi(xs[0]) if err != nil || offset > 255 { - return "", 0, "bad offset in $GENERATE" + return "", 0, errors.New("bad offset in $GENERATE") } width, err := strconv.Atoi(xs[1]) if err != nil || width > 255 { - return "", offset, "bad width in $GENERATE" + return "", offset, errors.New("bad width in $GENERATE") } switch { case width < 0: - return "", offset, "bad width in $GENERATE" + return "", offset, errors.New("bad width in $GENERATE") case width == 0: - return "%" + xs[1] + xs[2], offset, "" + return "%" + xs[1] + xs[2], offset, nil } - return "%0" + xs[1] + xs[2], offset, "" + return "%0" + xs[1] + xs[2], offset, nil } diff --git a/vendor/github.com/miekg/dns/labels.go b/vendor/github.com/miekg/dns/labels.go index cb549fc672c0..fca5c7dd2d15 100644 --- a/vendor/github.com/miekg/dns/labels.go +++ b/vendor/github.com/miekg/dns/labels.go @@ -107,7 +107,7 @@ func CountLabel(s string) (labels int) { // Split splits a name s into its label indexes. // www.miek.nl. returns []int{0, 4, 9}, www.miek.nl also returns []int{0, 4, 9}. -// The root name (.) returns nil. Also see SplitDomainName. +// The root name (.) returns nil. Also see SplitDomainName. // s must be a syntactically valid domain name. func Split(s string) []int { if s == "." { diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go index 7274800fc018..ec2f7ab7bb7e 100644 --- a/vendor/github.com/miekg/dns/msg.go +++ b/vendor/github.com/miekg/dns/msg.go @@ -8,55 +8,54 @@ package dns +//go:generate go run msg_generate.go + import ( - "encoding/base32" - "encoding/base64" - "encoding/hex" + crand "crypto/rand" + "encoding/binary" "math/big" "math/rand" - "net" - "reflect" "strconv" - "time" ) +func init() { + // Initialize default math/rand source using crypto/rand to provide better + // security without the performance trade-off. + buf := make([]byte, 8) + _, err := crand.Read(buf) + if err != nil { + // Failed to read from cryptographic source, fallback to default initial + // seed (1) by returning early + return + } + seed := binary.BigEndian.Uint64(buf) + rand.Seed(int64(seed)) +} + const maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer var ( - // ErrAlg indicates an error with the (DNSSEC) algorithm. - ErrAlg error = &Error{err: "bad algorithm"} - // ErrAuth indicates an error in the TSIG authentication. - ErrAuth error = &Error{err: "bad authentication"} - // ErrBuf indicates that the buffer used it too small for the message. - ErrBuf error = &Error{err: "buffer size too small"} - // ErrConnEmpty indicates a connection is being uses before it is initialized. - ErrConnEmpty error = &Error{err: "conn has no connection"} - // ErrExtendedRcode ... - ErrExtendedRcode error = &Error{err: "bad extended rcode"} - // ErrFqdn indicates that a domain name does not have a closing dot. - ErrFqdn error = &Error{err: "domain must be fully qualified"} - // ErrId indicates there is a mismatch with the message's ID. - ErrId error = &Error{err: "id mismatch"} - // ErrKeyAlg indicates that the algorithm in the key is not valid. - ErrKeyAlg error = &Error{err: "bad key algorithm"} - ErrKey error = &Error{err: "bad key"} - ErrKeySize error = &Error{err: "bad key size"} - ErrNoSig error = &Error{err: "no signature found"} - ErrPrivKey error = &Error{err: "bad private key"} - ErrRcode error = &Error{err: "bad rcode"} - ErrRdata error = &Error{err: "bad rdata"} - ErrRRset error = &Error{err: "bad rrset"} - ErrSecret error = &Error{err: "no secrets defined"} - ErrShortRead error = &Error{err: "short read"} - // ErrSig indicates that a signature can not be cryptographically validated. - ErrSig error = &Error{err: "bad signature"} - // ErrSOA indicates that no SOA RR was seen when doing zone transfers. - ErrSoa error = &Error{err: "no SOA"} - // ErrTime indicates a timing error in TSIG authentication. - ErrTime error = &Error{err: "bad time"} - // ErrTruncated indicates that we failed to unpack a truncated message. - // We unpacked as much as we had so Msg can still be used, if desired. - ErrTruncated error = &Error{err: "failed to unpack truncated message"} + ErrAlg error = &Error{err: "bad algorithm"} // ErrAlg indicates an error with the (DNSSEC) algorithm. + ErrAuth error = &Error{err: "bad authentication"} // ErrAuth indicates an error in the TSIG authentication. + ErrBuf error = &Error{err: "buffer size too small"} // ErrBuf indicates that the buffer used it too small for the message. + ErrConnEmpty error = &Error{err: "conn has no connection"} // ErrConnEmpty indicates a connection is being uses before it is initialized. + ErrExtendedRcode error = &Error{err: "bad extended rcode"} // ErrExtendedRcode ... + ErrFqdn error = &Error{err: "domain must be fully qualified"} // ErrFqdn indicates that a domain name does not have a closing dot. + ErrId error = &Error{err: "id mismatch"} // ErrId indicates there is a mismatch with the message's ID. + ErrKeyAlg error = &Error{err: "bad key algorithm"} // ErrKeyAlg indicates that the algorithm in the key is not valid. + ErrKey error = &Error{err: "bad key"} + ErrKeySize error = &Error{err: "bad key size"} + ErrNoSig error = &Error{err: "no signature found"} + ErrPrivKey error = &Error{err: "bad private key"} + ErrRcode error = &Error{err: "bad rcode"} + ErrRdata error = &Error{err: "bad rdata"} + ErrRRset error = &Error{err: "bad rrset"} + ErrSecret error = &Error{err: "no secrets defined"} + ErrShortRead error = &Error{err: "short read"} + ErrSig error = &Error{err: "bad signature"} // ErrSig indicates that a signature can not be cryptographically validated. + ErrSoa error = &Error{err: "no SOA"} // ErrSOA indicates that no SOA RR was seen when doing zone transfers. + ErrTime error = &Error{err: "bad time"} // ErrTime indicates a timing error in TSIG authentication. + ErrTruncated error = &Error{err: "failed to unpack truncated message"} // ErrTruncated indicates that we failed to unpack a truncated message. We unpacked as much as we had so Msg can still be used, if desired. ) // Id, by default, returns a 16 bits random number to be used as a @@ -67,6 +66,13 @@ var ( // dns.Id = func() uint16 { return 3 } var Id func() uint16 = id +// id returns a 16 bits random number to be used as a +// message id. The random provided should be good enough. +func id() uint16 { + id32 := rand.Uint32() + return uint16(id32) +} + // MsgHdr is a a manually-unpacked version of (id, bits). type MsgHdr struct { Id uint16 @@ -85,25 +91,13 @@ type MsgHdr struct { // Msg contains the layout of a DNS message. type Msg struct { MsgHdr - Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format. This not part of the official DNS packet format. + Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format. Question []Question // Holds the RR(s) of the question section. Answer []RR // Holds the RR(s) of the answer section. Ns []RR // Holds the RR(s) of the authority section. Extra []RR // Holds the RR(s) of the additional section. } -// StringToType is the reverse of TypeToString, needed for string parsing. -var StringToType = reverseInt16(TypeToString) - -// StringToClass is the reverse of ClassToString, needed for string parsing. -var StringToClass = reverseInt16(ClassToString) - -// Map of opcodes strings. -var StringToOpcode = reverseInt(OpcodeToString) - -// Map of rcodes strings. -var StringToRcode = reverseInt(RcodeToString) - // ClassToString is a maps Classes to strings for each CLASS wire type. var ClassToString = map[uint16]string{ ClassINET: "IN", @@ -131,27 +125,22 @@ var RcodeToString = map[int]string{ RcodeNameError: "NXDOMAIN", RcodeNotImplemented: "NOTIMPL", RcodeRefused: "REFUSED", - RcodeYXDomain: "YXDOMAIN", // From RFC 2136 + RcodeYXDomain: "YXDOMAIN", // See RFC 2136 RcodeYXRrset: "YXRRSET", RcodeNXRrset: "NXRRSET", RcodeNotAuth: "NOTAUTH", RcodeNotZone: "NOTZONE", RcodeBadSig: "BADSIG", // Also known as RcodeBadVers, see RFC 6891 // RcodeBadVers: "BADVERS", - RcodeBadKey: "BADKEY", - RcodeBadTime: "BADTIME", - RcodeBadMode: "BADMODE", - RcodeBadName: "BADNAME", - RcodeBadAlg: "BADALG", - RcodeBadTrunc: "BADTRUNC", + RcodeBadKey: "BADKEY", + RcodeBadTime: "BADTIME", + RcodeBadMode: "BADMODE", + RcodeBadName: "BADNAME", + RcodeBadAlg: "BADALG", + RcodeBadTrunc: "BADTRUNC", + RcodeBadCookie: "BADCOOKIE", } -// Rather than write the usual handful of routines to pack and -// unpack every message that can appear on the wire, we use -// reflection to write a generic pack/unpack for structs and then -// use it. Thus, if in the future we need to define new message -// structs, no new pack/unpack/printing code needs to be written. - // Domain names are a sequence of counted strings // split at the dots. They end with a zero-length string. @@ -291,11 +280,11 @@ func packDomainName(s string, msg []byte, off int, compression map[string]int, c if pointer != -1 { // We have two bytes (14 bits) to put the pointer in // if msg == nil, we will never do compression - msg[nameoffset], msg[nameoffset+1] = packUint16(uint16(pointer ^ 0xC000)) + binary.BigEndian.PutUint16(msg[nameoffset:], uint16(pointer^0xC000)) off = nameoffset + 1 goto End } - if msg != nil { + if msg != nil && off < len(msg) { msg[off] = 0 } End: @@ -401,7 +390,6 @@ Loop: } func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { - var err error if len(txt) == 0 { if offset >= len(msg) { return offset, ErrBuf @@ -409,6 +397,7 @@ func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { msg[offset] = 0 return offset, nil } + var err error for i := range txt { if len(txt[i]) > len(tmp) { return offset, ErrBuf @@ -418,12 +407,12 @@ func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) { return offset, err } } - return offset, err + return offset, nil } func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) { lenByteOffset := offset - if offset >= len(msg) { + if offset >= len(msg) || len(s) > len(tmp) { return offset, ErrBuf } offset++ @@ -465,7 +454,7 @@ func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) { } func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) { - if offset >= len(msg) { + if offset >= len(msg) || len(s) > len(tmp) { return offset, ErrBuf } bs := tmp[:len(s)] @@ -545,764 +534,6 @@ func unpackTxtString(msg []byte, offset int) (string, int, error) { return string(s), offset, nil } -// Pack a reflect.StructValue into msg. Struct members can only be uint8, uint16, uint32, string, -// slices and other (often anonymous) structs. -func packStructValue(val reflect.Value, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) { - var txtTmp []byte - lenmsg := len(msg) - numfield := val.NumField() - for i := 0; i < numfield; i++ { - typefield := val.Type().Field(i) - if typefield.Tag == `dns:"-"` { - continue - } - switch fv := val.Field(i); fv.Kind() { - default: - return lenmsg, &Error{err: "bad kind packing"} - case reflect.Interface: - // PrivateRR is the only RR implementation that has interface field. - // therefore it's expected that this interface would be PrivateRdata - switch data := fv.Interface().(type) { - case PrivateRdata: - n, err := data.Pack(msg[off:]) - if err != nil { - return lenmsg, err - } - off += n - default: - return lenmsg, &Error{err: "bad kind interface packing"} - } - case reflect.Slice: - switch typefield.Tag { - default: - return lenmsg, &Error{"bad tag packing slice: " + typefield.Tag.Get("dns")} - case `dns:"domain-name"`: - for j := 0; j < val.Field(i).Len(); j++ { - element := val.Field(i).Index(j).String() - off, err = PackDomainName(element, msg, off, compression, false && compress) - if err != nil { - return lenmsg, err - } - } - case `dns:"txt"`: - if txtTmp == nil { - txtTmp = make([]byte, 256*4+1) - } - off, err = packTxt(fv.Interface().([]string), msg, off, txtTmp) - if err != nil { - return lenmsg, err - } - case `dns:"opt"`: // edns - for j := 0; j < val.Field(i).Len(); j++ { - element := val.Field(i).Index(j).Interface() - b, e := element.(EDNS0).pack() - if e != nil { - return lenmsg, &Error{err: "overflow packing opt"} - } - // Option code - msg[off], msg[off+1] = packUint16(element.(EDNS0).Option()) - // Length - msg[off+2], msg[off+3] = packUint16(uint16(len(b))) - off += 4 - if off+len(b) > lenmsg { - copy(msg[off:], b) - off = lenmsg - continue - } - // Actual data - copy(msg[off:off+len(b)], b) - off += len(b) - } - case `dns:"a"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, must be 1 - if val.Field(2).Uint() != 1 { - continue - } - } - // It must be a slice of 4, even if it is 16, we encode - // only the first 4 - if off+net.IPv4len > lenmsg { - return lenmsg, &Error{err: "overflow packing a"} - } - switch fv.Len() { - case net.IPv6len: - msg[off] = byte(fv.Index(12).Uint()) - msg[off+1] = byte(fv.Index(13).Uint()) - msg[off+2] = byte(fv.Index(14).Uint()) - msg[off+3] = byte(fv.Index(15).Uint()) - off += net.IPv4len - case net.IPv4len: - msg[off] = byte(fv.Index(0).Uint()) - msg[off+1] = byte(fv.Index(1).Uint()) - msg[off+2] = byte(fv.Index(2).Uint()) - msg[off+3] = byte(fv.Index(3).Uint()) - off += net.IPv4len - case 0: - // Allowed, for dynamic updates - default: - return lenmsg, &Error{err: "overflow packing a"} - } - case `dns:"aaaa"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, must be 2 - if val.Field(2).Uint() != 2 { - continue - } - } - if fv.Len() == 0 { - break - } - if fv.Len() > net.IPv6len || off+fv.Len() > lenmsg { - return lenmsg, &Error{err: "overflow packing aaaa"} - } - for j := 0; j < net.IPv6len; j++ { - msg[off] = byte(fv.Index(j).Uint()) - off++ - } - case `dns:"wks"`: - // TODO(miek): this is wrong should be lenrd - if off == lenmsg { - break // dyn. updates - } - if val.Field(i).Len() == 0 { - break - } - off1 := off - for j := 0; j < val.Field(i).Len(); j++ { - serv := int(fv.Index(j).Uint()) - if off+serv/8+1 > len(msg) { - return len(msg), &Error{err: "overflow packing wks"} - } - msg[off+serv/8] |= byte(1 << (7 - uint(serv%8))) - if off+serv/8+1 > off1 { - off1 = off + serv/8 + 1 - } - } - off = off1 - case `dns:"nsec"`: // NSEC/NSEC3 - // This is the uint16 type bitmap - if val.Field(i).Len() == 0 { - // Do absolutely nothing - break - } - var lastwindow, lastlength uint16 - for j := 0; j < val.Field(i).Len(); j++ { - t := uint16(fv.Index(j).Uint()) - window := t / 256 - length := (t-window*256)/8 + 1 - if window > lastwindow && lastlength != 0 { - // New window, jump to the new offset - off += int(lastlength) + 2 - lastlength = 0 - } - if window < lastwindow || length < lastlength { - return len(msg), &Error{err: "nsec bits out of order"} - } - if off+2+int(length) > len(msg) { - return len(msg), &Error{err: "overflow packing nsec"} - } - // Setting the window # - msg[off] = byte(window) - // Setting the octets length - msg[off+1] = byte(length) - // Setting the bit value for the type in the right octet - msg[off+1+int(length)] |= byte(1 << (7 - (t % 8))) - lastwindow, lastlength = window, length - } - off += int(lastlength) + 2 - } - case reflect.Struct: - off, err = packStructValue(fv, msg, off, compression, compress) - if err != nil { - return lenmsg, err - } - case reflect.Uint8: - if off+1 > lenmsg { - return lenmsg, &Error{err: "overflow packing uint8"} - } - msg[off] = byte(fv.Uint()) - off++ - case reflect.Uint16: - if off+2 > lenmsg { - return lenmsg, &Error{err: "overflow packing uint16"} - } - i := fv.Uint() - msg[off] = byte(i >> 8) - msg[off+1] = byte(i) - off += 2 - case reflect.Uint32: - if off+4 > lenmsg { - return lenmsg, &Error{err: "overflow packing uint32"} - } - i := fv.Uint() - msg[off] = byte(i >> 24) - msg[off+1] = byte(i >> 16) - msg[off+2] = byte(i >> 8) - msg[off+3] = byte(i) - off += 4 - case reflect.Uint64: - switch typefield.Tag { - default: - if off+8 > lenmsg { - return lenmsg, &Error{err: "overflow packing uint64"} - } - i := fv.Uint() - msg[off] = byte(i >> 56) - msg[off+1] = byte(i >> 48) - msg[off+2] = byte(i >> 40) - msg[off+3] = byte(i >> 32) - msg[off+4] = byte(i >> 24) - msg[off+5] = byte(i >> 16) - msg[off+6] = byte(i >> 8) - msg[off+7] = byte(i) - off += 8 - case `dns:"uint48"`: - // Used in TSIG, where it stops at 48 bits, so we discard the upper 16 - if off+6 > lenmsg { - return lenmsg, &Error{err: "overflow packing uint64 as uint48"} - } - i := fv.Uint() - msg[off] = byte(i >> 40) - msg[off+1] = byte(i >> 32) - msg[off+2] = byte(i >> 24) - msg[off+3] = byte(i >> 16) - msg[off+4] = byte(i >> 8) - msg[off+5] = byte(i) - off += 6 - } - case reflect.String: - // There are multiple string encodings. - // The tag distinguishes ordinary strings from domain names. - s := fv.String() - switch typefield.Tag { - default: - return lenmsg, &Error{"bad tag packing string: " + typefield.Tag.Get("dns")} - case `dns:"base64"`: - b64, e := fromBase64([]byte(s)) - if e != nil { - return lenmsg, e - } - copy(msg[off:off+len(b64)], b64) - off += len(b64) - case `dns:"domain-name"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, 1 and 2 or used for addresses - x := val.Field(2).Uint() - if x == 1 || x == 2 { - continue - } - } - if off, err = PackDomainName(s, msg, off, compression, false && compress); err != nil { - return lenmsg, err - } - case `dns:"cdomain-name"`: - if off, err = PackDomainName(s, msg, off, compression, true && compress); err != nil { - return lenmsg, err - } - case `dns:"size-base32"`: - // This is purely for NSEC3 atm, the previous byte must - // holds the length of the encoded string. As NSEC3 - // is only defined to SHA1, the hashlength is 20 (160 bits) - msg[off-1] = 20 - fallthrough - case `dns:"base32"`: - b32, e := fromBase32([]byte(s)) - if e != nil { - return lenmsg, e - } - copy(msg[off:off+len(b32)], b32) - off += len(b32) - case `dns:"size-hex"`: - fallthrough - case `dns:"hex"`: - // There is no length encoded here - h, e := hex.DecodeString(s) - if e != nil { - return lenmsg, e - } - if off+hex.DecodedLen(len(s)) > lenmsg { - return lenmsg, &Error{err: "overflow packing hex"} - } - copy(msg[off:off+hex.DecodedLen(len(s))], h) - off += hex.DecodedLen(len(s)) - case `dns:"size"`: - // the size is already encoded in the RR, we can safely use the - // length of string. String is RAW (not encoded in hex, nor base64) - copy(msg[off:off+len(s)], s) - off += len(s) - case `dns:"octet"`: - bytesTmp := make([]byte, 256) - off, err = packOctetString(fv.String(), msg, off, bytesTmp) - if err != nil { - return lenmsg, err - } - case `dns:"txt"`: - fallthrough - case "": - if txtTmp == nil { - txtTmp = make([]byte, 256*4+1) - } - off, err = packTxtString(fv.String(), msg, off, txtTmp) - if err != nil { - return lenmsg, err - } - } - } - } - return off, nil -} - -func structValue(any interface{}) reflect.Value { - return reflect.ValueOf(any).Elem() -} - -// PackStruct packs any structure to wire format. -func PackStruct(any interface{}, msg []byte, off int) (off1 int, err error) { - off, err = packStructValue(structValue(any), msg, off, nil, false) - return off, err -} - -func packStructCompress(any interface{}, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) { - off, err = packStructValue(structValue(any), msg, off, compression, compress) - return off, err -} - -// Unpack a reflect.StructValue from msg. -// Same restrictions as packStructValue. -func unpackStructValue(val reflect.Value, msg []byte, off int) (off1 int, err error) { - lenmsg := len(msg) - for i := 0; i < val.NumField(); i++ { - if off > lenmsg { - return lenmsg, &Error{"bad offset unpacking"} - } - switch fv := val.Field(i); fv.Kind() { - default: - return lenmsg, &Error{err: "bad kind unpacking"} - case reflect.Interface: - // PrivateRR is the only RR implementation that has interface field. - // therefore it's expected that this interface would be PrivateRdata - switch data := fv.Interface().(type) { - case PrivateRdata: - n, err := data.Unpack(msg[off:]) - if err != nil { - return lenmsg, err - } - off += n - default: - return lenmsg, &Error{err: "bad kind interface unpacking"} - } - case reflect.Slice: - switch val.Type().Field(i).Tag { - default: - return lenmsg, &Error{"bad tag unpacking slice: " + val.Type().Field(i).Tag.Get("dns")} - case `dns:"domain-name"`: - // HIP record slice of name (or none) - var servers []string - var s string - for off < lenmsg { - s, off, err = UnpackDomainName(msg, off) - if err != nil { - return lenmsg, err - } - servers = append(servers, s) - } - fv.Set(reflect.ValueOf(servers)) - case `dns:"txt"`: - if off == lenmsg { - break - } - var txt []string - txt, off, err = unpackTxt(msg, off) - if err != nil { - return lenmsg, err - } - fv.Set(reflect.ValueOf(txt)) - case `dns:"opt"`: // edns0 - if off == lenmsg { - // This is an EDNS0 (OPT Record) with no rdata - // We can safely return here. - break - } - var edns []EDNS0 - Option: - code := uint16(0) - if off+4 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking opt"} - } - code, off = unpackUint16(msg, off) - optlen, off1 := unpackUint16(msg, off) - if off1+int(optlen) > lenmsg { - return lenmsg, &Error{err: "overflow unpacking opt"} - } - switch code { - case EDNS0NSID: - e := new(EDNS0_NSID) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - case EDNS0SUBNET, EDNS0SUBNETDRAFT: - e := new(EDNS0_SUBNET) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - if code == EDNS0SUBNETDRAFT { - e.DraftOption = true - } - case EDNS0UL: - e := new(EDNS0_UL) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - case EDNS0LLQ: - e := new(EDNS0_LLQ) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - case EDNS0DAU: - e := new(EDNS0_DAU) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - case EDNS0DHU: - e := new(EDNS0_DHU) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - case EDNS0N3U: - e := new(EDNS0_N3U) - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - default: - e := new(EDNS0_LOCAL) - e.Code = code - if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil { - return lenmsg, err - } - edns = append(edns, e) - off = off1 + int(optlen) - } - if off < lenmsg { - goto Option - } - fv.Set(reflect.ValueOf(edns)) - case `dns:"a"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, must be 1 - if val.Field(2).Uint() != 1 { - continue - } - } - if off == lenmsg { - break // dyn. update - } - if off+net.IPv4len > lenmsg { - return lenmsg, &Error{err: "overflow unpacking a"} - } - fv.Set(reflect.ValueOf(net.IPv4(msg[off], msg[off+1], msg[off+2], msg[off+3]))) - off += net.IPv4len - case `dns:"aaaa"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, must be 2 - if val.Field(2).Uint() != 2 { - continue - } - } - if off == lenmsg { - break - } - if off+net.IPv6len > lenmsg { - return lenmsg, &Error{err: "overflow unpacking aaaa"} - } - fv.Set(reflect.ValueOf(net.IP{msg[off], msg[off+1], msg[off+2], msg[off+3], msg[off+4], - msg[off+5], msg[off+6], msg[off+7], msg[off+8], msg[off+9], msg[off+10], - msg[off+11], msg[off+12], msg[off+13], msg[off+14], msg[off+15]})) - off += net.IPv6len - case `dns:"wks"`: - // Rest of the record is the bitmap - var serv []uint16 - j := 0 - for off < lenmsg { - if off+1 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking wks"} - } - b := msg[off] - // Check the bits one by one, and set the type - if b&0x80 == 0x80 { - serv = append(serv, uint16(j*8+0)) - } - if b&0x40 == 0x40 { - serv = append(serv, uint16(j*8+1)) - } - if b&0x20 == 0x20 { - serv = append(serv, uint16(j*8+2)) - } - if b&0x10 == 0x10 { - serv = append(serv, uint16(j*8+3)) - } - if b&0x8 == 0x8 { - serv = append(serv, uint16(j*8+4)) - } - if b&0x4 == 0x4 { - serv = append(serv, uint16(j*8+5)) - } - if b&0x2 == 0x2 { - serv = append(serv, uint16(j*8+6)) - } - if b&0x1 == 0x1 { - serv = append(serv, uint16(j*8+7)) - } - j++ - off++ - } - fv.Set(reflect.ValueOf(serv)) - case `dns:"nsec"`: // NSEC/NSEC3 - if off == len(msg) { - break - } - // Rest of the record is the type bitmap - var nsec []uint16 - length := 0 - window := 0 - lastwindow := -1 - for off < len(msg) { - if off+2 > len(msg) { - return len(msg), &Error{err: "overflow unpacking nsecx"} - } - window = int(msg[off]) - length = int(msg[off+1]) - off += 2 - if window <= lastwindow { - // RFC 4034: Blocks are present in the NSEC RR RDATA in - // increasing numerical order. - return len(msg), &Error{err: "out of order NSEC block"} - } - if length == 0 { - // RFC 4034: Blocks with no types present MUST NOT be included. - return len(msg), &Error{err: "empty NSEC block"} - } - if length > 32 { - return len(msg), &Error{err: "NSEC block too long"} - } - if off+length > len(msg) { - return len(msg), &Error{err: "overflowing NSEC block"} - } - - // Walk the bytes in the window and extract the type bits - for j := 0; j < length; j++ { - b := msg[off+j] - // Check the bits one by one, and set the type - if b&0x80 == 0x80 { - nsec = append(nsec, uint16(window*256+j*8+0)) - } - if b&0x40 == 0x40 { - nsec = append(nsec, uint16(window*256+j*8+1)) - } - if b&0x20 == 0x20 { - nsec = append(nsec, uint16(window*256+j*8+2)) - } - if b&0x10 == 0x10 { - nsec = append(nsec, uint16(window*256+j*8+3)) - } - if b&0x8 == 0x8 { - nsec = append(nsec, uint16(window*256+j*8+4)) - } - if b&0x4 == 0x4 { - nsec = append(nsec, uint16(window*256+j*8+5)) - } - if b&0x2 == 0x2 { - nsec = append(nsec, uint16(window*256+j*8+6)) - } - if b&0x1 == 0x1 { - nsec = append(nsec, uint16(window*256+j*8+7)) - } - } - off += length - lastwindow = window - } - fv.Set(reflect.ValueOf(nsec)) - } - case reflect.Struct: - off, err = unpackStructValue(fv, msg, off) - if err != nil { - return lenmsg, err - } - if val.Type().Field(i).Name == "Hdr" { - lenrd := off + int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint()) - if lenrd > lenmsg { - return lenmsg, &Error{err: "overflowing header size"} - } - msg = msg[:lenrd] - lenmsg = len(msg) - } - case reflect.Uint8: - if off == lenmsg { - break - } - if off+1 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking uint8"} - } - fv.SetUint(uint64(uint8(msg[off]))) - off++ - case reflect.Uint16: - if off == lenmsg { - break - } - var i uint16 - if off+2 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking uint16"} - } - i, off = unpackUint16(msg, off) - fv.SetUint(uint64(i)) - case reflect.Uint32: - if off == lenmsg { - break - } - if off+4 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking uint32"} - } - fv.SetUint(uint64(uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]))) - off += 4 - case reflect.Uint64: - if off == lenmsg { - break - } - switch val.Type().Field(i).Tag { - default: - if off+8 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking uint64"} - } - fv.SetUint(uint64(uint64(msg[off])<<56 | uint64(msg[off+1])<<48 | uint64(msg[off+2])<<40 | - uint64(msg[off+3])<<32 | uint64(msg[off+4])<<24 | uint64(msg[off+5])<<16 | uint64(msg[off+6])<<8 | uint64(msg[off+7]))) - off += 8 - case `dns:"uint48"`: - // Used in TSIG where the last 48 bits are occupied, so for now, assume a uint48 (6 bytes) - if off+6 > lenmsg { - return lenmsg, &Error{err: "overflow unpacking uint64 as uint48"} - } - fv.SetUint(uint64(uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 | - uint64(msg[off+4])<<8 | uint64(msg[off+5]))) - off += 6 - } - case reflect.String: - var s string - if off == lenmsg { - break - } - switch val.Type().Field(i).Tag { - default: - return lenmsg, &Error{"bad tag unpacking string: " + val.Type().Field(i).Tag.Get("dns")} - case `dns:"octet"`: - s = string(msg[off:]) - off = lenmsg - case `dns:"hex"`: - hexend := lenmsg - if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) { - hexend = off + int(val.FieldByName("HitLength").Uint()) - } - if hexend > lenmsg { - return lenmsg, &Error{err: "overflow unpacking HIP hex"} - } - s = hex.EncodeToString(msg[off:hexend]) - off = hexend - case `dns:"base64"`: - // Rest of the RR is base64 encoded value - b64end := lenmsg - if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) { - b64end = off + int(val.FieldByName("PublicKeyLength").Uint()) - } - if b64end > lenmsg { - return lenmsg, &Error{err: "overflow unpacking HIP base64"} - } - s = toBase64(msg[off:b64end]) - off = b64end - case `dns:"cdomain-name"`: - fallthrough - case `dns:"domain-name"`: - if val.Type().String() == "dns.IPSECKEY" { - // Field(2) is GatewayType, 1 and 2 or used for addresses - x := val.Field(2).Uint() - if x == 1 || x == 2 { - continue - } - } - if off == lenmsg && int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint()) == 0 { - // zero rdata is ok for dyn updates, but only if rdlength is 0 - break - } - s, off, err = UnpackDomainName(msg, off) - if err != nil { - return lenmsg, err - } - case `dns:"size-base32"`: - var size int - switch val.Type().Name() { - case "NSEC3": - switch val.Type().Field(i).Name { - case "NextDomain": - name := val.FieldByName("HashLength") - size = int(name.Uint()) - } - } - if off+size > lenmsg { - return lenmsg, &Error{err: "overflow unpacking base32"} - } - s = toBase32(msg[off : off+size]) - off += size - case `dns:"size-hex"`: - // a "size" string, but it must be encoded in hex in the string - var size int - switch val.Type().Name() { - case "NSEC3": - switch val.Type().Field(i).Name { - case "Salt": - name := val.FieldByName("SaltLength") - size = int(name.Uint()) - case "NextDomain": - name := val.FieldByName("HashLength") - size = int(name.Uint()) - } - case "TSIG": - switch val.Type().Field(i).Name { - case "MAC": - name := val.FieldByName("MACSize") - size = int(name.Uint()) - case "OtherData": - name := val.FieldByName("OtherLen") - size = int(name.Uint()) - } - } - if off+size > lenmsg { - return lenmsg, &Error{err: "overflow unpacking hex"} - } - s = hex.EncodeToString(msg[off : off+size]) - off += size - case `dns:"txt"`: - fallthrough - case "": - s, off, err = unpackTxtString(msg, off) - } - fv.SetString(s) - } - } - return off, nil -} - // Helpers for dealing with escaped bytes func isDigit(b byte) bool { return b >= '0' && b <= '9' } @@ -1310,12 +541,6 @@ func dddToByte(s []byte) byte { return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0')) } -// UnpackStruct unpacks a binary message from offset off to the interface -// value given. -func UnpackStruct(any interface{}, msg []byte, off int) (int, error) { - return unpackStructValue(structValue(any), msg, off) -} - // Helper function for packing and unpacking func intToBytes(i *big.Int, length int) []byte { buf := i.Bytes() @@ -1327,38 +552,6 @@ func intToBytes(i *big.Int, length int) []byte { return buf } -func unpackUint16(msg []byte, off int) (uint16, int) { - return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2 -} - -func packUint16(i uint16) (byte, byte) { - return byte(i >> 8), byte(i) -} - -func toBase32(b []byte) string { - return base32.HexEncoding.EncodeToString(b) -} - -func fromBase32(s []byte) (buf []byte, err error) { - buflen := base32.HexEncoding.DecodedLen(len(s)) - buf = make([]byte, buflen) - n, err := base32.HexEncoding.Decode(buf, s) - buf = buf[:n] - return -} - -func toBase64(b []byte) string { - return base64.StdEncoding.EncodeToString(b) -} - -func fromBase64(s []byte) (buf []byte, err error) { - buflen := base64.StdEncoding.DecodedLen(len(s)) - buf = make([]byte, buflen) - n, err := base64.StdEncoding.Decode(buf, s) - buf = buf[:n] - return -} - // PackRR packs a resource record rr into msg[off:]. // See PackDomainName for documentation about the compression. func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) { @@ -1366,10 +559,11 @@ func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress boo return len(msg), &Error{err: "nil rr"} } - off1, err = packStructCompress(rr, msg, off, compression, compress) + off1, err = rr.pack(msg, off, compression, compress) if err != nil { return len(msg), err } + // TODO(miek): Not sure if this is needed? If removed we can remove rawmsg.go as well. if rawSetRdlength(msg, off, off1) { return off1, nil } @@ -1378,21 +572,17 @@ func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress boo // UnpackRR unpacks msg[off:] into an RR. func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) { - // unpack just the header, to find the rr type and length - var h RR_Header - off0 := off - if off, err = UnpackStruct(&h, msg, off); err != nil { + h, off, msg, err := unpackHeader(msg, off) + if err != nil { return nil, len(msg), err } end := off + int(h.Rdlength) - // make an rr of that type and re-unpack. - mk, known := TypeToRR[h.Rrtype] - if !known { - rr = new(RFC3597) + + if fn, known := typeToUnpack[h.Rrtype]; !known { + rr, off, err = unpackRFC3597(h, msg, off) } else { - rr = mk() + rr, off, err = fn(h, msg, off) } - off, err = UnpackStruct(rr, msg, off0) if off != end { return &h, end, &Error{err: "bad rdlength"} } @@ -1425,31 +615,6 @@ func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) return dst, off, err } -// Reverse a map -func reverseInt8(m map[uint8]string) map[string]uint8 { - n := make(map[string]uint8) - for u, s := range m { - n[s] = u - } - return n -} - -func reverseInt16(m map[uint16]string) map[string]uint16 { - n := make(map[string]uint16) - for u, s := range m { - n[s] = u - } - return n -} - -func reverseInt(m map[int]string) map[string]int { - n := make(map[string]int) - for u, s := range m { - n[s] = u - } - return n -} - // Convert a MsgHdr to a string, with dig-like headers: // //;; opcode: QUERY, status: NOERROR, id: 48404 @@ -1503,8 +668,12 @@ func (dns *Msg) Pack() (msg []byte, err error) { // PackBuffer packs a Msg, using the given buffer buf. If buf is too small // a new buffer is allocated. func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) { - var dh Header - var compression map[string]int + // We use a similar function in tsig.go's stripTsig. + var ( + dh Header + compression map[string]int + ) + if dns.Compress { compression = make(map[string]int) // Compression pointer mappings } @@ -1572,12 +741,12 @@ func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) { // Pack it in: header and then the pieces. off := 0 - off, err = packStructCompress(&dh, msg, off, compression, dns.Compress) + off, err = dh.pack(msg, off, compression, dns.Compress) if err != nil { return nil, err } for i := 0; i < len(question); i++ { - off, err = packStructCompress(&question[i], msg, off, compression, dns.Compress) + off, err = question[i].pack(msg, off, compression, dns.Compress) if err != nil { return nil, err } @@ -1605,12 +774,17 @@ func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) { // Unpack unpacks a binary message to a Msg structure. func (dns *Msg) Unpack(msg []byte) (err error) { - // Header. - var dh Header - off := 0 - if off, err = UnpackStruct(&dh, msg, off); err != nil { + var ( + dh Header + off int + ) + if dh, off, err = unpackMsgHdr(msg, off); err != nil { return err } + if off == len(msg) { + return ErrTruncated + } + dns.Id = dh.Id dns.Response = (dh.Bits & _QR) != 0 dns.Opcode = int(dh.Bits>>11) & 0xF @@ -1626,10 +800,10 @@ func (dns *Msg) Unpack(msg []byte) (err error) { // Optimistically use the count given to us in the header dns.Question = make([]Question, 0, int(dh.Qdcount)) - var q Question for i := 0; i < int(dh.Qdcount); i++ { off1 := off - off, err = UnpackStruct(&q, msg, off) + var q Question + q, off, err = unpackQuestion(msg, off) if err != nil { // Even if Truncated is set, we only will set ErrTruncated if we // actually got the questions @@ -1655,6 +829,7 @@ func (dns *Msg) Unpack(msg []byte) (err error) { } // The header counts might have been wrong so we need to update it dh.Arcount = uint16(len(dns.Extra)) + if off != len(msg) { // TODO(miek) make this an error? // use PackOpt to let people tell how detailed the error reporting should be? @@ -1728,6 +903,9 @@ func (dns *Msg) Len() int { } } for i := 0; i < len(dns.Answer); i++ { + if dns.Answer[i] == nil { + continue + } l += dns.Answer[i].len() if dns.Compress { k, ok := compressionLenSearch(compression, dns.Answer[i].Header().Name) @@ -1743,6 +921,9 @@ func (dns *Msg) Len() int { } } for i := 0; i < len(dns.Ns); i++ { + if dns.Ns[i] == nil { + continue + } l += dns.Ns[i].len() if dns.Compress { k, ok := compressionLenSearch(compression, dns.Ns[i].Header().Name) @@ -1758,6 +939,9 @@ func (dns *Msg) Len() int { } } for i := 0; i < len(dns.Extra); i++ { + if dns.Extra[i] == nil { + continue + } l += dns.Extra[i].len() if dns.Compress { k, ok := compressionLenSearch(compression, dns.Extra[i].Header().Name) @@ -1807,7 +991,7 @@ func compressionLenSearch(c map[string]int, s string) (int, bool) { return 0, false } -// TODO(miek): should add all types, because the all can be *used* for compression. +// TODO(miek): should add all types, because the all can be *used* for compression. Autogenerate from msg_generate and put in zmsg.go func compressionLenHelperType(c map[string]int, r RR) { switch x := r.(type) { case *NS: @@ -1833,11 +1017,23 @@ func compressionLenHelperType(c map[string]int, r RR) { compressionLenHelper(c, x.Md) case *RT: compressionLenHelper(c, x.Host) + case *RP: + compressionLenHelper(c, x.Mbox) + compressionLenHelper(c, x.Txt) case *MINFO: compressionLenHelper(c, x.Rmail) compressionLenHelper(c, x.Email) case *AFSDB: compressionLenHelper(c, x.Hostname) + case *SRV: + compressionLenHelper(c, x.Target) + case *NAPTR: + compressionLenHelper(c, x.Replacement) + case *RRSIG: + compressionLenHelper(c, x.SignerName) + case *NSEC: + compressionLenHelper(c, x.NextDomain) + // HIP? } } @@ -1850,6 +1046,8 @@ func compressionLenSearchType(c map[string]int, r RR) (int, bool) { return compressionLenSearch(c, x.Mx) case *CNAME: return compressionLenSearch(c, x.Target) + case *DNAME: + return compressionLenSearch(c, x.Target) case *PTR: return compressionLenSearch(c, x.Ptr) case *SOA: @@ -1884,27 +1082,14 @@ func compressionLenSearchType(c map[string]int, r RR) (int, bool) { return 0, false } -// id returns a 16 bits random number to be used as a -// message id. The random provided should be good enough. -func id() uint16 { - return uint16(rand.Int()) ^ uint16(time.Now().Nanosecond()) -} - // Copy returns a new RR which is a deep-copy of r. -func Copy(r RR) RR { - r1 := r.copy() - return r1 -} +func Copy(r RR) RR { r1 := r.copy(); return r1 } // Len returns the length (in octets) of the uncompressed RR in wire format. -func Len(r RR) int { - return r.len() -} +func Len(r RR) int { return r.len() } // Copy returns a new *Msg which is a deep-copy of dns. -func (dns *Msg) Copy() *Msg { - return dns.CopyTo(new(Msg)) -} +func (dns *Msg) Copy() *Msg { return dns.CopyTo(new(Msg)) } // CopyTo copies the contents to the provided message using a deep-copy and returns the copy. func (dns *Msg) CopyTo(r1 *Msg) *Msg { @@ -1948,3 +1133,99 @@ func (dns *Msg) CopyTo(r1 *Msg) *Msg { return r1 } + +func (q *Question) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := PackDomainName(q.Name, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packUint16(q.Qtype, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(q.Qclass, msg, off) + if err != nil { + return off, err + } + return off, nil +} + +func unpackQuestion(msg []byte, off int) (Question, int, error) { + var ( + q Question + err error + ) + q.Name, off, err = UnpackDomainName(msg, off) + if err != nil { + return q, off, err + } + if off == len(msg) { + return q, off, nil + } + q.Qtype, off, err = unpackUint16(msg, off) + if err != nil { + return q, off, err + } + if off == len(msg) { + return q, off, nil + } + q.Qclass, off, err = unpackUint16(msg, off) + if off == len(msg) { + return q, off, nil + } + return q, off, err +} + +func (dh *Header) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := packUint16(dh.Id, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(dh.Bits, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(dh.Qdcount, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(dh.Ancount, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(dh.Nscount, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(dh.Arcount, msg, off) + return off, err +} + +func unpackMsgHdr(msg []byte, off int) (Header, int, error) { + var ( + dh Header + err error + ) + dh.Id, off, err = unpackUint16(msg, off) + if err != nil { + return dh, off, err + } + dh.Bits, off, err = unpackUint16(msg, off) + if err != nil { + return dh, off, err + } + dh.Qdcount, off, err = unpackUint16(msg, off) + if err != nil { + return dh, off, err + } + dh.Ancount, off, err = unpackUint16(msg, off) + if err != nil { + return dh, off, err + } + dh.Nscount, off, err = unpackUint16(msg, off) + if err != nil { + return dh, off, err + } + dh.Arcount, off, err = unpackUint16(msg, off) + return dh, off, err +} diff --git a/vendor/github.com/miekg/dns/msg_generate.go b/vendor/github.com/miekg/dns/msg_generate.go new file mode 100644 index 000000000000..166b3af00c83 --- /dev/null +++ b/vendor/github.com/miekg/dns/msg_generate.go @@ -0,0 +1,337 @@ +//+build ignore + +// msg_generate.go is meant to run with go generate. It will use +// go/{importer,types} to track down all the RR struct types. Then for each type +// it will generate pack/unpack methods based on the struct tags. The generated source is +// written to zmsg.go, and is meant to be checked into git. +package main + +import ( + "bytes" + "fmt" + "go/format" + "go/importer" + "go/types" + "log" + "os" + "strings" +) + +var packageHdr = ` +// *** DO NOT MODIFY *** +// AUTOGENERATED BY go generate from msg_generate.go + +package dns + +` + +// getTypeStruct will take a type and the package scope, and return the +// (innermost) struct if the type is considered a RR type (currently defined as +// those structs beginning with a RR_Header, could be redefined as implementing +// the RR interface). The bool return value indicates if embedded structs were +// resolved. +func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) { + st, ok := t.Underlying().(*types.Struct) + if !ok { + return nil, false + } + if st.Field(0).Type() == scope.Lookup("RR_Header").Type() { + return st, false + } + if st.Field(0).Anonymous() { + st, _ := getTypeStruct(st.Field(0).Type(), scope) + return st, true + } + return nil, false +} + +func main() { + // Import and type-check the package + pkg, err := importer.Default().Import("github.com/miekg/dns") + fatalIfErr(err) + scope := pkg.Scope() + + // Collect actual types (*X) + var namedTypes []string + for _, name := range scope.Names() { + o := scope.Lookup(name) + if o == nil || !o.Exported() { + continue + } + if st, _ := getTypeStruct(o.Type(), scope); st == nil { + continue + } + if name == "PrivateRR" { + continue + } + + // Check if corresponding TypeX exists + if scope.Lookup("Type"+o.Name()) == nil && o.Name() != "RFC3597" { + log.Fatalf("Constant Type%s does not exist.", o.Name()) + } + + namedTypes = append(namedTypes, o.Name()) + } + + b := &bytes.Buffer{} + b.WriteString(packageHdr) + + fmt.Fprint(b, "// pack*() functions\n\n") + for _, name := range namedTypes { + o := scope.Lookup(name) + st, _ := getTypeStruct(o.Type(), scope) + + fmt.Fprintf(b, "func (rr *%s) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) {\n", name) + fmt.Fprint(b, `off, err := rr.Hdr.pack(msg, off, compression, compress) +if err != nil { + return off, err +} +headerEnd := off +`) + for i := 1; i < st.NumFields(); i++ { + o := func(s string) { + fmt.Fprintf(b, s, st.Field(i).Name()) + fmt.Fprint(b, `if err != nil { +return off, err +} +`) + } + + if _, ok := st.Field(i).Type().(*types.Slice); ok { + switch st.Tag(i) { + case `dns:"-"`: // ignored + case `dns:"txt"`: + o("off, err = packStringTxt(rr.%s, msg, off)\n") + case `dns:"opt"`: + o("off, err = packDataOpt(rr.%s, msg, off)\n") + case `dns:"nsec"`: + o("off, err = packDataNsec(rr.%s, msg, off)\n") + case `dns:"domain-name"`: + o("off, err = packDataDomainNames(rr.%s, msg, off, compression, compress)\n") + default: + log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) + } + continue + } + + switch { + case st.Tag(i) == `dns:"-"`: // ignored + case st.Tag(i) == `dns:"cdomain-name"`: + fallthrough + case st.Tag(i) == `dns:"domain-name"`: + o("off, err = PackDomainName(rr.%s, msg, off, compression, compress)\n") + case st.Tag(i) == `dns:"a"`: + o("off, err = packDataA(rr.%s, msg, off)\n") + case st.Tag(i) == `dns:"aaaa"`: + o("off, err = packDataAAAA(rr.%s, msg, off)\n") + case st.Tag(i) == `dns:"uint48"`: + o("off, err = packUint48(rr.%s, msg, off)\n") + case st.Tag(i) == `dns:"txt"`: + o("off, err = packString(rr.%s, msg, off)\n") + + case strings.HasPrefix(st.Tag(i), `dns:"size-base32`): // size-base32 can be packed just like base32 + fallthrough + case st.Tag(i) == `dns:"base32"`: + o("off, err = packStringBase32(rr.%s, msg, off)\n") + + case strings.HasPrefix(st.Tag(i), `dns:"size-base64`): // size-base64 can be packed just like base64 + fallthrough + case st.Tag(i) == `dns:"base64"`: + o("off, err = packStringBase64(rr.%s, msg, off)\n") + + case strings.HasPrefix(st.Tag(i), `dns:"size-hex`): // size-hex can be packed just like hex + fallthrough + case st.Tag(i) == `dns:"hex"`: + o("off, err = packStringHex(rr.%s, msg, off)\n") + + case st.Tag(i) == `dns:"octet"`: + o("off, err = packStringOctet(rr.%s, msg, off)\n") + case st.Tag(i) == "": + switch st.Field(i).Type().(*types.Basic).Kind() { + case types.Uint8: + o("off, err = packUint8(rr.%s, msg, off)\n") + case types.Uint16: + o("off, err = packUint16(rr.%s, msg, off)\n") + case types.Uint32: + o("off, err = packUint32(rr.%s, msg, off)\n") + case types.Uint64: + o("off, err = packUint64(rr.%s, msg, off)\n") + case types.String: + o("off, err = packString(rr.%s, msg, off)\n") + default: + log.Fatalln(name, st.Field(i).Name()) + } + default: + log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) + } + } + // We have packed everything, only now we know the rdlength of this RR + fmt.Fprintln(b, "rr.Header().Rdlength = uint16(off- headerEnd)") + fmt.Fprintln(b, "return off, nil }\n") + } + + fmt.Fprint(b, "// unpack*() functions\n\n") + for _, name := range namedTypes { + o := scope.Lookup(name) + st, _ := getTypeStruct(o.Type(), scope) + + fmt.Fprintf(b, "func unpack%s(h RR_Header, msg []byte, off int) (RR, int, error) {\n", name) + fmt.Fprintf(b, "rr := new(%s)\n", name) + fmt.Fprint(b, "rr.Hdr = h\n") + fmt.Fprint(b, `if noRdata(h) { +return rr, off, nil + } +var err error +rdStart := off +_ = rdStart + +`) + for i := 1; i < st.NumFields(); i++ { + o := func(s string) { + fmt.Fprintf(b, s, st.Field(i).Name()) + fmt.Fprint(b, `if err != nil { +return rr, off, err +} +`) + } + + // size-* are special, because they reference a struct member we should use for the length. + if strings.HasPrefix(st.Tag(i), `dns:"size-`) { + structMember := structMember(st.Tag(i)) + structTag := structTag(st.Tag(i)) + switch structTag { + case "hex": + fmt.Fprintf(b, "rr.%s, off, err = unpackStringHex(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) + case "base32": + fmt.Fprintf(b, "rr.%s, off, err = unpackStringBase32(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) + case "base64": + fmt.Fprintf(b, "rr.%s, off, err = unpackStringBase64(msg, off, off + int(rr.%s))\n", st.Field(i).Name(), structMember) + default: + log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) + } + fmt.Fprint(b, `if err != nil { +return rr, off, err +} +`) + continue + } + + if _, ok := st.Field(i).Type().(*types.Slice); ok { + switch st.Tag(i) { + case `dns:"-"`: // ignored + case `dns:"txt"`: + o("rr.%s, off, err = unpackStringTxt(msg, off)\n") + case `dns:"opt"`: + o("rr.%s, off, err = unpackDataOpt(msg, off)\n") + case `dns:"nsec"`: + o("rr.%s, off, err = unpackDataNsec(msg, off)\n") + case `dns:"domain-name"`: + o("rr.%s, off, err = unpackDataDomainNames(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") + default: + log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) + } + continue + } + + switch st.Tag(i) { + case `dns:"-"`: // ignored + case `dns:"cdomain-name"`: + fallthrough + case `dns:"domain-name"`: + o("rr.%s, off, err = UnpackDomainName(msg, off)\n") + case `dns:"a"`: + o("rr.%s, off, err = unpackDataA(msg, off)\n") + case `dns:"aaaa"`: + o("rr.%s, off, err = unpackDataAAAA(msg, off)\n") + case `dns:"uint48"`: + o("rr.%s, off, err = unpackUint48(msg, off)\n") + case `dns:"txt"`: + o("rr.%s, off, err = unpackString(msg, off)\n") + case `dns:"base32"`: + o("rr.%s, off, err = unpackStringBase32(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") + case `dns:"base64"`: + o("rr.%s, off, err = unpackStringBase64(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") + case `dns:"hex"`: + o("rr.%s, off, err = unpackStringHex(msg, off, rdStart + int(rr.Hdr.Rdlength))\n") + case `dns:"octet"`: + o("rr.%s, off, err = unpackStringOctet(msg, off)\n") + case "": + switch st.Field(i).Type().(*types.Basic).Kind() { + case types.Uint8: + o("rr.%s, off, err = unpackUint8(msg, off)\n") + case types.Uint16: + o("rr.%s, off, err = unpackUint16(msg, off)\n") + case types.Uint32: + o("rr.%s, off, err = unpackUint32(msg, off)\n") + case types.Uint64: + o("rr.%s, off, err = unpackUint64(msg, off)\n") + case types.String: + o("rr.%s, off, err = unpackString(msg, off)\n") + default: + log.Fatalln(name, st.Field(i).Name()) + } + default: + log.Fatalln(name, st.Field(i).Name(), st.Tag(i)) + } + // If we've hit len(msg) we return without error. + if i < st.NumFields()-1 { + fmt.Fprintf(b, `if off == len(msg) { +return rr, off, nil + } +`) + } + } + fmt.Fprintf(b, "return rr, off, err }\n\n") + } + // Generate typeToUnpack map + fmt.Fprintln(b, "var typeToUnpack = map[uint16]func(RR_Header, []byte, int) (RR, int, error){") + for _, name := range namedTypes { + if name == "RFC3597" { + continue + } + fmt.Fprintf(b, "Type%s: unpack%s,\n", name, name) + } + fmt.Fprintln(b, "}\n") + + // gofmt + res, err := format.Source(b.Bytes()) + if err != nil { + b.WriteTo(os.Stderr) + log.Fatal(err) + } + + // write result + f, err := os.Create("zmsg.go") + fatalIfErr(err) + defer f.Close() + f.Write(res) +} + +// structMember will take a tag like dns:"size-base32:SaltLength" and return the last part of this string. +func structMember(s string) string { + fields := strings.Split(s, ":") + if len(fields) == 0 { + return "" + } + f := fields[len(fields)-1] + // f should have a closing " + if len(f) > 1 { + return f[:len(f)-1] + } + return f +} + +// structTag will take a tag like dns:"size-base32:SaltLength" and return base32. +func structTag(s string) string { + fields := strings.Split(s, ":") + if len(fields) < 2 { + return "" + } + return fields[1][len("\"size-"):] +} + +func fatalIfErr(err error) { + if err != nil { + log.Fatal(err) + } +} diff --git a/vendor/github.com/miekg/dns/msg_helpers.go b/vendor/github.com/miekg/dns/msg_helpers.go new file mode 100644 index 000000000000..e7a9500cc074 --- /dev/null +++ b/vendor/github.com/miekg/dns/msg_helpers.go @@ -0,0 +1,630 @@ +package dns + +import ( + "encoding/base32" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "net" + "strconv" +) + +// helper functions called from the generated zmsg.go + +// These function are named after the tag to help pack/unpack, if there is no tag it is the name +// of the type they pack/unpack (string, int, etc). We prefix all with unpackData or packData, so packDataA or +// packDataDomainName. + +func unpackDataA(msg []byte, off int) (net.IP, int, error) { + if off+net.IPv4len > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking a"} + } + a := append(make(net.IP, 0, net.IPv4len), msg[off:off+net.IPv4len]...) + off += net.IPv4len + return a, off, nil +} + +func packDataA(a net.IP, msg []byte, off int) (int, error) { + // It must be a slice of 4, even if it is 16, we encode only the first 4 + if off+net.IPv4len > len(msg) { + return len(msg), &Error{err: "overflow packing a"} + } + switch len(a) { + case net.IPv4len, net.IPv6len: + copy(msg[off:], a.To4()) + off += net.IPv4len + case 0: + // Allowed, for dynamic updates. + default: + return len(msg), &Error{err: "overflow packing a"} + } + return off, nil +} + +func unpackDataAAAA(msg []byte, off int) (net.IP, int, error) { + if off+net.IPv6len > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking aaaa"} + } + aaaa := append(make(net.IP, 0, net.IPv6len), msg[off:off+net.IPv6len]...) + off += net.IPv6len + return aaaa, off, nil +} + +func packDataAAAA(aaaa net.IP, msg []byte, off int) (int, error) { + if off+net.IPv6len > len(msg) { + return len(msg), &Error{err: "overflow packing aaaa"} + } + + switch len(aaaa) { + case net.IPv6len: + copy(msg[off:], aaaa) + off += net.IPv6len + case 0: + // Allowed, dynamic updates. + default: + return len(msg), &Error{err: "overflow packing aaaa"} + } + return off, nil +} + +// unpackHeader unpacks an RR header, returning the offset to the end of the header and a +// re-sliced msg according to the expected length of the RR. +func unpackHeader(msg []byte, off int) (rr RR_Header, off1 int, truncmsg []byte, err error) { + hdr := RR_Header{} + if off == len(msg) { + return hdr, off, msg, nil + } + + hdr.Name, off, err = UnpackDomainName(msg, off) + if err != nil { + return hdr, len(msg), msg, err + } + hdr.Rrtype, off, err = unpackUint16(msg, off) + if err != nil { + return hdr, len(msg), msg, err + } + hdr.Class, off, err = unpackUint16(msg, off) + if err != nil { + return hdr, len(msg), msg, err + } + hdr.Ttl, off, err = unpackUint32(msg, off) + if err != nil { + return hdr, len(msg), msg, err + } + hdr.Rdlength, off, err = unpackUint16(msg, off) + if err != nil { + return hdr, len(msg), msg, err + } + msg, err = truncateMsgFromRdlength(msg, off, hdr.Rdlength) + return hdr, off, msg, nil +} + +// pack packs an RR header, returning the offset to the end of the header. +// See PackDomainName for documentation about the compression. +func (hdr RR_Header) pack(msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) { + if off == len(msg) { + return off, nil + } + + off, err = PackDomainName(hdr.Name, msg, off, compression, compress) + if err != nil { + return len(msg), err + } + off, err = packUint16(hdr.Rrtype, msg, off) + if err != nil { + return len(msg), err + } + off, err = packUint16(hdr.Class, msg, off) + if err != nil { + return len(msg), err + } + off, err = packUint32(hdr.Ttl, msg, off) + if err != nil { + return len(msg), err + } + off, err = packUint16(hdr.Rdlength, msg, off) + if err != nil { + return len(msg), err + } + return off, nil +} + +// helper helper functions. + +// truncateMsgFromRdLength truncates msg to match the expected length of the RR. +// Returns an error if msg is smaller than the expected size. +func truncateMsgFromRdlength(msg []byte, off int, rdlength uint16) (truncmsg []byte, err error) { + lenrd := off + int(rdlength) + if lenrd > len(msg) { + return msg, &Error{err: "overflowing header size"} + } + return msg[:lenrd], nil +} + +func fromBase32(s []byte) (buf []byte, err error) { + buflen := base32.HexEncoding.DecodedLen(len(s)) + buf = make([]byte, buflen) + n, err := base32.HexEncoding.Decode(buf, s) + buf = buf[:n] + return +} + +func toBase32(b []byte) string { return base32.HexEncoding.EncodeToString(b) } + +func fromBase64(s []byte) (buf []byte, err error) { + buflen := base64.StdEncoding.DecodedLen(len(s)) + buf = make([]byte, buflen) + n, err := base64.StdEncoding.Decode(buf, s) + buf = buf[:n] + return +} + +func toBase64(b []byte) string { return base64.StdEncoding.EncodeToString(b) } + +// dynamicUpdate returns true if the Rdlength is zero. +func noRdata(h RR_Header) bool { return h.Rdlength == 0 } + +func unpackUint8(msg []byte, off int) (i uint8, off1 int, err error) { + if off+1 > len(msg) { + return 0, len(msg), &Error{err: "overflow unpacking uint8"} + } + return uint8(msg[off]), off + 1, nil +} + +func packUint8(i uint8, msg []byte, off int) (off1 int, err error) { + if off+1 > len(msg) { + return len(msg), &Error{err: "overflow packing uint8"} + } + msg[off] = byte(i) + return off + 1, nil +} + +func unpackUint16(msg []byte, off int) (i uint16, off1 int, err error) { + if off+2 > len(msg) { + return 0, len(msg), &Error{err: "overflow unpacking uint16"} + } + return binary.BigEndian.Uint16(msg[off:]), off + 2, nil +} + +func packUint16(i uint16, msg []byte, off int) (off1 int, err error) { + if off+2 > len(msg) { + return len(msg), &Error{err: "overflow packing uint16"} + } + binary.BigEndian.PutUint16(msg[off:], i) + return off + 2, nil +} + +func unpackUint32(msg []byte, off int) (i uint32, off1 int, err error) { + if off+4 > len(msg) { + return 0, len(msg), &Error{err: "overflow unpacking uint32"} + } + return binary.BigEndian.Uint32(msg[off:]), off + 4, nil +} + +func packUint32(i uint32, msg []byte, off int) (off1 int, err error) { + if off+4 > len(msg) { + return len(msg), &Error{err: "overflow packing uint32"} + } + binary.BigEndian.PutUint32(msg[off:], i) + return off + 4, nil +} + +func unpackUint48(msg []byte, off int) (i uint64, off1 int, err error) { + if off+6 > len(msg) { + return 0, len(msg), &Error{err: "overflow unpacking uint64 as uint48"} + } + // Used in TSIG where the last 48 bits are occupied, so for now, assume a uint48 (6 bytes) + i = (uint64(uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 | + uint64(msg[off+4])<<8 | uint64(msg[off+5]))) + off += 6 + return i, off, nil +} + +func packUint48(i uint64, msg []byte, off int) (off1 int, err error) { + if off+6 > len(msg) { + return len(msg), &Error{err: "overflow packing uint64 as uint48"} + } + msg[off] = byte(i >> 40) + msg[off+1] = byte(i >> 32) + msg[off+2] = byte(i >> 24) + msg[off+3] = byte(i >> 16) + msg[off+4] = byte(i >> 8) + msg[off+5] = byte(i) + off += 6 + return off, nil +} + +func unpackUint64(msg []byte, off int) (i uint64, off1 int, err error) { + if off+8 > len(msg) { + return 0, len(msg), &Error{err: "overflow unpacking uint64"} + } + return binary.BigEndian.Uint64(msg[off:]), off + 8, nil +} + +func packUint64(i uint64, msg []byte, off int) (off1 int, err error) { + if off+8 > len(msg) { + return len(msg), &Error{err: "overflow packing uint64"} + } + binary.BigEndian.PutUint64(msg[off:], i) + off += 8 + return off, nil +} + +func unpackString(msg []byte, off int) (string, int, error) { + if off+1 > len(msg) { + return "", off, &Error{err: "overflow unpacking txt"} + } + l := int(msg[off]) + if off+l+1 > len(msg) { + return "", off, &Error{err: "overflow unpacking txt"} + } + s := make([]byte, 0, l) + for _, b := range msg[off+1 : off+1+l] { + switch b { + case '"', '\\': + s = append(s, '\\', b) + case '\t', '\r', '\n': + s = append(s, b) + default: + if b < 32 || b > 127 { // unprintable + var buf [3]byte + bufs := strconv.AppendInt(buf[:0], int64(b), 10) + s = append(s, '\\') + for i := 0; i < 3-len(bufs); i++ { + s = append(s, '0') + } + for _, r := range bufs { + s = append(s, r) + } + } else { + s = append(s, b) + } + } + } + off += 1 + l + return string(s), off, nil +} + +func packString(s string, msg []byte, off int) (int, error) { + txtTmp := make([]byte, 256*4+1) + off, err := packTxtString(s, msg, off, txtTmp) + if err != nil { + return len(msg), err + } + return off, nil +} + +func unpackStringBase32(msg []byte, off, end int) (string, int, error) { + if end > len(msg) { + return "", len(msg), &Error{err: "overflow unpacking base32"} + } + s := toBase32(msg[off:end]) + return s, end, nil +} + +func packStringBase32(s string, msg []byte, off int) (int, error) { + b32, err := fromBase32([]byte(s)) + if err != nil { + return len(msg), err + } + if off+len(b32) > len(msg) { + return len(msg), &Error{err: "overflow packing base32"} + } + copy(msg[off:off+len(b32)], b32) + off += len(b32) + return off, nil +} + +func unpackStringBase64(msg []byte, off, end int) (string, int, error) { + // Rest of the RR is base64 encoded value, so we don't need an explicit length + // to be set. Thus far all RR's that have base64 encoded fields have those as their + // last one. What we do need is the end of the RR! + if end > len(msg) { + return "", len(msg), &Error{err: "overflow unpacking base64"} + } + s := toBase64(msg[off:end]) + return s, end, nil +} + +func packStringBase64(s string, msg []byte, off int) (int, error) { + b64, err := fromBase64([]byte(s)) + if err != nil { + return len(msg), err + } + if off+len(b64) > len(msg) { + return len(msg), &Error{err: "overflow packing base64"} + } + copy(msg[off:off+len(b64)], b64) + off += len(b64) + return off, nil +} + +func unpackStringHex(msg []byte, off, end int) (string, int, error) { + // Rest of the RR is hex encoded value, so we don't need an explicit length + // to be set. NSEC and TSIG have hex fields with a length field. + // What we do need is the end of the RR! + if end > len(msg) { + return "", len(msg), &Error{err: "overflow unpacking hex"} + } + + s := hex.EncodeToString(msg[off:end]) + return s, end, nil +} + +func packStringHex(s string, msg []byte, off int) (int, error) { + h, err := hex.DecodeString(s) + if err != nil { + return len(msg), err + } + if off+(len(h)) > len(msg) { + return len(msg), &Error{err: "overflow packing hex"} + } + copy(msg[off:off+len(h)], h) + off += len(h) + return off, nil +} + +func unpackStringTxt(msg []byte, off int) ([]string, int, error) { + txt, off, err := unpackTxt(msg, off) + if err != nil { + return nil, len(msg), err + } + return txt, off, nil +} + +func packStringTxt(s []string, msg []byte, off int) (int, error) { + txtTmp := make([]byte, 256*4+1) // If the whole string consists out of \DDD we need this many. + off, err := packTxt(s, msg, off, txtTmp) + if err != nil { + return len(msg), err + } + return off, nil +} + +func unpackDataOpt(msg []byte, off int) ([]EDNS0, int, error) { + var edns []EDNS0 +Option: + code := uint16(0) + if off+4 > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking opt"} + } + code = binary.BigEndian.Uint16(msg[off:]) + off += 2 + optlen := binary.BigEndian.Uint16(msg[off:]) + off += 2 + if off+int(optlen) > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking opt"} + } + switch code { + case EDNS0NSID: + e := new(EDNS0_NSID) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0SUBNET, EDNS0SUBNETDRAFT: + e := new(EDNS0_SUBNET) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + if code == EDNS0SUBNETDRAFT { + e.DraftOption = true + } + case EDNS0COOKIE: + e := new(EDNS0_COOKIE) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0UL: + e := new(EDNS0_UL) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0LLQ: + e := new(EDNS0_LLQ) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0DAU: + e := new(EDNS0_DAU) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0DHU: + e := new(EDNS0_DHU) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + case EDNS0N3U: + e := new(EDNS0_N3U) + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + default: + e := new(EDNS0_LOCAL) + e.Code = code + if err := e.unpack(msg[off : off+int(optlen)]); err != nil { + return nil, len(msg), err + } + edns = append(edns, e) + off += int(optlen) + } + + if off < len(msg) { + goto Option + } + + return edns, off, nil +} + +func packDataOpt(options []EDNS0, msg []byte, off int) (int, error) { + for _, el := range options { + b, err := el.pack() + if err != nil || off+3 > len(msg) { + return len(msg), &Error{err: "overflow packing opt"} + } + binary.BigEndian.PutUint16(msg[off:], el.Option()) // Option code + binary.BigEndian.PutUint16(msg[off+2:], uint16(len(b))) // Length + off += 4 + if off+len(b) > len(msg) { + copy(msg[off:], b) + off = len(msg) + continue + } + // Actual data + copy(msg[off:off+len(b)], b) + off += len(b) + } + return off, nil +} + +func unpackStringOctet(msg []byte, off int) (string, int, error) { + s := string(msg[off:]) + return s, len(msg), nil +} + +func packStringOctet(s string, msg []byte, off int) (int, error) { + txtTmp := make([]byte, 256*4+1) + off, err := packOctetString(s, msg, off, txtTmp) + if err != nil { + return len(msg), err + } + return off, nil +} + +func unpackDataNsec(msg []byte, off int) ([]uint16, int, error) { + var nsec []uint16 + length, window, lastwindow := 0, 0, -1 + for off < len(msg) { + if off+2 > len(msg) { + return nsec, len(msg), &Error{err: "overflow unpacking nsecx"} + } + window = int(msg[off]) + length = int(msg[off+1]) + off += 2 + if window <= lastwindow { + // RFC 4034: Blocks are present in the NSEC RR RDATA in + // increasing numerical order. + return nsec, len(msg), &Error{err: "out of order NSEC block"} + } + if length == 0 { + // RFC 4034: Blocks with no types present MUST NOT be included. + return nsec, len(msg), &Error{err: "empty NSEC block"} + } + if length > 32 { + return nsec, len(msg), &Error{err: "NSEC block too long"} + } + if off+length > len(msg) { + return nsec, len(msg), &Error{err: "overflowing NSEC block"} + } + + // Walk the bytes in the window and extract the type bits + for j := 0; j < length; j++ { + b := msg[off+j] + // Check the bits one by one, and set the type + if b&0x80 == 0x80 { + nsec = append(nsec, uint16(window*256+j*8+0)) + } + if b&0x40 == 0x40 { + nsec = append(nsec, uint16(window*256+j*8+1)) + } + if b&0x20 == 0x20 { + nsec = append(nsec, uint16(window*256+j*8+2)) + } + if b&0x10 == 0x10 { + nsec = append(nsec, uint16(window*256+j*8+3)) + } + if b&0x8 == 0x8 { + nsec = append(nsec, uint16(window*256+j*8+4)) + } + if b&0x4 == 0x4 { + nsec = append(nsec, uint16(window*256+j*8+5)) + } + if b&0x2 == 0x2 { + nsec = append(nsec, uint16(window*256+j*8+6)) + } + if b&0x1 == 0x1 { + nsec = append(nsec, uint16(window*256+j*8+7)) + } + } + off += length + lastwindow = window + } + return nsec, off, nil +} + +func packDataNsec(bitmap []uint16, msg []byte, off int) (int, error) { + if len(bitmap) == 0 { + return off, nil + } + var lastwindow, lastlength uint16 + for j := 0; j < len(bitmap); j++ { + t := bitmap[j] + window := t / 256 + length := (t-window*256)/8 + 1 + if window > lastwindow && lastlength != 0 { // New window, jump to the new offset + off += int(lastlength) + 2 + lastlength = 0 + } + if window < lastwindow || length < lastlength { + return len(msg), &Error{err: "nsec bits out of order"} + } + if off+2+int(length) > len(msg) { + return len(msg), &Error{err: "overflow packing nsec"} + } + // Setting the window # + msg[off] = byte(window) + // Setting the octets length + msg[off+1] = byte(length) + // Setting the bit value for the type in the right octet + msg[off+1+int(length)] |= byte(1 << (7 - (t % 8))) + lastwindow, lastlength = window, length + } + off += int(lastlength) + 2 + return off, nil +} + +func unpackDataDomainNames(msg []byte, off, end int) ([]string, int, error) { + var ( + servers []string + s string + err error + ) + if end > len(msg) { + return nil, len(msg), &Error{err: "overflow unpacking domain names"} + } + for off < end { + s, off, err = UnpackDomainName(msg, off) + if err != nil { + return servers, len(msg), err + } + servers = append(servers, s) + } + return servers, off, nil +} + +func packDataDomainNames(names []string, msg []byte, off int, compression map[string]int, compress bool) (int, error) { + var err error + for j := 0; j < len(names); j++ { + off, err = PackDomainName(names[j], msg, off, compression, false && compress) + if err != nil { + return len(msg), err + } + } + return off, nil +} diff --git a/vendor/github.com/miekg/dns/nsecx.go b/vendor/github.com/miekg/dns/nsecx.go index d2392c6ec60c..6f10f3e65bcc 100644 --- a/vendor/github.com/miekg/dns/nsecx.go +++ b/vendor/github.com/miekg/dns/nsecx.go @@ -11,13 +11,12 @@ type saltWireFmt struct { Salt string `dns:"size-hex"` } -// HashName hashes a string (label) according to RFC 5155. It returns the hashed string in -// uppercase. +// HashName hashes a string (label) according to RFC 5155. It returns the hashed string in uppercase. func HashName(label string, ha uint8, iter uint16, salt string) string { saltwire := new(saltWireFmt) saltwire.Salt = salt wire := make([]byte, DefaultMsgSize) - n, err := PackStruct(saltwire, wire, 0) + n, err := packSaltWire(saltwire, wire) if err != nil { return "" } @@ -110,3 +109,11 @@ func (rr *NSEC3) Match(name string) bool { } return false } + +func packSaltWire(sw *saltWireFmt, msg []byte) (int, error) { + off, err := packStringHex(sw.Salt, msg, 0) + if err != nil { + return off, err + } + return off, nil +} diff --git a/vendor/github.com/miekg/dns/privaterr.go b/vendor/github.com/miekg/dns/privaterr.go index c78f8859120a..6b08e6e9592e 100644 --- a/vendor/github.com/miekg/dns/privaterr.go +++ b/vendor/github.com/miekg/dns/privaterr.go @@ -65,6 +65,20 @@ func (r *PrivateRR) copy() RR { } return rr } +func (r *PrivateRR) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := r.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + n, err := r.Data.Pack(msg[off:]) + if err != nil { + return len(msg), err + } + off += n + r.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} // PrivateHandle registers a private resource record type. It requires // string and numeric representation of private RR type and generator function as argument. @@ -75,19 +89,36 @@ func PrivateHandle(rtypestr string, rtype uint16, generator func() PrivateRdata) TypeToString[rtype] = rtypestr StringToType[rtypestr] = rtype + typeToUnpack[rtype] = func(h RR_Header, msg []byte, off int) (RR, int, error) { + if noRdata(h) { + return &h, off, nil + } + var err error + + rr := mkPrivateRR(h.Rrtype) + rr.Hdr = h + + off1, err := rr.Data.Unpack(msg[off:]) + off += off1 + if err != nil { + return rr, off, err + } + return rr, off, err + } + setPrivateRR := func(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { rr := mkPrivateRR(h.Rrtype) rr.Hdr = h var l lex text := make([]string, 0, 2) // could be 0..N elements, median is probably 1 - FETCH: + Fetch: for { // TODO(miek): we could also be returning _QUOTE, this might or might not // be an issue (basically parsing TXT becomes hard) switch l = <-c; l.value { case zNewline, zEOF: - break FETCH + break Fetch case zString: text = append(text, l.token) } @@ -112,6 +143,7 @@ func PrivateHandleRemove(rtype uint16) { delete(TypeToString, rtype) delete(typeToparserFunc, rtype) delete(StringToType, rtypestr) + delete(typeToUnpack, rtype) } return } diff --git a/vendor/github.com/miekg/dns/rawmsg.go b/vendor/github.com/miekg/dns/rawmsg.go index b4a706b93887..6e21fba7e1fb 100644 --- a/vendor/github.com/miekg/dns/rawmsg.go +++ b/vendor/github.com/miekg/dns/rawmsg.go @@ -1,52 +1,6 @@ package dns -// These raw* functions do not use reflection, they directly set the values -// in the buffer. There are faster than their reflection counterparts. - -// RawSetId sets the message id in buf. -func rawSetId(msg []byte, i uint16) bool { - if len(msg) < 2 { - return false - } - msg[0], msg[1] = packUint16(i) - return true -} - -// rawSetQuestionLen sets the length of the question section. -func rawSetQuestionLen(msg []byte, i uint16) bool { - if len(msg) < 6 { - return false - } - msg[4], msg[5] = packUint16(i) - return true -} - -// rawSetAnswerLen sets the length of the answer section. -func rawSetAnswerLen(msg []byte, i uint16) bool { - if len(msg) < 8 { - return false - } - msg[6], msg[7] = packUint16(i) - return true -} - -// rawSetsNsLen sets the length of the authority section. -func rawSetNsLen(msg []byte, i uint16) bool { - if len(msg) < 10 { - return false - } - msg[8], msg[9] = packUint16(i) - return true -} - -// rawSetExtraLen sets the length of the additional section. -func rawSetExtraLen(msg []byte, i uint16) bool { - if len(msg) < 12 { - return false - } - msg[10], msg[11] = packUint16(i) - return true -} +import "encoding/binary" // rawSetRdlength sets the rdlength in the header of // the RR. The offset 'off' must be positioned at the @@ -90,6 +44,6 @@ Loop: if rdatalen > 0xFFFF { return false } - msg[off], msg[off+1] = packUint16(uint16(rdatalen)) + binary.BigEndian.PutUint16(msg[off:], uint16(rdatalen)) return true } diff --git a/vendor/github.com/miekg/dns/reverse.go b/vendor/github.com/miekg/dns/reverse.go new file mode 100644 index 000000000000..099dac9486d5 --- /dev/null +++ b/vendor/github.com/miekg/dns/reverse.go @@ -0,0 +1,38 @@ +package dns + +// StringToType is the reverse of TypeToString, needed for string parsing. +var StringToType = reverseInt16(TypeToString) + +// StringToClass is the reverse of ClassToString, needed for string parsing. +var StringToClass = reverseInt16(ClassToString) + +// Map of opcodes strings. +var StringToOpcode = reverseInt(OpcodeToString) + +// Map of rcodes strings. +var StringToRcode = reverseInt(RcodeToString) + +// Reverse a map +func reverseInt8(m map[uint8]string) map[string]uint8 { + n := make(map[string]uint8, len(m)) + for u, s := range m { + n[s] = u + } + return n +} + +func reverseInt16(m map[uint16]string) map[string]uint16 { + n := make(map[string]uint16, len(m)) + for u, s := range m { + n[s] = u + } + return n +} + +func reverseInt(m map[int]string) map[string]int { + n := make(map[string]int, len(m)) + for u, s := range m { + n[s] = u + } + return n +} diff --git a/vendor/github.com/miekg/dns/zscan.go b/vendor/github.com/miekg/dns/scan.go similarity index 99% rename from vendor/github.com/miekg/dns/zscan.go rename to vendor/github.com/miekg/dns/scan.go index 5c10fbaaaaf8..0e83797fb597 100644 --- a/vendor/github.com/miekg/dns/zscan.go +++ b/vendor/github.com/miekg/dns/scan.go @@ -377,8 +377,8 @@ func parseZone(r io.Reader, origin, f string, t chan *Token, include int) { t <- &Token{Error: &ParseError{f, "expecting $GENERATE value, not this...", l}} return } - if e := generate(l, c, t, origin); e != "" { - t <- &Token{Error: &ParseError{f, e, l}} + if errMsg := generate(l, c, t, origin); errMsg != "" { + t <- &Token{Error: &ParseError{f, errMsg, l}} return } st = zExpectOwnerDir @@ -966,8 +966,8 @@ func stringToNodeID(l lex) (uint64, *ParseError) { return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l} } s := l.token[0:4] + l.token[5:9] + l.token[10:14] + l.token[15:19] - u, e := strconv.ParseUint(s, 16, 64) - if e != nil { + u, err := strconv.ParseUint(s, 16, 64) + if err != nil { return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l} } return u, nil diff --git a/vendor/github.com/miekg/dns/zscan_rr.go b/vendor/github.com/miekg/dns/scan_rr.go similarity index 94% rename from vendor/github.com/miekg/dns/zscan_rr.go rename to vendor/github.com/miekg/dns/scan_rr.go index ead9614d13b4..e521dc063e95 100644 --- a/vendor/github.com/miekg/dns/zscan_rr.go +++ b/vendor/github.com/miekg/dns/scan_rr.go @@ -1443,64 +1443,6 @@ func setEUI64(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { return rr, nil, "" } -func setWKS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { - rr := new(WKS) - rr.Hdr = h - - l := <-c - if l.length == 0 { - return rr, nil, l.comment - } - rr.Address = net.ParseIP(l.token) - if rr.Address == nil || l.err { - return nil, &ParseError{f, "bad WKS Address", l}, "" - } - - <-c // zBlank - l = <-c - proto := "tcp" - i, e := strconv.Atoi(l.token) - if e != nil || l.err { - return nil, &ParseError{f, "bad WKS Protocol", l}, "" - } - rr.Protocol = uint8(i) - switch rr.Protocol { - case 17: - proto = "udp" - case 6: - proto = "tcp" - default: - return nil, &ParseError{f, "bad WKS Protocol", l}, "" - } - - <-c - l = <-c - rr.BitMap = make([]uint16, 0) - var ( - k int - err error - ) - for l.value != zNewline && l.value != zEOF { - switch l.value { - case zBlank: - // Ok - case zString: - if k, err = net.LookupPort(proto, l.token); err != nil { - i, e := strconv.Atoi(l.token) // If a number use that - if e != nil { - return nil, &ParseError{f, "bad WKS BitMap", l}, "" - } - rr.BitMap = append(rr.BitMap, uint16(i)) - } - rr.BitMap = append(rr.BitMap, uint16(k)) - default: - return nil, &ParseError{f, "bad WKS BitMap", l}, "" - } - l = <-c - } - return rr, nil, l.comment -} - func setSSHFP(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { rr := new(SSHFP) rr.Hdr = h @@ -2103,73 +2045,6 @@ func setPX(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { return rr, nil, "" } -func setIPSECKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { - rr := new(IPSECKEY) - rr.Hdr = h - l := <-c - if l.length == 0 { - return rr, nil, l.comment - } - i, err := strconv.Atoi(l.token) - if err != nil || l.err { - return nil, &ParseError{f, "bad IPSECKEY Precedence", l}, "" - } - rr.Precedence = uint8(i) - <-c // zBlank - l = <-c - i, err = strconv.Atoi(l.token) - if err != nil || l.err { - return nil, &ParseError{f, "bad IPSECKEY GatewayType", l}, "" - } - rr.GatewayType = uint8(i) - <-c // zBlank - l = <-c - i, err = strconv.Atoi(l.token) - if err != nil || l.err { - return nil, &ParseError{f, "bad IPSECKEY Algorithm", l}, "" - } - rr.Algorithm = uint8(i) - - // Now according to GatewayType we can have different elements here - <-c // zBlank - l = <-c - switch rr.GatewayType { - case 0: - fallthrough - case 3: - rr.GatewayName = l.token - if l.token == "@" { - rr.GatewayName = o - } - _, ok := IsDomainName(l.token) - if !ok || l.length == 0 || l.err { - return nil, &ParseError{f, "bad IPSECKEY GatewayName", l}, "" - } - if rr.GatewayName[l.length-1] != '.' { - rr.GatewayName = appendOrigin(rr.GatewayName, o) - } - case 1: - rr.GatewayA = net.ParseIP(l.token) - if rr.GatewayA == nil { - return nil, &ParseError{f, "bad IPSECKEY GatewayA", l}, "" - } - case 2: - rr.GatewayAAAA = net.ParseIP(l.token) - if rr.GatewayAAAA == nil { - return nil, &ParseError{f, "bad IPSECKEY GatewayAAAA", l}, "" - } - default: - return nil, &ParseError{f, "bad IPSECKEY GatewayType", l}, "" - } - - s, e, c1 := endingToString(c, "bad IPSECKEY PublicKey", f) - if e != nil { - return nil, e, c1 - } - rr.PublicKey = s - return rr, nil, c1 -} - func setCAA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { rr := new(CAA) rr.Hdr = h @@ -2224,7 +2099,6 @@ var typeToparserFunc = map[uint16]parserFunc{ TypeGPOS: {setGPOS, false}, TypeHINFO: {setHINFO, true}, TypeHIP: {setHIP, true}, - TypeIPSECKEY: {setIPSECKEY, true}, TypeKX: {setKX, false}, TypeL32: {setL32, false}, TypeL64: {setL64, false}, @@ -2265,6 +2139,5 @@ var typeToparserFunc = map[uint16]parserFunc{ TypeUID: {setUID, false}, TypeUINFO: {setUINFO, true}, TypeURI: {setURI, true}, - TypeWKS: {setWKS, true}, TypeX25: {setX25, false}, } diff --git a/vendor/github.com/miekg/dns/server.go b/vendor/github.com/miekg/dns/server.go index edc5c6258c9c..2b4bff49f27b 100644 --- a/vendor/github.com/miekg/dns/server.go +++ b/vendor/github.com/miekg/dns/server.go @@ -5,6 +5,7 @@ package dns import ( "bytes" "crypto/tls" + "encoding/binary" "io" "net" "sync" @@ -320,20 +321,20 @@ func (srv *Server) ListenAndServe() error { } switch srv.Net { case "tcp", "tcp4", "tcp6": - a, e := net.ResolveTCPAddr(srv.Net, addr) - if e != nil { - return e + a, err := net.ResolveTCPAddr(srv.Net, addr) + if err != nil { + return err } - l, e := net.ListenTCP(srv.Net, a) - if e != nil { - return e + l, err := net.ListenTCP(srv.Net, a) + if err != nil { + return err } srv.Listener = l srv.started = true srv.lock.Unlock() - e = srv.serveTCP(l) + err = srv.serveTCP(l) srv.lock.Lock() // to satisfy the defer at the top - return e + return err case "tcp-tls", "tcp4-tls", "tcp6-tls": network := "tcp" if srv.Net == "tcp4-tls" { @@ -342,24 +343,24 @@ func (srv *Server) ListenAndServe() error { network = "tcp6" } - l, e := tls.Listen(network, addr, srv.TLSConfig) - if e != nil { - return e + l, err := tls.Listen(network, addr, srv.TLSConfig) + if err != nil { + return err } srv.Listener = l srv.started = true srv.lock.Unlock() - e = srv.serveTCP(l) + err = srv.serveTCP(l) srv.lock.Lock() // to satisfy the defer at the top - return e + return err case "udp", "udp4", "udp6": - a, e := net.ResolveUDPAddr(srv.Net, addr) - if e != nil { - return e + a, err := net.ResolveUDPAddr(srv.Net, addr) + if err != nil { + return err } - l, e := net.ListenUDP(srv.Net, a) - if e != nil { - return e + l, err := net.ListenUDP(srv.Net, a) + if err != nil { + return err } if e := setUDPSocketOptions(l); e != nil { return e @@ -367,9 +368,9 @@ func (srv *Server) ListenAndServe() error { srv.PacketConn = l srv.started = true srv.lock.Unlock() - e = srv.serveUDP(l) + err = srv.serveUDP(l) srv.lock.Lock() // to satisfy the defer at the top - return e + return err } return &Error{err: "bad network"} } @@ -473,21 +474,21 @@ func (srv *Server) serveTCP(l net.Listener) error { rtimeout := srv.getReadTimeout() // deadline is not used here for { - rw, e := l.Accept() - if e != nil { - if neterr, ok := e.(net.Error); ok && neterr.Temporary() { + rw, err := l.Accept() + if err != nil { + if neterr, ok := err.(net.Error); ok && neterr.Temporary() { continue } - return e + return err } - m, e := reader.ReadTCP(rw, rtimeout) + m, err := reader.ReadTCP(rw, rtimeout) srv.lock.RLock() if !srv.started { srv.lock.RUnlock() return nil } srv.lock.RUnlock() - if e != nil { + if err != nil { continue } srv.inFlight.Add(1) @@ -516,14 +517,14 @@ func (srv *Server) serveUDP(l *net.UDPConn) error { rtimeout := srv.getReadTimeout() // deadline is not used here for { - m, s, e := reader.ReadUDP(l, rtimeout) + m, s, err := reader.ReadUDP(l, rtimeout) srv.lock.RLock() if !srv.started { srv.lock.RUnlock() return nil } srv.lock.RUnlock() - if e != nil { + if err != nil { continue } srv.inFlight.Add(1) @@ -596,8 +597,8 @@ Exit: if srv.IdleTimeout != nil { idleTimeout = srv.IdleTimeout() } - m, e := reader.ReadTCP(w.tcp, idleTimeout) - if e == nil { + m, err = reader.ReadTCP(w.tcp, idleTimeout) + if err == nil { q++ goto Redo } @@ -615,7 +616,7 @@ func (srv *Server) readTCP(conn net.Conn, timeout time.Duration) ([]byte, error) } return nil, ErrShortRead } - length, _ := unpackUint16(l, 0) + length := binary.BigEndian.Uint16(l) if length == 0 { return nil, ErrShortRead } @@ -643,10 +644,10 @@ func (srv *Server) readTCP(conn net.Conn, timeout time.Duration) ([]byte, error) func (srv *Server) readUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) { conn.SetReadDeadline(time.Now().Add(timeout)) m := make([]byte, srv.UDPSize) - n, s, e := ReadFromSessionUDP(conn, m) - if e != nil || n == 0 { - if e != nil { - return nil, nil, e + n, s, err := ReadFromSessionUDP(conn, m) + if err != nil || n == 0 { + if err != nil { + return nil, nil, err } return nil, nil, ErrShortRead } @@ -690,7 +691,7 @@ func (w *response) Write(m []byte) (int, error) { return 0, &Error{err: "message too large"} } l := make([]byte, 2, 2+lm) - l[0], l[1] = packUint16(uint16(lm)) + binary.BigEndian.PutUint16(l, uint16(lm)) m = append(l, m...) n, err := io.Copy(w.tcp, bytes.NewReader(m)) diff --git a/vendor/github.com/miekg/dns/sig0.go b/vendor/github.com/miekg/dns/sig0.go index 0fccddbc150a..2dce06af82f6 100644 --- a/vendor/github.com/miekg/dns/sig0.go +++ b/vendor/github.com/miekg/dns/sig0.go @@ -5,6 +5,7 @@ import ( "crypto/dsa" "crypto/ecdsa" "crypto/rsa" + "encoding/binary" "math/big" "strings" "time" @@ -67,13 +68,13 @@ func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error) { } // Adjust sig data length rdoff := len(mbuf) + 1 + 2 + 2 + 4 - rdlen, _ := unpackUint16(buf, rdoff) + rdlen := binary.BigEndian.Uint16(buf[rdoff:]) rdlen += uint16(len(sig)) - buf[rdoff], buf[rdoff+1] = packUint16(rdlen) + binary.BigEndian.PutUint16(buf[rdoff:], rdlen) // Adjust additional count - adc, _ := unpackUint16(buf, 10) + adc := binary.BigEndian.Uint16(buf[10:]) adc++ - buf[10], buf[11] = packUint16(adc) + binary.BigEndian.PutUint16(buf[10:], adc) return buf, nil } @@ -103,10 +104,11 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error { hasher := hash.New() buflen := len(buf) - qdc, _ := unpackUint16(buf, 4) - anc, _ := unpackUint16(buf, 6) - auc, _ := unpackUint16(buf, 8) - adc, offset := unpackUint16(buf, 10) + qdc := binary.BigEndian.Uint16(buf[4:]) + anc := binary.BigEndian.Uint16(buf[6:]) + auc := binary.BigEndian.Uint16(buf[8:]) + adc := binary.BigEndian.Uint16(buf[10:]) + offset := 12 var err error for i := uint16(0); i < qdc && offset < buflen; i++ { _, offset, err = UnpackDomainName(buf, offset) @@ -127,7 +129,8 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error { continue } var rdlen uint16 - rdlen, offset = unpackUint16(buf, offset) + rdlen = binary.BigEndian.Uint16(buf[offset:]) + offset += 2 offset += int(rdlen) } if offset >= buflen { @@ -149,9 +152,9 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error { if offset+4+4 >= buflen { return &Error{err: "overflow unpacking signed message"} } - expire := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3]) + expire := binary.BigEndian.Uint32(buf[offset:]) offset += 4 - incept := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3]) + incept := binary.BigEndian.Uint32(buf[offset:]) offset += 4 now := uint32(time.Now().Unix()) if now < incept || now > expire { diff --git a/vendor/github.com/miekg/dns/tlsa.go b/vendor/github.com/miekg/dns/tlsa.go index 0a550dc6cbfc..34fe6615aa2f 100644 --- a/vendor/github.com/miekg/dns/tlsa.go +++ b/vendor/github.com/miekg/dns/tlsa.go @@ -78,9 +78,9 @@ func TLSAName(name, service, network string) (string, error) { if !IsFqdn(name) { return "", ErrFqdn } - p, e := net.LookupPort(network, service) - if e != nil { - return "", e + p, err := net.LookupPort(network, service) + if err != nil { + return "", err } return "_" + strconv.Itoa(p) + "._" + network + "." + name, nil } diff --git a/vendor/github.com/miekg/dns/tsig.go b/vendor/github.com/miekg/dns/tsig.go index c3374e19407a..78365e1c5bac 100644 --- a/vendor/github.com/miekg/dns/tsig.go +++ b/vendor/github.com/miekg/dns/tsig.go @@ -6,6 +6,7 @@ import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" + "encoding/binary" "encoding/hex" "hash" "io" @@ -30,11 +31,11 @@ type TSIG struct { TimeSigned uint64 `dns:"uint48"` Fudge uint16 MACSize uint16 - MAC string `dns:"size-hex"` + MAC string `dns:"size-hex:MACSize"` OrigId uint16 Error uint16 OtherLen uint16 - OtherData string `dns:"size-hex"` + OtherData string `dns:"size-hex:OtherLen"` } // TSIG has no official presentation format, but this will suffice. @@ -68,14 +69,13 @@ type tsigWireFmt struct { // MACSize, MAC and OrigId excluded Error uint16 OtherLen uint16 - OtherData string `dns:"size-hex"` + OtherData string `dns:"size-hex:OtherLen"` } -// If we have the MAC use this type to convert it to wiredata. -// Section 3.4.3. Request MAC +// If we have the MAC use this type to convert it to wiredata. Section 3.4.3. Request MAC type macWireFmt struct { MACSize uint16 - MAC string `dns:"size-hex"` + MAC string `dns:"size-hex:MACSize"` } // 3.3. Time values used in TSIG calculations @@ -141,7 +141,9 @@ func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, s return nil, "", err } mbuf = append(mbuf, tbuf...) - rawSetExtraLen(mbuf, uint16(len(m.Extra)+1)) + // Update the ArCount directly in the buffer. + binary.BigEndian.PutUint16(mbuf[10:], uint16(len(m.Extra)+1)) + return mbuf, t.MAC, nil } @@ -212,7 +214,7 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b m.MACSize = uint16(len(requestMAC) / 2) m.MAC = requestMAC buf = make([]byte, len(requestMAC)) // long enough - n, _ := PackStruct(m, buf, 0) + n, _ := packMacWire(m, buf) buf = buf[:n] } @@ -221,7 +223,7 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b tsig := new(timerWireFmt) tsig.TimeSigned = rr.TimeSigned tsig.Fudge = rr.Fudge - n, _ := PackStruct(tsig, tsigvar, 0) + n, _ := packTimerWire(tsig, tsigvar) tsigvar = tsigvar[:n] } else { tsig := new(tsigWireFmt) @@ -234,7 +236,7 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b tsig.Error = rr.Error tsig.OtherLen = rr.OtherLen tsig.OtherData = rr.OtherData - n, _ := PackStruct(tsig, tsigvar, 0) + n, _ := packTsigWire(tsig, tsigvar) tsigvar = tsigvar[:n] } @@ -249,60 +251,54 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b // Strip the TSIG from the raw message. func stripTsig(msg []byte) ([]byte, *TSIG, error) { - // Copied from msg.go's Unpack() - // Header. - var dh Header - var err error - dns := new(Msg) - rr := new(TSIG) - off := 0 - tsigoff := 0 - if off, err = UnpackStruct(&dh, msg, off); err != nil { + // Copied from msg.go's Unpack() Header, but modified. + var ( + dh Header + err error + ) + off, tsigoff := 0, 0 + + if dh, off, err = unpackMsgHdr(msg, off); err != nil { return nil, nil, err } if dh.Arcount == 0 { return nil, nil, ErrNoSig } + // Rcode, see msg.go Unpack() if int(dh.Bits&0xF) == RcodeNotAuth { return nil, nil, ErrAuth } - // Arrays. - dns.Question = make([]Question, dh.Qdcount) - dns.Answer = make([]RR, dh.Ancount) - dns.Ns = make([]RR, dh.Nscount) - dns.Extra = make([]RR, dh.Arcount) - - for i := 0; i < len(dns.Question); i++ { - off, err = UnpackStruct(&dns.Question[i], msg, off) + for i := 0; i < int(dh.Qdcount); i++ { + _, off, err = unpackQuestion(msg, off) if err != nil { return nil, nil, err } } - for i := 0; i < len(dns.Answer); i++ { - dns.Answer[i], off, err = UnpackRR(msg, off) - if err != nil { - return nil, nil, err - } + + _, off, err = unpackRRslice(int(dh.Ancount), msg, off) + if err != nil { + return nil, nil, err } - for i := 0; i < len(dns.Ns); i++ { - dns.Ns[i], off, err = UnpackRR(msg, off) - if err != nil { - return nil, nil, err - } + _, off, err = unpackRRslice(int(dh.Nscount), msg, off) + if err != nil { + return nil, nil, err } - for i := 0; i < len(dns.Extra); i++ { + + rr := new(TSIG) + var extra RR + for i := 0; i < int(dh.Arcount); i++ { tsigoff = off - dns.Extra[i], off, err = UnpackRR(msg, off) + extra, off, err = UnpackRR(msg, off) if err != nil { return nil, nil, err } - if dns.Extra[i].Header().Rrtype == TypeTSIG { - rr = dns.Extra[i].(*TSIG) + if extra.Header().Rrtype == TypeTSIG { + rr = extra.(*TSIG) // Adjust Arcount. - arcount, _ := unpackUint16(msg, 10) - msg[10], msg[11] = packUint16(arcount - 1) + arcount := binary.BigEndian.Uint16(msg[10:]) + binary.BigEndian.PutUint16(msg[10:], arcount-1) break } } @@ -318,3 +314,71 @@ func tsigTimeToString(t uint64) string { ti := time.Unix(int64(t), 0).UTC() return ti.Format("20060102150405") } + +func packTsigWire(tw *tsigWireFmt, msg []byte) (int, error) { + // copied from zmsg.go TSIG packing + // RR_Header + off, err := PackDomainName(tw.Name, msg, 0, nil, false) + if err != nil { + return off, err + } + off, err = packUint16(tw.Class, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(tw.Ttl, msg, off) + if err != nil { + return off, err + } + + off, err = PackDomainName(tw.Algorithm, msg, off, nil, false) + if err != nil { + return off, err + } + off, err = packUint48(tw.TimeSigned, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(tw.Fudge, msg, off) + if err != nil { + return off, err + } + + off, err = packUint16(tw.Error, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(tw.OtherLen, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(tw.OtherData, msg, off) + if err != nil { + return off, err + } + return off, nil +} + +func packMacWire(mw *macWireFmt, msg []byte) (int, error) { + off, err := packUint16(mw.MACSize, msg, 0) + if err != nil { + return off, err + } + off, err = packStringHex(mw.MAC, msg, off) + if err != nil { + return off, err + } + return off, nil +} + +func packTimerWire(tw *timerWireFmt, msg []byte) (int, error) { + off, err := packUint48(tw.TimeSigned, msg, 0) + if err != nil { + return off, err + } + off, err = packUint16(tw.Fudge, msg, off) + if err != nil { + return off, err + } + return off, nil +} diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go index 64143dba511c..e7370647900a 100644 --- a/vendor/github.com/miekg/dns/types.go +++ b/vendor/github.com/miekg/dns/types.go @@ -1,7 +1,6 @@ package dns import ( - "encoding/base64" "fmt" "net" "strconv" @@ -35,7 +34,6 @@ const ( TypeMG uint16 = 8 TypeMR uint16 = 9 TypeNULL uint16 = 10 - TypeWKS uint16 = 11 TypePTR uint16 = 12 TypeHINFO uint16 = 13 TypeMINFO uint16 = 14 @@ -65,7 +63,6 @@ const ( TypeOPT uint16 = 41 // EDNS TypeDS uint16 = 43 TypeSSHFP uint16 = 44 - TypeIPSECKEY uint16 = 45 TypeRRSIG uint16 = 46 TypeNSEC uint16 = 47 TypeDNSKEY uint16 = 48 @@ -136,6 +133,7 @@ const ( RcodeBadName = 20 RcodeBadAlg = 21 RcodeBadTrunc = 22 // TSIG + RcodeBadCookie = 23 // DNS Cookies // Message Opcodes. There is no 3. OpcodeQuery = 0 @@ -871,57 +869,6 @@ func (rr *SSHFP) String() string { " " + strings.ToUpper(rr.FingerPrint) } -type IPSECKEY struct { - Hdr RR_Header - Precedence uint8 - // GatewayType: 1: A record, 2: AAAA record, 3: domainname. - // 0 is use for no type and GatewayName should be "." then. - GatewayType uint8 - Algorithm uint8 - // Gateway can be an A record, AAAA record or a domain name. - GatewayA net.IP `dns:"a"` - GatewayAAAA net.IP `dns:"aaaa"` - GatewayName string `dns:"domain-name"` - PublicKey string `dns:"base64"` -} - -func (rr *IPSECKEY) String() string { - s := rr.Hdr.String() + strconv.Itoa(int(rr.Precedence)) + - " " + strconv.Itoa(int(rr.GatewayType)) + - " " + strconv.Itoa(int(rr.Algorithm)) - switch rr.GatewayType { - case 0: - fallthrough - case 3: - s += " " + rr.GatewayName - case 1: - s += " " + rr.GatewayA.String() - case 2: - s += " " + rr.GatewayAAAA.String() - default: - s += " ." - } - s += " " + rr.PublicKey - return s -} - -func (rr *IPSECKEY) len() int { - l := rr.Hdr.len() + 3 + 1 - switch rr.GatewayType { - default: - fallthrough - case 0: - fallthrough - case 3: - l += len(rr.GatewayName) - case 1: - l += 4 - case 2: - l += 16 - } - return l + base64.StdEncoding.DecodedLen(len(rr.PublicKey)) -} - type KEY struct { DNSKEY } @@ -973,9 +920,9 @@ type NSEC3 struct { Flags uint8 Iterations uint16 SaltLength uint8 - Salt string `dns:"size-hex"` + Salt string `dns:"size-hex:SaltLength"` HashLength uint8 - NextDomain string `dns:"size-base32"` + NextDomain string `dns:"size-base32:HashLength"` TypeBitMap []uint16 `dns:"nsec"` } @@ -1105,8 +1052,8 @@ type HIP struct { HitLength uint8 PublicKeyAlgorithm uint8 PublicKeyLength uint16 - Hit string `dns:"hex"` - PublicKey string `dns:"base64"` + Hit string `dns:"size-hex:HitLength"` + PublicKey string `dns:"size-base64:PublicKeyLength"` RendezvousServers []string `dns:"domain-name"` } @@ -1128,31 +1075,6 @@ type NINFO struct { func (rr *NINFO) String() string { return rr.Hdr.String() + sprintTxt(rr.ZSData) } -type WKS struct { - Hdr RR_Header - Address net.IP `dns:"a"` - Protocol uint8 - BitMap []uint16 `dns:"wks"` -} - -func (rr *WKS) len() int { - // TODO: this is missing something... - return rr.Hdr.len() + net.IPv4len + 1 -} - -func (rr *WKS) String() (s string) { - s = rr.Hdr.String() - if rr.Address != nil { - s += rr.Address.String() - } - // TODO(miek): missing protocol here, see /etc/protocols - for i := 0; i < len(rr.BitMap); i++ { - // should lookup the port - s += " " + strconv.Itoa(int(rr.BitMap[i])) - } - return s -} - type NID struct { Hdr RR_Header Preference uint16 @@ -1286,9 +1208,9 @@ func TimeToString(t uint32) string { // string values like "20110403154150" to an 32 bit integer. // It takes serial arithmetic (RFC 1982) into account. func StringToTime(s string) (uint32, error) { - t, e := time.Parse("20060102150405", s) - if e != nil { - return 0, e + t, err := time.Parse("20060102150405", s) + if err != nil { + return 0, err } mod := (t.Unix() / year68) - 1 if mod < 0 { diff --git a/vendor/github.com/miekg/dns/types_generate.go b/vendor/github.com/miekg/dns/types_generate.go index b8d1cd26b0cc..bf80da329c31 100644 --- a/vendor/github.com/miekg/dns/types_generate.go +++ b/vendor/github.com/miekg/dns/types_generate.go @@ -20,16 +20,14 @@ import ( ) var skipLen = map[string]struct{}{ - "NSEC": {}, - "NSEC3": {}, - "OPT": {}, - "WKS": {}, - "IPSECKEY": {}, + "NSEC": {}, + "NSEC3": {}, + "OPT": {}, } var packageHdr = ` // *** DO NOT MODIFY *** -// AUTOGENERATED BY go generate +// AUTOGENERATED BY go generate from type_generate.go package dns @@ -173,26 +171,30 @@ func main() { continue } - switch st.Tag(i) { - case `dns:"-"`: + switch { + case st.Tag(i) == `dns:"-"`: // ignored - case `dns:"cdomain-name"`, `dns:"domain-name"`: + case st.Tag(i) == `dns:"cdomain-name"`, st.Tag(i) == `dns:"domain-name"`: o("l += len(rr.%s) + 1\n") - case `dns:"octet"`: + case st.Tag(i) == `dns:"octet"`: o("l += len(rr.%s)\n") - case `dns:"base64"`: + case strings.HasPrefix(st.Tag(i), `dns:"size-base64`): + fallthrough + case st.Tag(i) == `dns:"base64"`: o("l += base64.StdEncoding.DecodedLen(len(rr.%s))\n") - case `dns:"size-hex"`, `dns:"hex"`: + case strings.HasPrefix(st.Tag(i), `dns:"size-hex`): + fallthrough + case st.Tag(i) == `dns:"hex"`: o("l += len(rr.%s)/2 + 1\n") - case `dns:"a"`: + case st.Tag(i) == `dns:"a"`: o("l += net.IPv4len // %s\n") - case `dns:"aaaa"`: + case st.Tag(i) == `dns:"aaaa"`: o("l += net.IPv6len // %s\n") - case `dns:"txt"`: + case st.Tag(i) == `dns:"txt"`: o("for _, t := range rr.%s { l += len(t) + 1 }\n") - case `dns:"uint48"`: + case st.Tag(i) == `dns:"uint48"`: o("l += 6 // %s\n") - case "": + case st.Tag(i) == "": switch st.Field(i).Type().(*types.Basic).Kind() { case types.Uint8: o("l += 1 // %s\n") @@ -229,7 +231,10 @@ func main() { if sl, ok := st.Field(i).Type().(*types.Slice); ok { t := sl.Underlying().String() t = strings.TrimPrefix(t, "[]") - t = strings.TrimPrefix(t, "github.com/miekg/dns.") + if strings.Contains(t, ".") { + splits := strings.Split(t, ".") + t = splits[len(splits)-1] + } fmt.Fprintf(b, "%s := make([]%s, len(rr.%s)); copy(%s, rr.%s)\n", f, t, f, f, f) fields = append(fields, f) diff --git a/vendor/github.com/miekg/dns/xfr.go b/vendor/github.com/miekg/dns/xfr.go index 7d3a67b8e451..7346deffbb73 100644 --- a/vendor/github.com/miekg/dns/xfr.go +++ b/vendor/github.com/miekg/dns/xfr.go @@ -162,8 +162,8 @@ func (t *Transfer) inIxfr(id uint16, c chan *Envelope) { // // ch := make(chan *dns.Envelope) // tr := new(dns.Transfer) -// tr.Out(w, r, ch) -// c <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}} +// go tr.Out(w, r, ch) +// ch <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}} // close(ch) // w.Hijack() // // w.Close() // Client closes connection diff --git a/vendor/github.com/miekg/dns/zmsg.go b/vendor/github.com/miekg/dns/zmsg.go new file mode 100644 index 000000000000..e5f3cf2974c4 --- /dev/null +++ b/vendor/github.com/miekg/dns/zmsg.go @@ -0,0 +1,3462 @@ +// *** DO NOT MODIFY *** +// AUTOGENERATED BY go generate from msg_generate.go + +package dns + +// pack*() functions + +func (rr *A) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packDataA(rr.A, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *AAAA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packDataAAAA(rr.AAAA, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *AFSDB) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Subtype, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Hostname, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *ANY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *CAA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Flag, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Tag, msg, off) + if err != nil { + return off, err + } + off, err = packStringOctet(rr.Value, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *CDNSKEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Protocol, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *CDS) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.DigestType, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Digest, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *CERT) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Type, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.Certificate, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *CNAME) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Target, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *DHCID) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringBase64(rr.Digest, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *DLV) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.DigestType, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Digest, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *DNAME) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Target, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *DNSKEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Protocol, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *DS) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.DigestType, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Digest, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *EID) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringHex(rr.Endpoint, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *EUI48) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint48(rr.Address, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *EUI64) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint64(rr.Address, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *GID) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint32(rr.Gid, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *GPOS) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packString(rr.Longitude, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Latitude, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Altitude, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *HINFO) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packString(rr.Cpu, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Os, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *HIP) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.HitLength, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.PublicKeyAlgorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.PublicKeyLength, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Hit, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + off, err = packDataDomainNames(rr.RendezvousServers, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *KEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Protocol, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *KX) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Exchanger, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *L32) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = packDataA(rr.Locator32, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *L64) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = packUint64(rr.Locator64, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *LOC) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Version, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Size, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.HorizPre, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.VertPre, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Latitude, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Longitude, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Altitude, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *LP) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Fqdn, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MB) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Mb, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MD) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Md, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MF) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Mf, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MG) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Mg, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MINFO) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Rmail, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Email, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MR) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Mr, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *MX) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Mx, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NAPTR) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Order, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Service, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Regexp, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Replacement, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NID) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = packUint64(rr.NodeID, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NIMLOC) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringHex(rr.Locator, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NINFO) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringTxt(rr.ZSData, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NS) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Ns, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NSAPPTR) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Ptr, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NSEC) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.NextDomain, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packDataNsec(rr.TypeBitMap, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NSEC3) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Hash, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Iterations, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.SaltLength, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Salt, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.HashLength, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase32(rr.NextDomain, msg, off) + if err != nil { + return off, err + } + off, err = packDataNsec(rr.TypeBitMap, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *NSEC3PARAM) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Hash, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Iterations, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.SaltLength, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Salt, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *OPENPGPKEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *OPT) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packDataOpt(rr.Option, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *PTR) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Ptr, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *PX) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Map822, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Mapx400, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *RFC3597) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringHex(rr.Rdata, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *RKEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Flags, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Protocol, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.PublicKey, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *RP) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Mbox, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Txt, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *RRSIG) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.TypeCovered, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Labels, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.OrigTtl, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Expiration, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Inception, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.SignerName, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.Signature, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *RT) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Preference, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Host, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *SIG) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.TypeCovered, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Labels, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.OrigTtl, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Expiration, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Inception, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.SignerName, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packStringBase64(rr.Signature, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *SOA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Ns, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Mbox, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packUint32(rr.Serial, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Refresh, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Retry, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Expire, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Minttl, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *SPF) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringTxt(rr.Txt, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *SRV) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Priority, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Weight, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Port, msg, off) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.Target, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *SSHFP) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Type, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.FingerPrint, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.KeyTag, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Algorithm, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.DigestType, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Digest, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TALINK) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.PreviousName, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = PackDomainName(rr.NextName, msg, off, compression, compress) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TKEY) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Algorithm, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packUint32(rr.Inception, msg, off) + if err != nil { + return off, err + } + off, err = packUint32(rr.Expiration, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Mode, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Error, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.KeySize, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.Key, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.OtherLen, msg, off) + if err != nil { + return off, err + } + off, err = packString(rr.OtherData, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TLSA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint8(rr.Usage, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.Selector, msg, off) + if err != nil { + return off, err + } + off, err = packUint8(rr.MatchingType, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.Certificate, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TSIG) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = PackDomainName(rr.Algorithm, msg, off, compression, compress) + if err != nil { + return off, err + } + off, err = packUint48(rr.TimeSigned, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Fudge, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.MACSize, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.MAC, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.OrigId, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Error, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.OtherLen, msg, off) + if err != nil { + return off, err + } + off, err = packStringHex(rr.OtherData, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *TXT) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringTxt(rr.Txt, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *UID) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint32(rr.Uid, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *UINFO) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packString(rr.Uinfo, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *URI) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packUint16(rr.Priority, msg, off) + if err != nil { + return off, err + } + off, err = packUint16(rr.Weight, msg, off) + if err != nil { + return off, err + } + off, err = packStringOctet(rr.Target, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +func (rr *X25) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packString(rr.PSDNAddress, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + +// unpack*() functions + +func unpackA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(A) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.A, off, err = unpackDataA(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackAAAA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(AAAA) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.AAAA, off, err = unpackDataAAAA(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackAFSDB(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(AFSDB) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Subtype, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Hostname, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackANY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(ANY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + return rr, off, err +} + +func unpackCAA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(CAA) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Flag, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Tag, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Value, off, err = unpackStringOctet(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackCDNSKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(CDNSKEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Flags, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Protocol, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKey, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackCDS(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(CDS) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.DigestType, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Digest, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackCERT(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(CERT) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Type, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Certificate, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackCNAME(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(CNAME) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Target, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackDHCID(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(DHCID) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Digest, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackDLV(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(DLV) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.DigestType, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Digest, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackDNAME(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(DNAME) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Target, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackDNSKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(DNSKEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Flags, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Protocol, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKey, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackDS(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(DS) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.DigestType, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Digest, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackEID(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(EID) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Endpoint, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackEUI48(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(EUI48) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Address, off, err = unpackUint48(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackEUI64(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(EUI64) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Address, off, err = unpackUint64(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackGID(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(GID) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Gid, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackGPOS(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(GPOS) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Longitude, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Latitude, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Altitude, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackHINFO(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(HINFO) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Cpu, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Os, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackHIP(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(HIP) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.HitLength, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKeyAlgorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKeyLength, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Hit, off, err = unpackStringHex(msg, off, off+int(rr.HitLength)) + if err != nil { + return rr, off, err + } + rr.PublicKey, off, err = unpackStringBase64(msg, off, off+int(rr.PublicKeyLength)) + if err != nil { + return rr, off, err + } + rr.RendezvousServers, off, err = unpackDataDomainNames(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(KEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Flags, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Protocol, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKey, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackKX(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(KX) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Exchanger, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackL32(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(L32) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Locator32, off, err = unpackDataA(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackL64(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(L64) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Locator64, off, err = unpackUint64(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackLOC(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(LOC) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Version, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Size, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.HorizPre, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.VertPre, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Latitude, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Longitude, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Altitude, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackLP(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(LP) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Fqdn, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMB(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MB) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Mb, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMD(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MD) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Md, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMF(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MF) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Mf, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMG(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MG) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Mg, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMINFO(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MINFO) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Rmail, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Email, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMR(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MR) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Mr, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackMX(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(MX) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Mx, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNAPTR(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NAPTR) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Order, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Flags, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Service, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Regexp, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Replacement, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNID(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NID) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.NodeID, off, err = unpackUint64(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNIMLOC(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NIMLOC) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Locator, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNINFO(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NINFO) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.ZSData, off, err = unpackStringTxt(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNS(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NS) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Ns, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNSAPPTR(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NSAPPTR) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Ptr, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNSEC(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NSEC) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.NextDomain, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.TypeBitMap, off, err = unpackDataNsec(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNSEC3(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NSEC3) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Hash, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Flags, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Iterations, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.SaltLength, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Salt, off, err = unpackStringHex(msg, off, off+int(rr.SaltLength)) + if err != nil { + return rr, off, err + } + rr.HashLength, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.NextDomain, off, err = unpackStringBase32(msg, off, off+int(rr.HashLength)) + if err != nil { + return rr, off, err + } + rr.TypeBitMap, off, err = unpackDataNsec(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackNSEC3PARAM(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(NSEC3PARAM) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Hash, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Flags, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Iterations, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.SaltLength, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Salt, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackOPENPGPKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(OPENPGPKEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.PublicKey, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackOPT(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(OPT) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Option, off, err = unpackDataOpt(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackPTR(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(PTR) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Ptr, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackPX(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(PX) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Map822, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Mapx400, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackRFC3597(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(RFC3597) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Rdata, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackRKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(RKEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Flags, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Protocol, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.PublicKey, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackRP(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(RP) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Mbox, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Txt, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackRRSIG(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(RRSIG) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.TypeCovered, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Labels, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OrigTtl, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Expiration, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Inception, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.SignerName, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Signature, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackRT(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(RT) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Preference, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Host, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackSIG(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(SIG) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.TypeCovered, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Labels, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OrigTtl, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Expiration, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Inception, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.SignerName, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Signature, off, err = unpackStringBase64(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackSOA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(SOA) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Ns, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Mbox, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Serial, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Refresh, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Retry, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Expire, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Minttl, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackSPF(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(SPF) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Txt, off, err = unpackStringTxt(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackSRV(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(SRV) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Priority, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Weight, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Port, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Target, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackSSHFP(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(SSHFP) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Type, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.FingerPrint, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TA) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.KeyTag, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Algorithm, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.DigestType, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Digest, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTALINK(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TALINK) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.PreviousName, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.NextName, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTKEY(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TKEY) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Algorithm, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Inception, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Expiration, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Mode, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Error, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.KeySize, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Key, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OtherLen, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OtherData, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTLSA(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TLSA) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Usage, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Selector, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.MatchingType, off, err = unpackUint8(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Certificate, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTSIG(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TSIG) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Algorithm, off, err = UnpackDomainName(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.TimeSigned, off, err = unpackUint48(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Fudge, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.MACSize, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.MAC, off, err = unpackStringHex(msg, off, off+int(rr.MACSize)) + if err != nil { + return rr, off, err + } + rr.OrigId, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Error, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OtherLen, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.OtherData, off, err = unpackStringHex(msg, off, off+int(rr.OtherLen)) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackTXT(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(TXT) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Txt, off, err = unpackStringTxt(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackUID(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(UID) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Uid, off, err = unpackUint32(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackUINFO(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(UINFO) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Uinfo, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackURI(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(URI) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Priority, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Weight, off, err = unpackUint16(msg, off) + if err != nil { + return rr, off, err + } + if off == len(msg) { + return rr, off, nil + } + rr.Target, off, err = unpackStringOctet(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +func unpackX25(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(X25) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.PSDNAddress, off, err = unpackString(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + +var typeToUnpack = map[uint16]func(RR_Header, []byte, int) (RR, int, error){ + TypeA: unpackA, + TypeAAAA: unpackAAAA, + TypeAFSDB: unpackAFSDB, + TypeANY: unpackANY, + TypeCAA: unpackCAA, + TypeCDNSKEY: unpackCDNSKEY, + TypeCDS: unpackCDS, + TypeCERT: unpackCERT, + TypeCNAME: unpackCNAME, + TypeDHCID: unpackDHCID, + TypeDLV: unpackDLV, + TypeDNAME: unpackDNAME, + TypeDNSKEY: unpackDNSKEY, + TypeDS: unpackDS, + TypeEID: unpackEID, + TypeEUI48: unpackEUI48, + TypeEUI64: unpackEUI64, + TypeGID: unpackGID, + TypeGPOS: unpackGPOS, + TypeHINFO: unpackHINFO, + TypeHIP: unpackHIP, + TypeKEY: unpackKEY, + TypeKX: unpackKX, + TypeL32: unpackL32, + TypeL64: unpackL64, + TypeLOC: unpackLOC, + TypeLP: unpackLP, + TypeMB: unpackMB, + TypeMD: unpackMD, + TypeMF: unpackMF, + TypeMG: unpackMG, + TypeMINFO: unpackMINFO, + TypeMR: unpackMR, + TypeMX: unpackMX, + TypeNAPTR: unpackNAPTR, + TypeNID: unpackNID, + TypeNIMLOC: unpackNIMLOC, + TypeNINFO: unpackNINFO, + TypeNS: unpackNS, + TypeNSAPPTR: unpackNSAPPTR, + TypeNSEC: unpackNSEC, + TypeNSEC3: unpackNSEC3, + TypeNSEC3PARAM: unpackNSEC3PARAM, + TypeOPENPGPKEY: unpackOPENPGPKEY, + TypeOPT: unpackOPT, + TypePTR: unpackPTR, + TypePX: unpackPX, + TypeRKEY: unpackRKEY, + TypeRP: unpackRP, + TypeRRSIG: unpackRRSIG, + TypeRT: unpackRT, + TypeSIG: unpackSIG, + TypeSOA: unpackSOA, + TypeSPF: unpackSPF, + TypeSRV: unpackSRV, + TypeSSHFP: unpackSSHFP, + TypeTA: unpackTA, + TypeTALINK: unpackTALINK, + TypeTKEY: unpackTKEY, + TypeTLSA: unpackTLSA, + TypeTSIG: unpackTSIG, + TypeTXT: unpackTXT, + TypeUID: unpackUID, + TypeUINFO: unpackUINFO, + TypeURI: unpackURI, + TypeX25: unpackX25, +} diff --git a/vendor/github.com/miekg/dns/ztypes.go b/vendor/github.com/miekg/dns/ztypes.go index 3d0f9aef5733..a4ecbb0cc0fa 100644 --- a/vendor/github.com/miekg/dns/ztypes.go +++ b/vendor/github.com/miekg/dns/ztypes.go @@ -1,5 +1,5 @@ // *** DO NOT MODIFY *** -// AUTOGENERATED BY go generate +// AUTOGENERATED BY go generate from type_generate.go package dns @@ -31,7 +31,6 @@ var TypeToRR = map[uint16]func() RR{ TypeGPOS: func() RR { return new(GPOS) }, TypeHINFO: func() RR { return new(HINFO) }, TypeHIP: func() RR { return new(HIP) }, - TypeIPSECKEY: func() RR { return new(IPSECKEY) }, TypeKEY: func() RR { return new(KEY) }, TypeKX: func() RR { return new(KX) }, TypeL32: func() RR { return new(L32) }, @@ -76,7 +75,6 @@ var TypeToRR = map[uint16]func() RR{ TypeUID: func() RR { return new(UID) }, TypeUINFO: func() RR { return new(UINFO) }, TypeURI: func() RR { return new(URI) }, - TypeWKS: func() RR { return new(WKS) }, TypeX25: func() RR { return new(X25) }, } @@ -105,7 +103,6 @@ var TypeToString = map[uint16]string{ TypeGPOS: "GPOS", TypeHINFO: "HINFO", TypeHIP: "HIP", - TypeIPSECKEY: "IPSECKEY", TypeISDN: "ISDN", TypeIXFR: "IXFR", TypeKEY: "KEY", @@ -158,7 +155,6 @@ var TypeToString = map[uint16]string{ TypeUINFO: "UINFO", TypeUNSPEC: "UNSPEC", TypeURI: "URI", - TypeWKS: "WKS", TypeX25: "X25", TypeNSAPPTR: "NSAP-PTR", } @@ -185,7 +181,6 @@ func (rr *GID) Header() *RR_Header { return &rr.Hdr } func (rr *GPOS) Header() *RR_Header { return &rr.Hdr } func (rr *HINFO) Header() *RR_Header { return &rr.Hdr } func (rr *HIP) Header() *RR_Header { return &rr.Hdr } -func (rr *IPSECKEY) Header() *RR_Header { return &rr.Hdr } func (rr *KEY) Header() *RR_Header { return &rr.Hdr } func (rr *KX) Header() *RR_Header { return &rr.Hdr } func (rr *L32) Header() *RR_Header { return &rr.Hdr } @@ -231,7 +226,6 @@ func (rr *TXT) Header() *RR_Header { return &rr.Hdr } func (rr *UID) Header() *RR_Header { return &rr.Hdr } func (rr *UINFO) Header() *RR_Header { return &rr.Hdr } func (rr *URI) Header() *RR_Header { return &rr.Hdr } -func (rr *WKS) Header() *RR_Header { return &rr.Hdr } func (rr *X25) Header() *RR_Header { return &rr.Hdr } // len() functions @@ -688,9 +682,6 @@ func (rr *HIP) copy() RR { copy(RendezvousServers, rr.RendezvousServers) return &HIP{*rr.Hdr.copyHeader(), rr.HitLength, rr.PublicKeyAlgorithm, rr.PublicKeyLength, rr.Hit, rr.PublicKey, RendezvousServers} } -func (rr *IPSECKEY) copy() RR { - return &IPSECKEY{*rr.Hdr.copyHeader(), rr.Precedence, rr.GatewayType, rr.Algorithm, copyIP(rr.GatewayA), copyIP(rr.GatewayAAAA), rr.GatewayName, rr.PublicKey} -} func (rr *KX) copy() RR { return &KX{*rr.Hdr.copyHeader(), rr.Preference, rr.Exchanger} } @@ -832,11 +823,6 @@ func (rr *UINFO) copy() RR { func (rr *URI) copy() RR { return &URI{*rr.Hdr.copyHeader(), rr.Priority, rr.Weight, rr.Target} } -func (rr *WKS) copy() RR { - BitMap := make([]uint16, len(rr.BitMap)) - copy(BitMap, rr.BitMap) - return &WKS{*rr.Hdr.copyHeader(), copyIP(rr.Address), rr.Protocol, BitMap} -} func (rr *X25) copy() RR { return &X25{*rr.Hdr.copyHeader(), rr.PSDNAddress} } diff --git a/vendor/github.com/mreiferson/go-httpclient/.gitignore b/vendor/github.com/mreiferson/go-httpclient/.gitignore new file mode 100644 index 000000000000..dbec55fb6f41 --- /dev/null +++ b/vendor/github.com/mreiferson/go-httpclient/.gitignore @@ -0,0 +1 @@ +*.sw[op] diff --git a/vendor/github.com/mreiferson/go-httpclient/.travis.yml b/vendor/github.com/mreiferson/go-httpclient/.travis.yml new file mode 100644 index 000000000000..ba1b6b7f9fed --- /dev/null +++ b/vendor/github.com/mreiferson/go-httpclient/.travis.yml @@ -0,0 +1,11 @@ +language: go +go: + - 1.1 +install: + - go get github.com/bmizerany/assert +script: + - pushd $TRAVIS_BUILD_DIR + - go test + - popd +notifications: + email: false diff --git a/vendor/github.com/mreiferson/go-httpclient/LICENSE b/vendor/github.com/mreiferson/go-httpclient/LICENSE new file mode 100644 index 000000000000..ba625cab0996 --- /dev/null +++ b/vendor/github.com/mreiferson/go-httpclient/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Matt Reiferson + +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/mreiferson/go-httpclient/README.md b/vendor/github.com/mreiferson/go-httpclient/README.md new file mode 100644 index 000000000000..6d0dbff945f6 --- /dev/null +++ b/vendor/github.com/mreiferson/go-httpclient/README.md @@ -0,0 +1,41 @@ +## go-httpclient + +**requires Go 1.1+** as of `v0.4.0` the API has been completely re-written for Go 1.1 (for a Go +1.0.x compatible release see [1adef50](https://github.com/mreiferson/go-httpclient/tree/1adef50)) + +[![Build +Status](https://secure.travis-ci.org/mreiferson/go-httpclient.png?branch=master)](http://travis-ci.org/mreiferson/go-httpclient) + +Provides an HTTP Transport that implements the `RoundTripper` interface and +can be used as a built in replacement for the standard library's, providing: + + * connection timeouts + * request timeouts + +This is a thin wrapper around `http.Transport` that sets dial timeouts and uses +Go's internal timer scheduler to call the Go 1.1+ `CancelRequest()` API. + +### Example + +```go +transport := &httpclient.Transport{ + ConnectTimeout: 1*time.Second, + RequestTimeout: 10*time.Second, + ResponseHeaderTimeout: 5*time.Second, +} +defer transport.Close() + +client := &http.Client{Transport: transport} +req, _ := http.NewRequest("GET", "http://127.0.0.1/test", nil) +resp, err := client.Do(req) +if err != nil { + return err +} +defer resp.Body.Close() +``` + +*Note:* you will want to re-use a single client object rather than creating one for each request, otherwise you will end up [leaking connections](https://code.google.com/p/go/issues/detail?id=4049#c3). + +### Reference Docs + +For API docs see [godoc](http://godoc.org/github.com/mreiferson/go-httpclient). diff --git a/vendor/github.com/mreiferson/go-httpclient/httpclient.go b/vendor/github.com/mreiferson/go-httpclient/httpclient.go new file mode 100644 index 000000000000..89e018bffdae --- /dev/null +++ b/vendor/github.com/mreiferson/go-httpclient/httpclient.go @@ -0,0 +1,237 @@ +/* +Provides an HTTP Transport that implements the `RoundTripper` interface and +can be used as a built in replacement for the standard library's, providing: + + * connection timeouts + * request timeouts + +This is a thin wrapper around `http.Transport` that sets dial timeouts and uses +Go's internal timer scheduler to call the Go 1.1+ `CancelRequest()` API. +*/ +package httpclient + +import ( + "crypto/tls" + "errors" + "io" + "net" + "net/http" + "net/url" + "sync" + "time" +) + +// returns the current version of the package +func Version() string { + return "0.4.1" +} + +// Transport implements the RoundTripper interface and can be used as a replacement +// for Go's built in http.Transport implementing end-to-end request timeouts. +// +// transport := &httpclient.Transport{ +// ConnectTimeout: 1*time.Second, +// ResponseHeaderTimeout: 5*time.Second, +// RequestTimeout: 10*time.Second, +// } +// defer transport.Close() +// +// client := &http.Client{Transport: transport} +// req, _ := http.NewRequest("GET", "http://127.0.0.1/test", nil) +// resp, err := client.Do(req) +// if err != nil { +// return err +// } +// defer resp.Body.Close() +// +type Transport struct { + // Proxy specifies a function to return a proxy for a given + // *http.Request. If the function returns a non-nil error, the + // request is aborted with the provided error. + // If Proxy is nil or returns a nil *url.URL, no proxy is used. + Proxy func(*http.Request) (*url.URL, error) + + // Dial specifies the dial function for creating TCP + // connections. This will override the Transport's ConnectTimeout and + // ReadWriteTimeout settings. + // If Dial is nil, a dialer is generated on demand matching the Transport's + // options. + Dial func(network, addr string) (net.Conn, error) + + // TLSClientConfig specifies the TLS configuration to use with + // tls.Client. If nil, the default configuration is used. + TLSClientConfig *tls.Config + + // DisableKeepAlives, if true, prevents re-use of TCP connections + // between different HTTP requests. + DisableKeepAlives bool + + // DisableCompression, if true, prevents the Transport from + // requesting compression with an "Accept-Encoding: gzip" + // request header when the Request contains no existing + // Accept-Encoding value. If the Transport requests gzip on + // its own and gets a gzipped response, it's transparently + // decoded in the Response.Body. However, if the user + // explicitly requested gzip it is not automatically + // uncompressed. + DisableCompression bool + + // MaxIdleConnsPerHost, if non-zero, controls the maximum idle + // (keep-alive) to keep per-host. If zero, + // http.DefaultMaxIdleConnsPerHost is used. + MaxIdleConnsPerHost int + + // ConnectTimeout, if non-zero, is the maximum amount of time a dial will wait for + // a connect to complete. + ConnectTimeout time.Duration + + // ResponseHeaderTimeout, if non-zero, specifies the amount of + // time to wait for a server's response headers after fully + // writing the request (including its body, if any). This + // time does not include the time to read the response body. + ResponseHeaderTimeout time.Duration + + // RequestTimeout, if non-zero, specifies the amount of time for the entire + // request to complete (including all of the above timeouts + entire response body). + // This should never be less than the sum total of the above two timeouts. + RequestTimeout time.Duration + + // ReadWriteTimeout, if non-zero, will set a deadline for every Read and + // Write operation on the request connection. + ReadWriteTimeout time.Duration + + // TCPWriteBufferSize, the size of the operating system's write + // buffer associated with the connection. + TCPWriteBufferSize int + + // TCPReadBuffserSize, the size of the operating system's read + // buffer associated with the connection. + TCPReadBufferSize int + + starter sync.Once + transport *http.Transport +} + +// Close cleans up the Transport, currently a no-op +func (t *Transport) Close() error { + return nil +} + +func (t *Transport) lazyStart() { + if t.Dial == nil { + t.Dial = func(netw, addr string) (net.Conn, error) { + c, err := net.DialTimeout(netw, addr, t.ConnectTimeout) + if err != nil { + return nil, err + } + + if t.TCPReadBufferSize != 0 || t.TCPWriteBufferSize != 0 { + if tcpCon, ok := c.(*net.TCPConn); ok { + if t.TCPWriteBufferSize != 0 { + if err = tcpCon.SetWriteBuffer(t.TCPWriteBufferSize); err != nil { + return nil, err + } + } + if t.TCPReadBufferSize != 0 { + if err = tcpCon.SetReadBuffer(t.TCPReadBufferSize); err != nil { + return nil, err + } + } + } else { + err = errors.New("Not Tcp Connection") + return nil, err + } + } + + if t.ReadWriteTimeout > 0 { + timeoutConn := &rwTimeoutConn{ + TCPConn: c.(*net.TCPConn), + rwTimeout: t.ReadWriteTimeout, + } + return timeoutConn, nil + } + return c, nil + } + } + + t.transport = &http.Transport{ + Dial: t.Dial, + Proxy: t.Proxy, + TLSClientConfig: t.TLSClientConfig, + DisableKeepAlives: t.DisableKeepAlives, + DisableCompression: t.DisableCompression, + MaxIdleConnsPerHost: t.MaxIdleConnsPerHost, + ResponseHeaderTimeout: t.ResponseHeaderTimeout, + } +} + +func (t *Transport) CancelRequest(req *http.Request) { + t.starter.Do(t.lazyStart) + + t.transport.CancelRequest(req) +} + +func (t *Transport) CloseIdleConnections() { + t.starter.Do(t.lazyStart) + + t.transport.CloseIdleConnections() +} + +func (t *Transport) RegisterProtocol(scheme string, rt http.RoundTripper) { + t.starter.Do(t.lazyStart) + + t.transport.RegisterProtocol(scheme, rt) +} + +func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) { + t.starter.Do(t.lazyStart) + + if t.RequestTimeout > 0 { + timer := time.AfterFunc(t.RequestTimeout, func() { + t.transport.CancelRequest(req) + }) + + resp, err = t.transport.RoundTrip(req) + if err != nil { + timer.Stop() + } else { + resp.Body = &bodyCloseInterceptor{ReadCloser: resp.Body, timer: timer} + } + } else { + resp, err = t.transport.RoundTrip(req) + } + + return +} + +type bodyCloseInterceptor struct { + io.ReadCloser + timer *time.Timer +} + +func (bci *bodyCloseInterceptor) Close() error { + bci.timer.Stop() + return bci.ReadCloser.Close() +} + +// A net.Conn that sets a deadline for every Read or Write operation +type rwTimeoutConn struct { + *net.TCPConn + rwTimeout time.Duration +} + +func (c *rwTimeoutConn) Read(b []byte) (int, error) { + err := c.TCPConn.SetDeadline(time.Now().Add(c.rwTimeout)) + if err != nil { + return 0, err + } + return c.TCPConn.Read(b) +} + +func (c *rwTimeoutConn) Write(b []byte) (int, error) { + err := c.TCPConn.SetDeadline(time.Now().Add(c.rwTimeout)) + if err != nil { + return 0, err + } + return c.TCPConn.Write(b) +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/README.md b/vendor/github.com/opencontainers/runc/libcontainer/README.md index fc6b4b0b1849..614969462f85 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/README.md +++ b/vendor/github.com/opencontainers/runc/libcontainer/README.md @@ -76,7 +76,7 @@ config := &configs.Config{ Name: "test-container", Parent: "system", Resources: &configs.Resources{ - MemorySwappiness: -1, + MemorySwappiness: nil, AllowAllDevices: false, AllowedDevices: configs.DefaultAllowedDevices, }, @@ -133,15 +133,15 @@ config := &configs.Config{ UidMappings: []configs.IDMap{ { ContainerID: 0, - Host: 1000, - size: 65536, + HostID: 1000, + Size: 65536, }, }, GidMappings: []configs.IDMap{ { ContainerID: 0, - Host: 1000, - size: 65536, + HostID: 1000, + Size: 65536, }, }, Networks: []*configs.Network{ @@ -216,6 +216,9 @@ container.Pause() // resume all paused processes. container.Resume() + +// send signal to container's init process. +container.Signal(signal) ``` diff --git a/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md b/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md index 615111252f94..221545c01dc3 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md +++ b/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md @@ -142,6 +142,7 @@ system resources like cpu, memory, and device access. | perf_event | 1 | | freezer | 1 | | hugetlb | 1 | +| pids | 1 | All cgroup subsystem are joined so that statistics can be collected from @@ -199,7 +200,7 @@ provide a good default for security and flexibility for the applications. | CAP_SYS_BOOT | 0 | | CAP_LEASE | 0 | | CAP_WAKE_ALARM | 0 | -| CAP_BLOCK_SUSPE | 0 | +| CAP_BLOCK_SUSPEND | 0 | Additional security layers like [apparmor](https://wiki.ubuntu.com/AppArmor) diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go index c8f7796567b9..274ab47dd83a 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go @@ -9,7 +9,7 @@ import ( ) type Manager interface { - // Apply cgroup configuration to the process with the specified pid + // Applies cgroup configuration to the process with the specified pid Apply(pid int) error // Returns the PIDs inside the cgroup set diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go index 4da3b734e18d..114f002ec846 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go @@ -14,6 +14,7 @@ import ( "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" + libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils" ) var ( @@ -30,6 +31,7 @@ var ( &NetPrioGroup{}, &PerfEventGroup{}, &FreezerGroup{}, + &NameGroup{GroupName: "name=systemd", Join: true}, } CgroupProcesses = "cgroup.procs" HugePageSizes, _ = cgroups.GetHugePageSize() @@ -94,11 +96,10 @@ func getCgroupRoot() (string, error) { } type cgroupData struct { - root string - parent string - name string - config *configs.Cgroup - pid int + root string + innerPath string + config *configs.Cgroup + pid int } func (m *Manager) Apply(pid int) (err error) { @@ -129,12 +130,9 @@ func (m *Manager) Apply(pid int) (err error) { return cgroups.EnterPid(m.Paths, pid) } + m.mu.Lock() + defer m.mu.Unlock() paths := make(map[string]string) - defer func() { - if err != nil { - cgroups.RemovePaths(paths) - } - }() for _, sys := range subsystems { if err := sys.Apply(d); err != nil { return err @@ -267,45 +265,31 @@ func getCgroupPath(c *configs.Cgroup) (string, error) { return d.path("devices") } -// pathClean makes a path safe for use with filepath.Join. This is done by not -// only cleaning the path, but also (if the path is relative) adding a leading -// '/' and cleaning it (then removing the leading '/'). This ensures that a -// path resulting from prepending another path will always resolve to lexically -// be a subdirectory of the prefixed path. This is all done lexically, so paths -// that include symlinks won't be safe as a result of using pathClean. -func pathClean(path string) string { - // Ensure that all paths are cleaned (especially problematic ones like - // "/../../../../../" which can cause lots of issues). - path = filepath.Clean(path) - - // If the path isn't absolute, we need to do more processing to fix paths - // such as "../../../..//some/path". We also shouldn't convert absolute - // paths to relative ones. - if !filepath.IsAbs(path) { - path = filepath.Clean(string(os.PathSeparator) + path) - // This can't fail, as (by definition) all paths are relative to root. - path, _ = filepath.Rel(string(os.PathSeparator), path) - } - - // Clean the path again for good measure. - return filepath.Clean(path) -} - func getCgroupData(c *configs.Cgroup, pid int) (*cgroupData, error) { root, err := getCgroupRoot() if err != nil { return nil, err } - // Clean the parent slice path. - c.Parent = pathClean(c.Parent) + if (c.Name != "" || c.Parent != "") && c.Path != "" { + return nil, fmt.Errorf("cgroup: either Path or Name and Parent should be used") + } + + // XXX: Do not remove this code. Path safety is important! -- cyphar + cgPath := libcontainerUtils.CleanPath(c.Path) + cgParent := libcontainerUtils.CleanPath(c.Parent) + cgName := libcontainerUtils.CleanPath(c.Name) + + innerPath := cgPath + if innerPath == "" { + innerPath = filepath.Join(cgParent, cgName) + } return &cgroupData{ - root: root, - parent: c.Parent, - name: c.Name, - config: c, - pid: pid, + root: root, + innerPath: innerPath, + config: c, + pid: pid, }, nil } @@ -333,11 +317,10 @@ func (raw *cgroupData) path(subsystem string) (string, error) { return "", err } - cgPath := filepath.Join(raw.parent, raw.name) // If the cgroup name/path is absolute do not look relative to the cgroup of the init process. - if filepath.IsAbs(cgPath) { + if filepath.IsAbs(raw.innerPath) { // Sometimes subsystems can be mounted togethger as 'cpu,cpuacct'. - return filepath.Join(raw.root, filepath.Base(mnt), cgPath), nil + return filepath.Join(raw.root, filepath.Base(mnt), raw.innerPath), nil } parentPath, err := raw.parentPath(subsystem, mnt, root) @@ -345,7 +328,7 @@ func (raw *cgroupData) path(subsystem string) (string, error) { return "", err } - return filepath.Join(parentPath, cgPath), nil + return filepath.Join(parentPath, raw.innerPath), nil } func (raw *cgroupData) join(subsystem string) (string, error) { @@ -368,7 +351,10 @@ func writeFile(dir, file, data string) error { if dir == "" { return fmt.Errorf("no such directory for %s.", file) } - return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) + if err := ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700); err != nil { + return fmt.Errorf("failed to write %v to %v: %v", data, file, err) + } + return nil } func readFile(dir, file string) (string, error) { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go index ed1002316e4e..cbe62bd983aa 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go @@ -12,6 +12,7 @@ import ( "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" + libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils" ) type CpusetGroup struct { @@ -88,7 +89,7 @@ func (s *CpusetGroup) getSubsystemSettings(parent string) (cpus []byte, mems []b // it's parent. func (s *CpusetGroup) ensureParent(current, root string) error { parent := filepath.Dir(current) - if filepath.Clean(parent) == root { + if libcontainerUtils.CleanPath(parent) == root { return nil } // Avoid infinite recursion. diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go index a41ce801ffd3..5f783310947d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go @@ -5,6 +5,7 @@ package fs import ( "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" + "github.com/opencontainers/runc/libcontainer/system" ) type DevicesGroup struct { @@ -25,6 +26,23 @@ func (s *DevicesGroup) Apply(d *cgroupData) error { } func (s *DevicesGroup) Set(path string, cgroup *configs.Cgroup) error { + if system.RunningInUserNS() { + return nil + } + + devices := cgroup.Resources.Devices + if len(devices) > 0 { + for _, dev := range devices { + file := "devices.deny" + if dev.Allow { + file = "devices.allow" + } + if err := writeFile(path, file, dev.CgroupString()); err != nil { + return err + } + } + return nil + } if !cgroup.Resources.AllowAllDevices { if err := writeFile(path, "devices.deny", "a"); err != nil { return err diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go index 8c3e963fe011..6b4a9eac4627 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go @@ -65,19 +65,61 @@ func (s *MemoryGroup) SetKernelMemory(path string, cgroup *configs.Cgroup) error return nil } -func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error { - if cgroup.Resources.Memory != 0 { - if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Resources.Memory, 10)); err != nil { +func setMemoryAndSwap(path string, cgroup *configs.Cgroup) error { + // When memory and swap memory are both set, we need to handle the cases + // for updating container. + if cgroup.Resources.Memory != 0 && cgroup.Resources.MemorySwap > 0 { + memoryUsage, err := getMemoryData(path, "") + if err != nil { return err } + + // When update memory limit, we should adapt the write sequence + // for memory and swap memory, so it won't fail because the new + // value and the old value don't fit kernel's validation. + if memoryUsage.Limit < uint64(cgroup.Resources.MemorySwap) { + if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.Resources.MemorySwap, 10)); err != nil { + return err + } + if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Resources.Memory, 10)); err != nil { + return err + } + } else { + if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Resources.Memory, 10)); err != nil { + return err + } + if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.Resources.MemorySwap, 10)); err != nil { + return err + } + } + } else { + if cgroup.Resources.Memory != 0 { + if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Resources.Memory, 10)); err != nil { + return err + } + } + if cgroup.Resources.MemorySwap > 0 { + if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.Resources.MemorySwap, 10)); err != nil { + return err + } + } } + + return nil +} + +func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error { + if err := setMemoryAndSwap(path, cgroup); err != nil { + return err + } + if cgroup.Resources.MemoryReservation != 0 { if err := writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatInt(cgroup.Resources.MemoryReservation, 10)); err != nil { return err } } - if cgroup.Resources.MemorySwap > 0 { - if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.Resources.MemorySwap, 10)); err != nil { + if cgroup.Resources.KernelMemoryTCP != 0 { + if err := writeFile(path, "memory.kmem.tcp.limit_in_bytes", strconv.FormatInt(cgroup.Resources.KernelMemoryTCP, 10)); err != nil { return err } } @@ -86,14 +128,14 @@ func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error { return err } } - if cgroup.Resources.MemorySwappiness >= 0 && cgroup.Resources.MemorySwappiness <= 100 { - if err := writeFile(path, "memory.swappiness", strconv.FormatInt(cgroup.Resources.MemorySwappiness, 10)); err != nil { + if cgroup.Resources.MemorySwappiness == nil || int64(*cgroup.Resources.MemorySwappiness) == -1 { + return nil + } else if int64(*cgroup.Resources.MemorySwappiness) >= 0 && int64(*cgroup.Resources.MemorySwappiness) <= 100 { + if err := writeFile(path, "memory.swappiness", strconv.FormatInt(*cgroup.Resources.MemorySwappiness, 10)); err != nil { return err } - } else if cgroup.Resources.MemorySwappiness == -1 { - return nil } else { - return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", cgroup.Resources.MemorySwappiness) + return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", int64(*cgroup.Resources.MemorySwappiness)) } return nil @@ -139,6 +181,11 @@ func (s *MemoryGroup) GetStats(path string, stats *cgroups.Stats) error { return err } stats.MemoryStats.KernelUsage = kernelUsage + kernelTCPUsage, err := getMemoryData(path, "kmem.tcp") + if err != nil { + return err + } + stats.MemoryStats.KernelTCPUsage = kernelTCPUsage return nil } @@ -148,8 +195,9 @@ func memoryAssigned(cgroup *configs.Cgroup) bool { cgroup.Resources.MemoryReservation != 0 || cgroup.Resources.MemorySwap > 0 || cgroup.Resources.KernelMemory > 0 || + cgroup.Resources.KernelMemoryTCP > 0 || cgroup.Resources.OomKillDisable || - cgroup.Resources.MemorySwappiness != -1 + (cgroup.Resources.MemorySwappiness != nil && *cgroup.Resources.MemorySwappiness != -1) } func getMemoryData(path, name string) (cgroups.MemoryData, error) { @@ -162,6 +210,7 @@ func getMemoryData(path, name string) (cgroups.MemoryData, error) { usage := strings.Join([]string{moduleName, "usage_in_bytes"}, ".") maxUsage := strings.Join([]string{moduleName, "max_usage_in_bytes"}, ".") failcnt := strings.Join([]string{moduleName, "failcnt"}, ".") + limit := strings.Join([]string{moduleName, "limit_in_bytes"}, ".") value, err := getCgroupParamUint(path, usage) if err != nil { @@ -187,6 +236,14 @@ func getMemoryData(path, name string) (cgroups.MemoryData, error) { return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", failcnt, err) } memoryData.Failcnt = value + value, err = getCgroupParamUint(path, limit) + if err != nil { + if moduleName != "memory" && os.IsNotExist(err) { + return cgroups.MemoryData{}, nil + } + return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", limit, err) + } + memoryData.Limit = value return memoryData, nil } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go index 0e423f667d87..d8cf1d87c043 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go @@ -9,6 +9,7 @@ import ( type NameGroup struct { GroupName string + Join bool } func (s *NameGroup) Name() string { @@ -16,6 +17,10 @@ func (s *NameGroup) Name() string { } func (s *NameGroup) Apply(d *cgroupData) error { + if s.Join { + // ignore errors if the named cgroup does not exist + d.join(s.GroupName) + } return nil } @@ -24,6 +29,9 @@ func (s *NameGroup) Set(path string, cgroup *configs.Cgroup) error { } func (s *NameGroup) Remove(d *cgroupData) error { + if s.Join { + removePath(d.path(s.GroupName)) + } return nil } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go index 96cbb896cb19..f1e37205518b 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go @@ -4,6 +4,7 @@ package fs import ( "fmt" + "path/filepath" "strconv" "github.com/opencontainers/runc/libcontainer/cgroups" @@ -47,11 +48,26 @@ func (s *PidsGroup) Remove(d *cgroupData) error { } func (s *PidsGroup) GetStats(path string, stats *cgroups.Stats) error { - value, err := getCgroupParamUint(path, "pids.current") + current, err := getCgroupParamUint(path, "pids.current") if err != nil { return fmt.Errorf("failed to parse pids.current - %s", err) } - stats.PidsStats.Current = value + maxString, err := getCgroupParamString(path, "pids.max") + if err != nil { + return fmt.Errorf("failed to parse pids.max - %s", err) + } + + // Default if pids.max == "max" is 0 -- which represents "no limit". + var max uint64 + if maxString != "max" { + max, err = parseUint(maxString, 10, 64) + if err != nil { + return fmt.Errorf("failed to parse pids.max - unable to parse %q as a uint from Cgroup file %q", maxString, filepath.Join(path, "pids.max")) + } + } + + stats.PidsStats.Current = current + stats.PidsStats.Limit = max return nil } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go index 74c65abf13ba..797a923c3884 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go @@ -36,7 +36,9 @@ type MemoryData struct { Usage uint64 `json:"usage,omitempty"` MaxUsage uint64 `json:"max_usage,omitempty"` Failcnt uint64 `json:"failcnt"` + Limit uint64 `json:"limit"` } + type MemoryStats struct { // memory used for cache Cache uint64 `json:"cache,omitempty"` @@ -44,14 +46,19 @@ type MemoryStats struct { Usage MemoryData `json:"usage,omitempty"` // usage of memory + swap SwapUsage MemoryData `json:"swap_usage,omitempty"` - // usafe of kernel memory - KernelUsage MemoryData `json:"kernel_usage,omitempty"` - Stats map[string]uint64 `json:"stats,omitempty"` + // usage of kernel memory + KernelUsage MemoryData `json:"kernel_usage,omitempty"` + // usage of kernel TCP memory + KernelTCPUsage MemoryData `json:"kernel_tcp_usage,omitempty"` + + Stats map[string]uint64 `json:"stats,omitempty"` } type PidsStats struct { // number of pids in the cgroup Current uint64 `json:"current,omitempty"` + // active pids hard limit + Limit uint64 `json:"limit,omitempty"` } type BlkioStatEntry struct { @@ -78,7 +85,7 @@ type HugetlbStats struct { Usage uint64 `json:"usage,omitempty"` // maximum usage ever recorded. MaxUsage uint64 `json:"max_usage,omitempty"` - // number of times htgetlb usage allocation failure. + // number of times hugetlb usage allocation failure. Failcnt uint64 `json:"failcnt"` } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go index db020a971fe6..b61580956032 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go @@ -150,16 +150,6 @@ func UseSystemd() bool { return hasStartTransientUnit } -func getIfaceForUnit(unitName string) string { - if strings.HasSuffix(unitName, ".scope") { - return "Scope" - } - if strings.HasSuffix(unitName, ".service") { - return "Service" - } - return "Unit" -} - func (m *Manager) Apply(pid int) error { var ( c = m.Cgroups @@ -193,6 +183,8 @@ func (m *Manager) Apply(pid int) error { systemdDbus.PropSlice(slice), systemdDbus.PropDescription("docker container "+c.Name), newProp("PIDs", []uint32{uint32(pid)}), + // This is only supported on systemd versions 218 and above. + newProp("Delegate", true), ) // Always enable accounting, this gets us the same behaviour as the fs implementation, @@ -236,53 +228,7 @@ func (m *Manager) Apply(pid int) error { return err } - if err := joinDevices(c, pid); err != nil { - return err - } - - // TODO: CpuQuota and CpuPeriod not available in systemd - // we need to manually join the cpu.cfs_quota_us and cpu.cfs_period_us - if err := joinCpu(c, pid); err != nil { - return err - } - - // TODO: MemoryReservation and MemorySwap not available in systemd - if err := joinMemory(c, pid); err != nil { - return err - } - - // we need to manually join the freezer, net_cls, net_prio, pids and cpuset cgroup in systemd - // because it does not currently support it via the dbus api. - if err := joinFreezer(c, pid); err != nil { - return err - } - - if err := joinNetPrio(c, pid); err != nil { - return err - } - if err := joinNetCls(c, pid); err != nil { - return err - } - - if err := joinPids(c, pid); err != nil { - return err - } - - if err := joinCpuset(c, pid); err != nil { - return err - } - - if err := joinHugetlb(c, pid); err != nil { - return err - } - - if err := joinPerfEvent(c, pid); err != nil { - return err - } - // FIXME: Systemd does have `BlockIODeviceWeight` property, but we got problem - // using that (at least on systemd 208, see https://github.com/opencontainers/runc/libcontainer/pull/354), - // so use fs work around for now. - if err := joinBlkio(c, pid); err != nil { + if err := joinCgroups(c, pid); err != nil { return err } @@ -347,43 +293,41 @@ func join(c *configs.Cgroup, subsystem string, pid int) (string, error) { return path, nil } -func joinCpu(c *configs.Cgroup, pid int) error { - _, err := join(c, "cpu", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} - -func joinFreezer(c *configs.Cgroup, pid int) error { - _, err := join(c, "freezer", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} - -func joinNetPrio(c *configs.Cgroup, pid int) error { - _, err := join(c, "net_prio", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} - -func joinNetCls(c *configs.Cgroup, pid int) error { - _, err := join(c, "net_cls", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err +func joinCgroups(c *configs.Cgroup, pid int) error { + for _, sys := range subsystems { + name := sys.Name() + switch name { + case "name=systemd": + // let systemd handle this + break + case "cpuset": + path, err := getSubsystemPath(c, name) + if err != nil && !cgroups.IsNotFound(err) { + return err + } + s := &fs.CpusetGroup{} + if err := s.ApplyDir(path, c, pid); err != nil { + return err + } + break + default: + _, err := join(c, name, pid) + if err != nil { + // Even if it's `not found` error, we'll return err + // because devices cgroup is hard requirement for + // container security. + if name == "devices" { + return err + } + // For other subsystems, omit the `not found` error + // because they are optional. + if !cgroups.IsNotFound(err) { + return err + } + } + } } - return nil -} -func joinPids(c *configs.Cgroup, pid int) error { - _, err := join(c, "pids", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } return nil } @@ -392,9 +336,18 @@ func joinPids(c *configs.Cgroup, pid int) error { // test.slice/test-a.slice/test-a-b.slice. func expandSlice(slice string) (string, error) { suffix := ".slice" - sliceName := strings.TrimSuffix(slice, suffix) + // Name has to end with ".slice", but can't be just ".slice". + if len(slice) < len(suffix) || !strings.HasSuffix(slice, suffix) { + return "", fmt.Errorf("invalid slice name: %s", slice) + } + + // Path-separators are not allowed. + if strings.Contains(slice, "/") { + return "", fmt.Errorf("invalid slice name: %s", slice) + } var path, prefix string + sliceName := strings.TrimSuffix(slice, suffix) for _, component := range strings.Split(sliceName, "-") { // test--a.slice isn't permitted, nor is -test.slice. if component == "" { @@ -510,27 +463,6 @@ func getUnitName(c *configs.Cgroup) string { return fmt.Sprintf("%s-%s.scope", c.ScopePrefix, c.Name) } -// Atm we can't use the systemd device support because of two missing things: -// * Support for wildcards to allow mknod on any device -// * Support for wildcards to allow /dev/pts support -// -// The second is available in more recent systemd as "char-pts", but not in e.g. v208 which is -// in wide use. When both these are available we will be able to switch, but need to keep the old -// implementation for backwards compat. -// -// Note: we can't use systemd to set up the initial limits, and then change the cgroup -// because systemd will re-write the device settings if it needs to re-apply the cgroup context. -// This happens at least for v208 when any sibling unit is started. -func joinDevices(c *configs.Cgroup, pid int) error { - _, err := join(c, "devices", pid) - // Even if it's `not found` error, we'll return err because devices cgroup - // is hard requirement for container security. - if err != nil { - return err - } - return nil -} - func setKernelMemory(c *configs.Cgroup) error { path, err := getSubsystemPath(c, "memory") if err != nil && !cgroups.IsNotFound(err) { @@ -545,52 +477,3 @@ func setKernelMemory(c *configs.Cgroup) error { s := &fs.MemoryGroup{} return s.SetKernelMemory(path, c) } - -func joinMemory(c *configs.Cgroup, pid int) error { - _, err := join(c, "memory", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} - -// systemd does not atm set up the cpuset controller, so we must manually -// join it. Additionally that is a very finicky controller where each -// level must have a full setup as the default for a new directory is "no cpus" -func joinCpuset(c *configs.Cgroup, pid int) error { - path, err := getSubsystemPath(c, "cpuset") - if err != nil && !cgroups.IsNotFound(err) { - return err - } - - s := &fs.CpusetGroup{} - - return s.ApplyDir(path, c, pid) -} - -// `BlockIODeviceWeight` property of systemd does not work properly, and systemd -// expects device path instead of major minor numbers, which is also confusing -// for users. So we use fs work around for now. -func joinBlkio(c *configs.Cgroup, pid int) error { - _, err := join(c, "blkio", pid) - if err != nil { - return err - } - return nil -} - -func joinHugetlb(c *configs.Cgroup, pid int) error { - _, err := join(c, "hugetlb", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} - -func joinPerfEvent(c *configs.Cgroup, pid int) error { - _, err := join(c, "perf_event", pid) - if err != nil && !cgroups.IsNotFound(err) { - return err - } - return nil -} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go index 88620aaee93f..235273299faf 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go @@ -5,6 +5,7 @@ package cgroups import ( "bufio" "fmt" + "io" "io/ioutil" "os" "path/filepath" @@ -12,7 +13,6 @@ import ( "strings" "time" - "github.com/docker/docker/pkg/mount" "github.com/docker/go-units" ) @@ -121,11 +121,45 @@ func (m Mount) GetThisCgroupDir(cgroups map[string]string) (string, error) { return getControllerPath(m.Subsystems[0], cgroups) } +func getCgroupMountsHelper(ss map[string]bool, mi io.Reader) ([]Mount, error) { + res := make([]Mount, 0, len(ss)) + scanner := bufio.NewScanner(mi) + for scanner.Scan() { + txt := scanner.Text() + sepIdx := strings.Index(txt, " - ") + if sepIdx == -1 { + return nil, fmt.Errorf("invalid mountinfo format") + } + if txt[sepIdx+3:sepIdx+9] != "cgroup" { + continue + } + fields := strings.Split(txt, " ") + m := Mount{ + Mountpoint: fields[4], + Root: fields[3], + } + for _, opt := range strings.Split(fields[len(fields)-1], ",") { + if strings.HasPrefix(opt, cgroupNamePrefix) { + m.Subsystems = append(m.Subsystems, opt[len(cgroupNamePrefix):]) + } + if ss[opt] { + m.Subsystems = append(m.Subsystems, opt) + } + } + res = append(res, m) + } + if err := scanner.Err(); err != nil { + return nil, err + } + return res, nil +} + func GetCgroupMounts() ([]Mount, error) { - mounts, err := mount.GetMounts() + f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } + defer f.Close() all, err := GetAllSubsystems() if err != nil { @@ -136,24 +170,7 @@ func GetCgroupMounts() ([]Mount, error) { for _, s := range all { allMap[s] = true } - - res := []Mount{} - for _, mount := range mounts { - if mount.Fstype == "cgroup" { - m := Mount{Mountpoint: mount.Mountpoint, Root: mount.Root} - - for _, opt := range strings.Split(mount.VfsOpts, ",") { - if strings.HasPrefix(opt, cgroupNamePrefix) { - m.Subsystems = append(m.Subsystems, opt[len(cgroupNamePrefix):]) - } - if allMap[opt] { - m.Subsystems = append(m.Subsystems, opt) - } - } - res = append(res, m) - } - } - return res, nil + return getCgroupMountsHelper(allMap, f) } // Returns all the cgroup subsystems supported by the kernel @@ -309,7 +326,7 @@ func RemovePaths(paths map[string]string) (err error) { return nil } } - return fmt.Errorf("Failed to remove paths: %s", paths) + return fmt.Errorf("Failed to remove paths: %v", paths) } func GetHugePageSize() ([]string, error) { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go index c186d289aca7..f2eff91cf45f 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go @@ -11,15 +11,22 @@ const ( ) type Cgroup struct { - Name string `json:"name"` + // Deprecated, use Path instead + Name string `json:"name,omitempty"` - // name of parent cgroup or slice - Parent string `json:"parent"` + // name of parent of cgroup or slice + // Deprecated, use Path instead + Parent string `json:"parent,omitempty"` + + // Path specifies the path to cgroups that are created and/or joined by the container. + // The path is assumed to be relative to the host system cgroup mountpoint. + Path string `json:"path"` // ScopePrefix decribes prefix for the scope name ScopePrefix string `json:"scope_prefix"` - // Paths represent the cgroups paths to join + // Paths represent the absolute cgroups paths to join. + // This takes precedence over Path. Paths map[string]string // Resources contains various cgroups settings to apply @@ -28,11 +35,14 @@ type Cgroup struct { type Resources struct { // If this is true allow access to any kind of device within the container. If false, allow access only to devices explicitly listed in the allowed_devices list. - AllowAllDevices bool `json:"allow_all_devices"` - - AllowedDevices []*Device `json:"allowed_devices"` + // Deprecated + AllowAllDevices bool `json:"allow_all_devices,omitempty"` + // Deprecated + AllowedDevices []*Device `json:"allowed_devices,omitempty"` + // Deprecated + DeniedDevices []*Device `json:"denied_devices,omitempty"` - DeniedDevices []*Device `json:"denied_devices"` + Devices []*Device `json:"devices"` // Memory limit (in bytes) Memory int64 `json:"memory"` @@ -46,6 +56,9 @@ type Resources struct { // Kernel memory limit (in bytes) KernelMemory int64 `json:"kernel_memory"` + // Kernel memory limit for TCP use (in bytes) + KernelMemoryTCP int64 `json:"kernel_memory_tcp"` + // CPU shares (relative weight vs. other containers) CpuShares int64 `json:"cpu_shares"` @@ -101,7 +114,7 @@ type Resources struct { OomKillDisable bool `json:"oom_kill_disable"` // Tuning swappiness behaviour per cgroup - MemorySwappiness int64 `json:"memory_swappiness"` + MemorySwappiness *int64 `json:"memory_swappiness"` // Set priority of network traffic for container NetPrioIfpriomap []*IfPrioMap `json:"net_prio_ifpriomap"` diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go index 069daae29351..1221ce272e04 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go @@ -3,7 +3,11 @@ package configs import ( "bytes" "encoding/json" + "fmt" "os/exec" + "time" + + "github.com/Sirupsen/logrus" ) type Rlimit struct { @@ -128,15 +132,15 @@ type Config struct { // AppArmorProfile specifies the profile to apply to the process running in the container and is // change at the time the process is execed - AppArmorProfile string `json:"apparmor_profile"` + AppArmorProfile string `json:"apparmor_profile,omitempty"` // ProcessLabel specifies the label to apply to the process running in the container. It is // commonly used by selinux - ProcessLabel string `json:"process_label"` + ProcessLabel string `json:"process_label,omitempty"` // Rlimits specifies the resource limits, such as max open files, to set in the container // If Rlimits are not set, the container will inherit rlimits from the parent process - Rlimits []Rlimit `json:"rlimits"` + Rlimits []Rlimit `json:"rlimits,omitempty"` // OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores // for a process. Valid values are between the range [-1000, '1000'], where processes with @@ -171,12 +175,18 @@ type Config struct { // A default action to be taken if no rules match is also given. Seccomp *Seccomp `json:"seccomp"` + // NoNewPrivileges controls whether processes in the container can gain additional privileges. + NoNewPrivileges bool `json:"no_new_privileges,omitempty"` + // Hooks are a collection of actions to perform at various container lifecycle events. - // Hooks are not able to be marshaled to json but they are also not needed to. - Hooks *Hooks `json:"-"` + // CommandHooks are serialized to JSON, but other hooks are not. + Hooks *Hooks // Version is the version of opencontainer specification that is supported. Version string `json:"version"` + + // Labels are user defined metadata that is stored in the config and populated on the state + Labels []string `json:"labels"` } type Hooks struct { @@ -191,12 +201,59 @@ type Hooks struct { Poststop []Hook } +func (hooks *Hooks) UnmarshalJSON(b []byte) error { + var state struct { + Prestart []CommandHook + Poststart []CommandHook + Poststop []CommandHook + } + + if err := json.Unmarshal(b, &state); err != nil { + return err + } + + deserialize := func(shooks []CommandHook) (hooks []Hook) { + for _, shook := range shooks { + hooks = append(hooks, shook) + } + + return hooks + } + + hooks.Prestart = deserialize(state.Prestart) + hooks.Poststart = deserialize(state.Poststart) + hooks.Poststop = deserialize(state.Poststop) + return nil +} + +func (hooks Hooks) MarshalJSON() ([]byte, error) { + serialize := func(hooks []Hook) (serializableHooks []CommandHook) { + for _, hook := range hooks { + switch chook := hook.(type) { + case CommandHook: + serializableHooks = append(serializableHooks, chook) + default: + logrus.Warnf("cannot serialize hook of type %T, skipping", hook) + } + } + + return serializableHooks + } + + return json.Marshal(map[string]interface{}{ + "prestart": serialize(hooks.Prestart), + "poststart": serialize(hooks.Poststart), + "poststop": serialize(hooks.Poststop), + }) +} + // HookState is the payload provided to a hook on execution. type HookState struct { - Version string `json:"version"` - ID string `json:"id"` - Pid int `json:"pid"` - Root string `json:"root"` + Version string `json:"ociVersion"` + ID string `json:"id"` + Pid int `json:"pid"` + Root string `json:"root"` + BundlePath string `json:"bundlePath"` } type Hook interface { @@ -220,10 +277,11 @@ func (f FuncHook) Run(s HookState) error { } type Command struct { - Path string `json:"path"` - Args []string `json:"args"` - Env []string `json:"env"` - Dir string `json:"dir"` + Path string `json:"path"` + Args []string `json:"args"` + Env []string `json:"env"` + Dir string `json:"dir"` + Timeout *time.Duration `json:"timeout"` } // NewCommandHooks will execute the provided command when the hook is run. @@ -248,5 +306,23 @@ func (c Command) Run(s HookState) error { Env: c.Env, Stdin: bytes.NewReader(b), } - return cmd.Run() + errC := make(chan error, 1) + go func() { + out, err := cmd.CombinedOutput() + if err != nil { + err = fmt.Errorf("%s: %s", err, out) + } + errC <- err + }() + if c.Timeout != nil { + select { + case err := <-errC: + return err + case <-time.After(*c.Timeout): + cmd.Process.Kill() + cmd.Wait() + return fmt.Errorf("hook ran past specified timeout of %.1fs", c.Timeout.Seconds()) + } + } + return <-errC } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go index a52a024af1ed..8701bb212d7b 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go @@ -35,6 +35,9 @@ type Device struct { // Gid of the device. Gid uint32 `json:"gid"` + + // Write the file to the allowed list + Allow bool `json:"allow"` } func (d *Device) CgroupString() string { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go index c962999efd4b..fb4b8522223c 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go @@ -18,7 +18,7 @@ var namespaceInfo = map[NamespaceType]int{ } // CloneFlags parses the container's Namespaces options to set the correct -// flags on clone, unshare. This functions returns flags only for new namespaces. +// flags on clone, unshare. This function returns flags only for new namespaces. func (n *Namespaces) CloneFlags() uintptr { var flag int for _, v := range *n { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go index 1644588dc79d..0547223a9db4 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go @@ -8,7 +8,7 @@ func (n *Namespace) Syscall() int { } // CloneFlags parses the container's Namespaces options to set the correct -// flags on clone, unshare. This functions returns flags only for new namespaces. +// flags on clone, unshare. This function returns flags only for new namespaces. func (n *Namespaces) CloneFlags() uintptr { panic("No namespace syscall support") return uintptr(0) diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go index 7bc9085468d3..b9c820d0627d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go @@ -2,7 +2,11 @@ package configs -import "fmt" +import ( + "fmt" + "os" + "sync" +) const ( NEWNET NamespaceType = "NEWNET" @@ -13,6 +17,51 @@ const ( NEWUSER NamespaceType = "NEWUSER" ) +var ( + nsLock sync.Mutex + supportedNamespaces = make(map[NamespaceType]bool) +) + +// nsToFile converts the namespace type to its filename +func nsToFile(ns NamespaceType) string { + switch ns { + case NEWNET: + return "net" + case NEWNS: + return "mnt" + case NEWPID: + return "pid" + case NEWIPC: + return "ipc" + case NEWUSER: + return "user" + case NEWUTS: + return "uts" + } + return "" +} + +// IsNamespaceSupported returns whether a namespace is available or +// not +func IsNamespaceSupported(ns NamespaceType) bool { + nsLock.Lock() + defer nsLock.Unlock() + supported, ok := supportedNamespaces[ns] + if ok { + return supported + } + nsFile := nsToFile(ns) + // if the namespace type is unknown, just return false + if nsFile == "" { + return false + } + _, err := os.Stat(fmt.Sprintf("/proc/self/ns/%s", nsFile)) + // a namespace is supported if it exists and we have permissions to read it + supported = err == nil + supportedNamespaces[ns] = supported + return supported +} + func NamespaceTypes() []NamespaceType { return []NamespaceType{ NEWNET, @@ -35,26 +84,7 @@ func (n *Namespace) GetPath(pid int) string { if n.Path != "" { return n.Path } - return fmt.Sprintf("/proc/%d/ns/%s", pid, n.file()) -} - -func (n *Namespace) file() string { - file := "" - switch n.Type { - case NEWNET: - file = "net" - case NEWNS: - file = "mnt" - case NEWPID: - file = "pid" - case NEWIPC: - file = "ipc" - case NEWUSER: - file = "user" - case NEWUTS: - file = "uts" - } - return file + return fmt.Sprintf("/proc/%d/ns/%s", pid, nsToFile(n.Type)) } func (n *Namespaces) Remove(t NamespaceType) bool { @@ -87,3 +117,11 @@ func (n *Namespaces) index(t NamespaceType) int { func (n *Namespaces) Contains(t NamespaceType) bool { return n.index(t) != -1 } + +func (n *Namespaces) PathOf(t NamespaceType) string { + i := n.index(t) + if i == -1 { + return "" + } + return (*n)[i].Path +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go similarity index 63% rename from vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go rename to vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go index 848a67c343a1..bd6964c56e8c 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/opencontainers/runc/libcontainer/configs" ) @@ -35,10 +36,13 @@ func (v *ConfigValidator) Validate(config *configs.Config) error { if err := v.usernamespace(config); err != nil { return err } + if err := v.sysctl(config); err != nil { + return err + } return nil } -// rootfs validates the the rootfs is an absolute path and is not a symlink +// rootfs validates if the rootfs is an absolute path and is not a symlink // to the container's root filesystem. func (v *ConfigValidator) rootfs(config *configs.Config) error { cleaned, err := filepath.Abs(config.Rootfs) @@ -48,7 +52,7 @@ func (v *ConfigValidator) rootfs(config *configs.Config) error { if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil { return err } - if config.Rootfs != cleaned { + if filepath.Clean(config.Rootfs) != cleaned { return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs) } return nil @@ -91,3 +95,39 @@ func (v *ConfigValidator) usernamespace(config *configs.Config) error { } return nil } + +// sysctl validates that the specified sysctl keys are valid or not. +// /proc/sys isn't completely namespaced and depending on which namespaces +// are specified, a subset of sysctls are permitted. +func (v *ConfigValidator) sysctl(config *configs.Config) error { + validSysctlMap := map[string]bool{ + "kernel.msgmax": true, + "kernel.msgmnb": true, + "kernel.msgmni": true, + "kernel.sem": true, + "kernel.shmall": true, + "kernel.shmmax": true, + "kernel.shmmni": true, + "kernel.shm_rmid_forced": true, + } + + for s := range config.Sysctl { + if validSysctlMap[s] || strings.HasPrefix(s, "fs.mqueue.") { + if config.Namespaces.Contains(configs.NEWIPC) { + continue + } else { + return fmt.Errorf("sysctl %q is not allowed in the hosts ipc namespace", s) + } + } + if strings.HasPrefix(s, "net.") { + if config.Namespaces.Contains(configs.NEWNET) { + continue + } else { + return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", s) + } + } + return fmt.Errorf("sysctl %q is not in a separate kernel namespace", s) + } + + return nil +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container.go b/vendor/github.com/opencontainers/runc/libcontainer/container.go index 03c8c559322b..32daa97675a9 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/container.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/container.go @@ -6,6 +6,7 @@ package libcontainer import ( "os" + "time" "github.com/opencontainers/runc/libcontainer/configs" ) @@ -26,9 +27,6 @@ const ( // The container exists, but all its processes are paused. Paused - // The container exists, but its state is saved on disk - Checkpointed - // The container does not exist. Destroyed ) @@ -43,8 +41,6 @@ func (s Status) String() string { return "pausing" case Paused: return "paused" - case Checkpointed: - return "checkpointed" case Destroyed: return "destroyed" default: @@ -61,9 +57,12 @@ type BaseState struct { // InitProcessPid is the init process id in the parent namespace. InitProcessPid int `json:"init_process_pid"` - // InitProcessStartTime is the init process start time. + // InitProcessStartTime is the init process start time in clock cycles since boot time. InitProcessStartTime string `json:"init_process_start"` + // Created is the unix timestamp for the creation time of the container in UTC + Created time.Time `json:"created"` + // Config is the container's configuration. Config configs.Config `json:"config"` } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go index 4015c9576281..2ae50c465c5d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go @@ -15,6 +15,7 @@ import ( "strings" "sync" "syscall" + "time" "github.com/Sirupsen/logrus" "github.com/golang/protobuf/proto" @@ -22,6 +23,7 @@ import ( "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/criurpc" "github.com/opencontainers/runc/libcontainer/utils" + "github.com/syndtr/gocapability/capability" "github.com/vishvananda/netlink/nl" ) @@ -39,6 +41,7 @@ type linuxContainer struct { m sync.Mutex criuVersion int state containerState + created time.Time } // State represents a running container's state @@ -75,7 +78,7 @@ type Container interface { // Systemerror - System error. Checkpoint(criuOpts *CriuOpts) error - // Restore restores the checkpointed container to a running state using the criu(8) utiity. + // Restore restores the checkpointed container to a running state using the criu(8) utility. // // errors: // Systemerror - System error. @@ -190,6 +193,9 @@ func (c *linuxContainer) Start(process *Process) error { } return newSystemError(err) } + // generate a timestamp indicating when the container was started + c.created = time.Now().UTC() + c.state = &runningState{ c: c, } @@ -199,10 +205,11 @@ func (c *linuxContainer) Start(process *Process) error { } if c.config.Hooks != nil { s := configs.HookState{ - Version: c.config.Version, - ID: c.id, - Pid: parent.pid(), - Root: c.config.Rootfs, + Version: c.config.Version, + ID: c.id, + Pid: parent.pid(), + Root: c.config.Rootfs, + BundlePath: utils.SearchLabels(c.config.Labels, "bundle"), } for _, hook := range c.config.Hooks.Poststart { if err := hook.Run(s); err != nil { @@ -263,37 +270,40 @@ func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec. } func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*initProcess, error) { - t := "_LIBCONTAINER_INITTYPE=" + string(initStandard) - cloneFlags := c.config.Namespaces.CloneFlags() - if cloneFlags&syscall.CLONE_NEWUSER != 0 { - if err := c.addUidGidMappings(cmd.SysProcAttr); err != nil { - // user mappings are not supported - return nil, err - } - enableSetgroups(cmd.SysProcAttr) - // Default to root user when user namespaces are enabled. - if cmd.SysProcAttr.Credential == nil { - cmd.SysProcAttr.Credential = &syscall.Credential{} + cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard)) + nsMaps := make(map[configs.NamespaceType]string) + for _, ns := range c.config.Namespaces { + if ns.Path != "" { + nsMaps[ns.Type] = ns.Path } } - cmd.Env = append(cmd.Env, t) - cmd.SysProcAttr.Cloneflags = cloneFlags + _, sharePidns := nsMaps[configs.NEWPID] + data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps, "") + if err != nil { + return nil, err + } return &initProcess{ - cmd: cmd, - childPipe: childPipe, - parentPipe: parentPipe, - manager: c.cgroupManager, - config: c.newInitConfig(p), - container: c, - process: p, + cmd: cmd, + childPipe: childPipe, + parentPipe: parentPipe, + manager: c.cgroupManager, + config: c.newInitConfig(p), + container: c, + process: p, + bootstrapData: data, + sharePidns: sharePidns, }, nil } func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*setnsProcess, error) { cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initSetns)) + state, err := c.currentState() + if err != nil { + return nil, newSystemError(err) + } // for setns process, we dont have to set cloneflags as the process namespaces // will only be set via setns syscall - data, err := c.bootstrapData(0, c.initProcess.pid(), p.consolePath) + data, err := c.bootstrapData(0, state.NamespacePaths, p.consolePath) if err != nil { return nil, err } @@ -310,7 +320,7 @@ func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, } func (c *linuxContainer) newInitConfig(process *Process) *initConfig { - return &initConfig{ + cfg := &initConfig{ Config: c.config, Args: process.Args, Env: process.Env, @@ -319,7 +329,25 @@ func (c *linuxContainer) newInitConfig(process *Process) *initConfig { Console: process.consolePath, Capabilities: process.Capabilities, PassedFilesCount: len(process.ExtraFiles), + ContainerId: c.ID(), + NoNewPrivileges: c.config.NoNewPrivileges, + AppArmorProfile: c.config.AppArmorProfile, + ProcessLabel: c.config.ProcessLabel, + Rlimits: c.config.Rlimits, } + if process.NoNewPrivileges != nil { + cfg.NoNewPrivileges = *process.NoNewPrivileges + } + if process.AppArmorProfile != "" { + cfg.AppArmorProfile = process.AppArmorProfile + } + if process.Label != "" { + cfg.ProcessLabel = process.Label + } + if len(process.Rlimits) > 0 { + cfg.Rlimits = process.Rlimits + } + return cfg } func newPipe() (parent *os.File, child *os.File, err error) { @@ -380,16 +408,6 @@ func (c *linuxContainer) NotifyMemoryPressure(level PressureLevel) (<-chan struc return notifyMemoryPressure(c.cgroupManager.GetPaths(), level) } -// XXX debug support, remove when debugging done. -func addArgsFromEnv(evar string, args *[]string) { - if e := os.Getenv(evar); e != "" { - for _, f := range strings.Fields(e) { - *args = append(*args, f) - } - } - fmt.Printf(">>> criu %v\n", *args) -} - // check Criu version greater than or equal to min_version func (c *linuxContainer) checkCriuVersion(min_version string) error { var x, y, z, versionReq int @@ -514,6 +532,7 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error { TcpEstablished: proto.Bool(criuOpts.TcpEstablished), ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections), FileLocks: proto.Bool(criuOpts.FileLocks), + EmptyNs: proto.Uint32(criuOpts.EmptyNs), } // append optional criu opts, e.g., page-server and port @@ -529,7 +548,8 @@ func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error { if err := c.checkCriuVersion("1.7"); err != nil { return err } - rpcOpts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode)) + mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode) + rpcOpts.ManageCgroupsMode = &mode } t := criurpc.CriuReqType_DUMP @@ -650,6 +670,7 @@ func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error { ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections), TcpEstablished: proto.Bool(criuOpts.TcpEstablished), FileLocks: proto.Bool(criuOpts.FileLocks), + EmptyNs: proto.Uint32(criuOpts.EmptyNs), }, } @@ -693,7 +714,8 @@ func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error { if err := c.checkCriuVersion("1.7"); err != nil { return err } - req.Opts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode)) + mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode) + req.Opts.ManageCgroupsMode = &mode } var ( @@ -850,7 +872,7 @@ func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts * if err != nil { return err } - n, err = criuClient.Write(data) + _, err = criuClient.Write(data) if err != nil { return err } @@ -925,6 +947,20 @@ func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Proc if err := lockNetwork(c.config); err != nil { return err } + case notify.GetScript() == "setup-namespaces": + if c.config.Hooks != nil { + s := configs.HookState{ + Version: c.config.Version, + ID: c.id, + Pid: int(notify.GetPid()), + Root: c.config.Rootfs, + } + for _, hook := range c.config.Hooks.Prestart { + if err := hook.Run(s); err != nil { + return newSystemError(err) + } + } + } case notify.GetScript() == "post-restore": pid := notify.GetPid() r, err := newRestoredProcess(int(pid), fds) @@ -1043,6 +1079,7 @@ func (c *linuxContainer) currentState() (*State, error) { Config: *c.config, InitProcessPid: pid, InitProcessStartTime: startTime, + Created: c.created, }, CgroupPaths: c.cgroupManager.GetPaths(), NamespacePaths: make(map[configs.NamespaceType]string), @@ -1053,6 +1090,9 @@ func (c *linuxContainer) currentState() (*State, error) { state.NamespacePaths[ns.Type] = ns.GetPath(pid) } for _, nsType := range configs.NamespaceTypes() { + if !configs.IsNamespaceSupported(nsType) { + continue + } if _, ok := state.NamespacePaths[nsType]; !ok { ns := configs.Namespace{Type: nsType} state.NamespacePaths[ns.Type] = ns.GetPath(pid) @@ -1062,18 +1102,69 @@ func (c *linuxContainer) currentState() (*State, error) { return state, nil } -// bootstrapData encodes the necessary data in netlink binary format as a io.Reader. -// Consumer can write the data to a bootstrap program such as one that uses -// nsenter package to bootstrap the container's init process correctly, i.e. with -// correct namespaces, uid/gid mapping etc. -func (c *linuxContainer) bootstrapData(cloneFlags uintptr, pid int, consolePath string) (io.Reader, error) { +// orderNamespacePaths sorts namespace paths into a list of paths that we +// can setns in order. +func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) { + paths := []string{} + nsTypes := []configs.NamespaceType{ + configs.NEWIPC, + configs.NEWUTS, + configs.NEWNET, + configs.NEWPID, + configs.NEWNS, + } + // join userns if the init process explicitly requires NEWUSER + if c.config.Namespaces.Contains(configs.NEWUSER) { + nsTypes = append(nsTypes, configs.NEWUSER) + } + for _, nsType := range nsTypes { + if p, ok := namespaces[nsType]; ok && p != "" { + // check if the requested namespace is supported + if !configs.IsNamespaceSupported(nsType) { + return nil, newSystemError(fmt.Errorf("namespace %s is not supported", nsType)) + } + // only set to join this namespace if it exists + if _, err := os.Lstat(p); err != nil { + return nil, newSystemError(err) + } + // do not allow namespace path with comma as we use it to separate + // the namespace paths + if strings.ContainsRune(p, ',') { + return nil, newSystemError(fmt.Errorf("invalid path %s", p)) + } + paths = append(paths, p) + } + } + return paths, nil +} + +func encodeIDMapping(idMap []configs.IDMap) ([]byte, error) { + data := bytes.NewBuffer(nil) + for _, im := range idMap { + line := fmt.Sprintf("%d %d %d\n", im.ContainerID, im.HostID, im.Size) + if _, err := data.WriteString(line); err != nil { + return nil, err + } + } + return data.Bytes(), nil +} + +// bootstrapData encodes the necessary data in netlink binary format +// as a io.Reader. +// Consumer can write the data to a bootstrap program +// such as one that uses nsenter package to bootstrap the container's +// init process correctly, i.e. with correct namespaces, uid/gid +// mapping etc. +func (c *linuxContainer) bootstrapData(cloneFlags uintptr, nsMaps map[configs.NamespaceType]string, consolePath string) (io.Reader, error) { // create the netlink message r := nl.NewNetlinkRequest(int(InitMsg), 0) - // write pid + + // write cloneFlags r.AddData(&Int32msg{ - Type: PidAttr, - Value: uint32(pid), + Type: CloneFlagsAttr, + Value: uint32(cloneFlags), }) + // write console path if consolePath != "" { r.AddData(&Bytemsg{ @@ -1081,5 +1172,57 @@ func (c *linuxContainer) bootstrapData(cloneFlags uintptr, pid int, consolePath Value: []byte(consolePath), }) } + + // write custom namespace paths + if len(nsMaps) > 0 { + nsPaths, err := c.orderNamespacePaths(nsMaps) + if err != nil { + return nil, err + } + r.AddData(&Bytemsg{ + Type: NsPathsAttr, + Value: []byte(strings.Join(nsPaths, ",")), + }) + } + + // write namespace paths only when we are not joining an existing user ns + _, joinExistingUser := nsMaps[configs.NEWUSER] + if !joinExistingUser { + // write uid mappings + if len(c.config.UidMappings) > 0 { + b, err := encodeIDMapping(c.config.UidMappings) + if err != nil { + return nil, err + } + r.AddData(&Bytemsg{ + Type: UidmapAttr, + Value: b, + }) + } + + // write gid mappings + if len(c.config.GidMappings) > 0 { + b, err := encodeIDMapping(c.config.GidMappings) + if err != nil { + return nil, err + } + r.AddData(&Bytemsg{ + Type: GidmapAttr, + Value: b, + }) + // check if we have CAP_SETGID to setgroup properly + pid, err := capability.NewPid(os.Getpid()) + if err != nil { + return nil, err + } + if !pid.Get(capability.EFFECTIVE, capability.CAP_SETGID) { + r.AddData(&Boolmsg{ + Type: SetgroupAttr, + Value: true, + }) + } + } + } + return bytes.NewReader(r.Serialize()), nil } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go deleted file mode 100644 index 3b75d593ccb3..000000000000 --- a/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !go1.4 - -package libcontainer - -import ( - "fmt" - "syscall" -) - -// not available before go 1.4 -func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error { - return fmt.Errorf("User namespace is not supported in golang < 1.4") -} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go deleted file mode 100644 index 5f4cf3c9fee5..000000000000 --- a/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build go1.4 - -package libcontainer - -import "syscall" - -// Converts IDMap to SysProcIDMap array and adds it to SysProcAttr. -func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error { - if c.config.UidMappings != nil { - sys.UidMappings = make([]syscall.SysProcIDMap, len(c.config.UidMappings)) - for i, um := range c.config.UidMappings { - sys.UidMappings[i].ContainerID = um.ContainerID - sys.UidMappings[i].HostID = um.HostID - sys.UidMappings[i].Size = um.Size - } - } - if c.config.GidMappings != nil { - sys.GidMappings = make([]syscall.SysProcIDMap, len(c.config.GidMappings)) - for i, gm := range c.config.GidMappings { - sys.GidMappings[i].ContainerID = gm.ContainerID - sys.GidMappings[i].HostID = gm.HostID - sys.GidMappings[i].Size = gm.Size - } - } - return nil -} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go index a2a816bd952e..133238583b54 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go @@ -33,4 +33,5 @@ type CriuOpts struct { PageServer CriuPageServerInfo // allow to dump to criu page server VethPairs []VethPairName // pass the veth to criu when restore ManageCgroupsMode cg_mode // dump or restore cgroup mode + EmptyNs uint32 // don't c/r properties for namespace from this mask } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go index 193b6df1db27..3c4fb7732616 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go @@ -19,6 +19,7 @@ It has these top-level messages: CriuDumpResp CriuRestoreResp CriuNotify + CriuFeatures CriuReq CriuResp */ @@ -31,6 +32,54 @@ import math "math" var _ = proto.Marshal var _ = math.Inf +type CriuCgMode int32 + +const ( + CriuCgMode_IGNORE CriuCgMode = 0 + CriuCgMode_NONE CriuCgMode = 1 + CriuCgMode_PROPS CriuCgMode = 2 + CriuCgMode_SOFT CriuCgMode = 3 + CriuCgMode_FULL CriuCgMode = 4 + CriuCgMode_STRICT CriuCgMode = 5 + CriuCgMode_DEFAULT CriuCgMode = 6 +) + +var CriuCgMode_name = map[int32]string{ + 0: "IGNORE", + 1: "NONE", + 2: "PROPS", + 3: "SOFT", + 4: "FULL", + 5: "STRICT", + 6: "DEFAULT", +} +var CriuCgMode_value = map[string]int32{ + "IGNORE": 0, + "NONE": 1, + "PROPS": 2, + "SOFT": 3, + "FULL": 4, + "STRICT": 5, + "DEFAULT": 6, +} + +func (x CriuCgMode) Enum() *CriuCgMode { + p := new(CriuCgMode) + *p = x + return p +} +func (x CriuCgMode) String() string { + return proto.EnumName(CriuCgMode_name, int32(x)) +} +func (x *CriuCgMode) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(CriuCgMode_value, data, "CriuCgMode") + if err != nil { + return err + } + *x = CriuCgMode(value) + return nil +} + type CriuReqType int32 const ( @@ -43,6 +92,7 @@ const ( CriuReqType_NOTIFY CriuReqType = 6 CriuReqType_CPUINFO_DUMP CriuReqType = 7 CriuReqType_CPUINFO_CHECK CriuReqType = 8 + CriuReqType_FEATURE_CHECK CriuReqType = 9 ) var CriuReqType_name = map[int32]string{ @@ -55,6 +105,7 @@ var CriuReqType_name = map[int32]string{ 6: "NOTIFY", 7: "CPUINFO_DUMP", 8: "CPUINFO_CHECK", + 9: "FEATURE_CHECK", } var CriuReqType_value = map[string]int32{ "EMPTY": 0, @@ -66,6 +117,7 @@ var CriuReqType_value = map[string]int32{ "NOTIFY": 6, "CPUINFO_DUMP": 7, "CPUINFO_CHECK": 8, + "FEATURE_CHECK": 9, } func (x CriuReqType) Enum() *CriuReqType { @@ -271,7 +323,12 @@ type CriuOpts struct { SkipMnt []string `protobuf:"bytes,31,rep,name=skip_mnt" json:"skip_mnt,omitempty"` EnableFs []string `protobuf:"bytes,32,rep,name=enable_fs" json:"enable_fs,omitempty"` UnixSkIno []*UnixSk `protobuf:"bytes,33,rep,name=unix_sk_ino" json:"unix_sk_ino,omitempty"` - ManageCgroupsMode *uint32 `protobuf:"varint,34,opt,name=manage_cgroups_mode" json:"manage_cgroups_mode,omitempty"` + ManageCgroupsMode *CriuCgMode `protobuf:"varint,34,opt,name=manage_cgroups_mode,enum=CriuCgMode" json:"manage_cgroups_mode,omitempty"` + GhostLimit *uint32 `protobuf:"varint,35,opt,name=ghost_limit,def=1048576" json:"ghost_limit,omitempty"` + IrmapScanPaths []string `protobuf:"bytes,36,rep,name=irmap_scan_paths" json:"irmap_scan_paths,omitempty"` + External []string `protobuf:"bytes,37,rep,name=external" json:"external,omitempty"` + EmptyNs *uint32 `protobuf:"varint,38,opt,name=empty_ns" json:"empty_ns,omitempty"` + NoSeccomp *bool `protobuf:"varint,39,opt,name=no_seccomp" json:"no_seccomp,omitempty"` XXX_unrecognized []byte `json:"-"` } @@ -281,6 +338,7 @@ func (*CriuOpts) ProtoMessage() {} const Default_CriuOpts_LogLevel int32 = 2 const Default_CriuOpts_CpuCap uint32 = 4294967295 +const Default_CriuOpts_GhostLimit uint32 = 1048576 func (m *CriuOpts) GetImagesDirFd() int32 { if m != nil && m.ImagesDirFd != nil { @@ -513,13 +571,48 @@ func (m *CriuOpts) GetUnixSkIno() []*UnixSk { return nil } -func (m *CriuOpts) GetManageCgroupsMode() uint32 { +func (m *CriuOpts) GetManageCgroupsMode() CriuCgMode { if m != nil && m.ManageCgroupsMode != nil { return *m.ManageCgroupsMode } + return CriuCgMode_IGNORE +} + +func (m *CriuOpts) GetGhostLimit() uint32 { + if m != nil && m.GhostLimit != nil { + return *m.GhostLimit + } + return Default_CriuOpts_GhostLimit +} + +func (m *CriuOpts) GetIrmapScanPaths() []string { + if m != nil { + return m.IrmapScanPaths + } + return nil +} + +func (m *CriuOpts) GetExternal() []string { + if m != nil { + return m.External + } + return nil +} + +func (m *CriuOpts) GetEmptyNs() uint32 { + if m != nil && m.EmptyNs != nil { + return *m.EmptyNs + } return 0 } +func (m *CriuOpts) GetNoSeccomp() bool { + if m != nil && m.NoSeccomp != nil { + return *m.NoSeccomp + } + return false +} + type CriuDumpResp struct { Restored *bool `protobuf:"varint,1,opt,name=restored" json:"restored,omitempty"` XXX_unrecognized []byte `json:"-"` @@ -576,6 +669,25 @@ func (m *CriuNotify) GetPid() int32 { return 0 } +// +// List of features which can queried via +// CRIU_REQ_TYPE__FEATURE_CHECK +type CriuFeatures struct { + MemTrack *bool `protobuf:"varint,1,opt,name=mem_track" json:"mem_track,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CriuFeatures) Reset() { *m = CriuFeatures{} } +func (m *CriuFeatures) String() string { return proto.CompactTextString(m) } +func (*CriuFeatures) ProtoMessage() {} + +func (m *CriuFeatures) GetMemTrack() bool { + if m != nil && m.MemTrack != nil { + return *m.MemTrack + } + return false +} + type CriuReq struct { Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"` Opts *CriuOpts `protobuf:"bytes,2,opt,name=opts" json:"opts,omitempty"` @@ -584,8 +696,13 @@ type CriuReq struct { // When set service won't close the connection but // will wait for more req-s to appear. Works not // for all request types. - KeepOpen *bool `protobuf:"varint,4,opt,name=keep_open" json:"keep_open,omitempty"` - XXX_unrecognized []byte `json:"-"` + KeepOpen *bool `protobuf:"varint,4,opt,name=keep_open" json:"keep_open,omitempty"` + // + // 'features' can be used to query which features + // are supported by the installed criu/kernel + // via RPC. + Features *CriuFeatures `protobuf:"bytes,5,opt,name=features" json:"features,omitempty"` + XXX_unrecognized []byte `json:"-"` } func (m *CriuReq) Reset() { *m = CriuReq{} } @@ -620,6 +737,13 @@ func (m *CriuReq) GetKeepOpen() bool { return false } +func (m *CriuReq) GetFeatures() *CriuFeatures { + if m != nil { + return m.Features + } + return nil +} + type CriuResp struct { Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"` Success *bool `protobuf:"varint,2,req,name=success" json:"success,omitempty"` @@ -628,6 +752,7 @@ type CriuResp struct { Notify *CriuNotify `protobuf:"bytes,5,opt,name=notify" json:"notify,omitempty"` Ps *CriuPageServerInfo `protobuf:"bytes,6,opt,name=ps" json:"ps,omitempty"` CrErrno *int32 `protobuf:"varint,7,opt,name=cr_errno" json:"cr_errno,omitempty"` + Features *CriuFeatures `protobuf:"bytes,8,opt,name=features" json:"features,omitempty"` XXX_unrecognized []byte `json:"-"` } @@ -684,6 +809,14 @@ func (m *CriuResp) GetCrErrno() int32 { return 0 } +func (m *CriuResp) GetFeatures() *CriuFeatures { + if m != nil { + return m.Features + } + return nil +} + func init() { + proto.RegisterEnum("CriuCgMode", CriuCgMode_name, CriuCgMode_value) proto.RegisterEnum("CriuReqType", CriuReqType_name, CriuReqType_value) } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto index f49325e27058..34fa988441f6 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto +++ b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto @@ -29,6 +29,16 @@ message unix_sk { required uint32 inode = 1; }; +enum criu_cg_mode { + IGNORE = 0; + NONE = 1; + PROPS = 2; + SOFT = 3; + FULL = 4; + STRICT = 5; + DEFAULT = 6; +}; + message criu_opts { required int32 images_dir_fd = 1; optional int32 pid = 2; /* if not set on dump, will dump requesting process */ @@ -75,7 +85,12 @@ message criu_opts { repeated unix_sk unix_sk_ino = 33; - optional uint32 manage_cgroups_mode = 34; + optional criu_cg_mode manage_cgroups_mode = 34; + optional uint32 ghost_limit = 35 [default = 0x100000]; + repeated string irmap_scan_paths = 36; + repeated string external = 37; + optional uint32 empty_ns = 38; + optional bool no_seccomp = 39; } message criu_dump_resp { @@ -103,6 +118,16 @@ enum criu_req_type { CPUINFO_DUMP = 7; CPUINFO_CHECK = 8; + + FEATURE_CHECK = 9; +} + +/* + * List of features which can queried via + * CRIU_REQ_TYPE__FEATURE_CHECK + */ +message criu_features { + optional bool mem_track = 1; } /* @@ -122,11 +147,17 @@ message criu_req { * for all request types. */ optional bool keep_open = 4; + /* + * 'features' can be used to query which features + * are supported by the installed criu/kernel + * via RPC. + */ + optional criu_features features = 5; } /* - * Responce -- it states whether the request was served - * and additional request-specific informarion + * Response -- it states whether the request was served + * and additional request-specific information */ message criu_resp { @@ -139,4 +170,5 @@ message criu_resp { optional criu_page_server_info ps = 6; optional int32 cr_errno = 7; + optional criu_features features = 8; } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/error.go b/vendor/github.com/opencontainers/runc/libcontainer/error.go index 378ef469434b..b50aaae84ed5 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/error.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/error.go @@ -19,7 +19,7 @@ const ( ContainerNotPaused // Process errors - ProcessNotExecuted + NoProcessOps // Common errors ConfigInvalid @@ -49,6 +49,8 @@ func (c ErrorCode) String() string { return "Console exists for process" case ContainerNotPaused: return "Container is not paused" + case NoProcessOps: + return "No process operations" default: return "Unknown error" } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go index 0e4e9dfd5abf..e67b001fb0d0 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go @@ -9,6 +9,7 @@ import ( "os/exec" "path/filepath" "regexp" + "runtime/debug" "strconv" "syscall" @@ -26,7 +27,7 @@ const ( ) var ( - idRegex = regexp.MustCompile(`^[\w_-]+$`) + idRegex = regexp.MustCompile(`^[\w-\.]+$`) maxIdLen = 1024 ) @@ -202,6 +203,7 @@ func (l *LinuxFactory) Load(id string) (Container, error) { criuPath: l.CriuPath, cgroupManager: l.NewCgroupsManager(state.Config.Cgroups, state.CgroupPaths), root: containerRoot, + created: state.Created, } c.state = &createdState{c: c, s: Created} if err := c.refreshState(); err != nil { @@ -231,26 +233,29 @@ func (l *LinuxFactory) StartInitialization() (err error) { os.Clearenv() var i initer defer func() { - // if we have an error during the initialization of the container's init then send it back to the - // parent process in the form of an initError. - if err != nil { - if _, ok := i.(*linuxStandardInit); ok { - // Synchronisation only necessary for standard init. - if err := utils.WriteJSON(pipe, syncT{procError}); err != nil { - panic(err) - } - } - if err := utils.WriteJSON(pipe, newSystemError(err)); err != nil { - panic(err) - } - } else { - if err := utils.WriteJSON(pipe, syncT{procStart}); err != nil { + // We have an error during the initialization of the container's init, + // send it back to the parent process in the form of an initError. + // If container's init successed, syscall.Exec will not return, hence + // this defer function will never be called. + if _, ok := i.(*linuxStandardInit); ok { + // Synchronisation only necessary for standard init. + if err := utils.WriteJSON(pipe, syncT{procError}); err != nil { panic(err) } } + if err := utils.WriteJSON(pipe, newSystemError(err)); err != nil { + panic(err) + } // ensure that this pipe is always closed pipe.Close() }() + + defer func() { + if e := recover(); e != nil { + err = fmt.Errorf("panic from initialization: %v, %v", e, string(debug.Stack())) + } + }() + i, err = newContainerInit(it, pipe) if err != nil { return err diff --git a/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go b/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go index 924d637b25d9..3ed33da6d170 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go @@ -1,7 +1,6 @@ package libcontainer import ( - "fmt" "io" "text/template" "time" @@ -14,8 +13,9 @@ type syncType uint8 const ( procReady syncType = iota procError - procStart procRun + procHooks + procResume ) type syncT struct { @@ -75,7 +75,7 @@ type genericError struct { } func (e *genericError) Error() string { - return fmt.Sprintf("[%d] %s: %s", e.ECode, e.ECode, e.Message) + return e.Message } func (e *genericError) Code() ErrorCode { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go index 918f1030167b..0bde656e2922 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go @@ -44,15 +44,20 @@ type network struct { // initConfig is used for transferring parameters from Exec() to Init() type initConfig struct { - Args []string `json:"args"` - Env []string `json:"env"` - Cwd string `json:"cwd"` - Capabilities []string `json:"capabilities"` - User string `json:"user"` - Config *configs.Config `json:"config"` - Console string `json:"console"` - Networks []*network `json:"network"` - PassedFilesCount int `json:"passed_files_count"` + Args []string `json:"args"` + Env []string `json:"env"` + Cwd string `json:"cwd"` + Capabilities []string `json:"capabilities"` + ProcessLabel string `json:"process_label"` + AppArmorProfile string `json:"apparmor_profile"` + NoNewPrivileges bool `json:"no_new_privileges"` + User string `json:"user"` + Config *configs.Config `json:"config"` + Console string `json:"console"` + Networks []*network `json:"network"` + PassedFilesCount int `json:"passed_files_count"` + ContainerId string `json:"containerid"` + Rlimits []configs.Rlimit `json:"rlimits"` } type initer interface { @@ -163,20 +168,22 @@ func syncParentReady(pipe io.ReadWriter) error { return nil } -// joinExistingNamespaces gets all the namespace paths specified for the container and -// does a setns on the namespace fd so that the current process joins the namespace. -func joinExistingNamespaces(namespaces []configs.Namespace) error { - for _, ns := range namespaces { - if ns.Path != "" { - f, err := os.OpenFile(ns.Path, os.O_RDONLY, 0) - if err != nil { - return err - } - err = system.Setns(f.Fd(), uintptr(ns.Syscall())) - f.Close() - if err != nil { - return err - } +// syncParentHooks sends to the given pipe a JSON payload which indicates that +// the parent should execute pre-start hooks. It then waits for the parent to +// indicate that it is cleared to resume. +func syncParentHooks(pipe io.ReadWriter) error { + // Tell parent. + if err := utils.WriteJSON(pipe, syncT{procHooks}); err != nil { + return err + } + // Wait for parent to give the all-clear. + var procSync syncT + if err := json.NewDecoder(pipe).Decode(&procSync); err != nil { + if err == io.EOF { + return fmt.Errorf("parent closed synchronisation channel") + } + if procSync.Type != procResume { + return fmt.Errorf("invalid synchronisation flag from parent") } } return nil @@ -309,19 +316,19 @@ func setupRoute(config *configs.Config) error { return nil } -func setupRlimits(config *configs.Config) error { - for _, rlimit := range config.Rlimits { - l := &syscall.Rlimit{Max: rlimit.Hard, Cur: rlimit.Soft} - if err := syscall.Setrlimit(rlimit.Type, l); err != nil { +func setupRlimits(limits []configs.Rlimit, pid int) error { + for _, rlimit := range limits { + if err := system.Prlimit(pid, rlimit.Type, syscall.Rlimit{Max: rlimit.Hard, Cur: rlimit.Soft}); err != nil { return fmt.Errorf("error setting rlimit type %v: %v", rlimit.Type, err) } } return nil } -func setOomScoreAdj(oomScoreAdj int) error { - path := "/proc/self/oom_score_adj" - return ioutil.WriteFile(path, []byte(strconv.Itoa(oomScoreAdj)), 0700) +func setOomScoreAdj(oomScoreAdj int, pid int) error { + path := fmt.Sprintf("/proc/%d/oom_score_adj", pid) + + return ioutil.WriteFile(path, []byte(strconv.Itoa(oomScoreAdj)), 0600) } // killCgroupProcesses freezes then iterates over all the processes inside the @@ -338,11 +345,14 @@ func killCgroupProcesses(m cgroups.Manager) error { return err } for _, pid := range pids { - if p, err := os.FindProcess(pid); err == nil { - procs = append(procs, p) - if err := p.Kill(); err != nil { - logrus.Warn(err) - } + p, err := os.FindProcess(pid) + if err != nil { + logrus.Warn(err) + continue + } + procs = append(procs, p) + if err := p.Kill(); err != nil { + logrus.Warn(err) } } if err := m.Freeze(configs.Thawed); err != nil { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go b/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go new file mode 100644 index 000000000000..c37ca2133037 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go @@ -0,0 +1,67 @@ +// +build linux + +package keyctl + +import ( + "fmt" + "syscall" + "strings" + "strconv" + "unsafe" +) + +const KEYCTL_JOIN_SESSION_KEYRING = 1 +const KEYCTL_SETPERM = 5 +const KEYCTL_DESCRIBE = 6 + +type KeySerial uint32 + +func JoinSessionKeyring(name string) (KeySerial, error) { + var _name *byte = nil + var err error + + if len(name) > 0 { + _name, err = syscall.BytePtrFromString(name) + if err != nil { + return KeySerial(0), err + } + } + + sessKeyId, _, errn := syscall.Syscall(syscall.SYS_KEYCTL, KEYCTL_JOIN_SESSION_KEYRING, uintptr(unsafe.Pointer(_name)), 0) + if errn != 0 { + return 0, fmt.Errorf("could not create session key: %v", errn) + } + return KeySerial(sessKeyId), nil +} + +// modify permissions on a keyring by reading the current permissions, +// anding the bits with the given mask (clearing permissions) and setting +// additional permission bits +func ModKeyringPerm(ringId KeySerial, mask, setbits uint32) error { + dest := make([]byte, 1024) + destBytes := unsafe.Pointer(&dest[0]) + + if _, _, err := syscall.Syscall6(syscall.SYS_KEYCTL, uintptr(KEYCTL_DESCRIBE), uintptr(ringId), uintptr(destBytes), uintptr(len(dest)), 0, 0); err != 0 { + return err + } + + res := strings.Split(string(dest), ";") + if len(res) < 5 { + return fmt.Errorf("Destination buffer for key description is too small") + } + + // parse permissions + perm64, err := strconv.ParseUint(res[3], 16, 32) + if err != nil { + return err + } + + perm := (uint32(perm64) & mask) | setbits + + if _, _, err := syscall.Syscall(syscall.SYS_KEYCTL, uintptr(KEYCTL_SETPERM), uintptr(ringId), uintptr(perm)); err != 0 { + return err + } + + return nil +} + diff --git a/vendor/github.com/opencontainers/runc/libcontainer/label/label.go b/vendor/github.com/opencontainers/runc/libcontainer/label/label.go index 97dc6baef4ca..684bb41bdc26 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/label/label.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/label/label.go @@ -21,6 +21,10 @@ func SetProcessLabel(processLabel string) error { return nil } +func GetFileLabel(path string) (string, error) { + return "", nil +} + func SetFileLabel(path string, fileLabel string) error { return nil } @@ -48,7 +52,7 @@ func UnreserveLabel(label string) error { return nil } -// DupSecOpt takes an process label and returns security options that +// DupSecOpt takes a process label and returns security options that // can be used to set duplicate labels on future container processes func DupSecOpt(src string) []string { return nil diff --git a/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go b/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go index e561cbfed7b9..d443df4f7bde 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go @@ -94,6 +94,11 @@ func GetProcessLabel() (string, error) { return selinux.Getexeccon() } +// GetFileLabel returns the label for specified path +func GetFileLabel(path string) (string, error) { + return selinux.Getfilecon(path) +} + // SetFileLabel modifies the "path" label to the specified file label func SetFileLabel(path string, fileLabel string) error { if selinux.SelinuxEnabled() && fileLabel != "" { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go index 0c3301f2bb57..166301338c1d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go @@ -12,8 +12,12 @@ import ( // The number is randomly chosen to not conflict with known netlink types const ( InitMsg uint16 = 62000 - PidAttr uint16 = 27281 + CloneFlagsAttr uint16 = 27281 ConsolePathAttr uint16 = 27282 + NsPathsAttr uint16 = 27283 + UidmapAttr uint16 = 27284 + GidmapAttr uint16 = 27285 + SetgroupAttr uint16 = 27286 // When syscall.NLA_HDRLEN is in gccgo, take this out. syscall_NLA_HDRLEN = (syscall.SizeofNlAttr + syscall.NLA_ALIGNTO - 1) & ^(syscall.NLA_ALIGNTO - 1) ) @@ -60,3 +64,25 @@ func (msg *Bytemsg) Serialize() []byte { func (msg *Bytemsg) Len() int { return syscall_NLA_HDRLEN + len(msg.Value) + 1 // null-terminated } + +type Boolmsg struct { + Type uint16 + Value bool +} + +func (msg *Boolmsg) Serialize() []byte { + buf := make([]byte, msg.Len()) + native := nl.NativeEndian() + native.PutUint16(buf[0:2], uint16(msg.Len())) + native.PutUint16(buf[2:4], msg.Type) + if msg.Value { + buf[4] = 1 + } else { + buf[4] = 0 + } + return buf +} + +func (msg *Boolmsg) Len() int { + return syscall_NLA_HDRLEN + 1 +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/process.go b/vendor/github.com/opencontainers/runc/libcontainer/process.go index 9661df80a814..91e8ef56f7e6 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/process.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/process.go @@ -5,6 +5,8 @@ import ( "io" "math" "os" + + "github.com/opencontainers/runc/libcontainer/configs" ) type processOperations interface { @@ -48,6 +50,20 @@ type Process struct { // All capabilities not specified will be dropped from the processes capability mask Capabilities []string + // AppArmorProfile specifies the profile to apply to the process and is + // changed at the time the process is execed + AppArmorProfile string + + // Label specifies the label to apply to the process. It is commonly used by selinux + Label string + + // NoNewPrivileges controls whether processes can gain additional privileges. + NoNewPrivileges *bool + + // Rlimits specifies the resource limits, such as max open files, to set in the container + // If Rlimits are not set, the container will inherit rlimits from the parent process + Rlimits []configs.Rlimit + ops processOperations } @@ -55,7 +71,7 @@ type Process struct { // Wait releases any resources associated with the Process func (p Process) Wait() (*os.ProcessState, error) { if p.ops == nil { - return nil, newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted) + return nil, newGenericError(fmt.Errorf("invalid process"), NoProcessOps) } return p.ops.wait() } @@ -65,7 +81,7 @@ func (p Process) Pid() (int, error) { // math.MinInt32 is returned here, because it's invalid value // for the kill() system call. if p.ops == nil { - return math.MinInt32, newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted) + return math.MinInt32, newGenericError(fmt.Errorf("invalid process"), NoProcessOps) } return p.ops.pid(), nil } @@ -73,7 +89,7 @@ func (p Process) Pid() (int, error) { // Signal sends a signal to the Process. func (p Process) Signal(sig os.Signal) error { if p.ops == nil { - return newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted) + return newGenericError(fmt.Errorf("invalid process"), NoProcessOps) } return p.ops.signal(sig) } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go index ac457c26c8aa..1a2ee0bcd28c 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go @@ -85,6 +85,15 @@ func (p *setnsProcess) start() (err error) { return newSystemError(err) } } + // set oom_score_adj + if err := setOomScoreAdj(p.config.Config.OomScoreAdj, p.pid()); err != nil { + return newSystemError(err) + } + // set rlimits, this has to be done here because we lose permissions + // to raise the limits once we enter a user-namespace + if err := setupRlimits(p.config.Rlimits, p.pid()); err != nil { + return newSystemError(err) + } if err := utils.WriteJSON(p.parentPipe, p.config); err != nil { return newSystemError(err) } @@ -167,14 +176,16 @@ func (p *setnsProcess) setExternalDescriptors(newFds []string) { } type initProcess struct { - cmd *exec.Cmd - parentPipe *os.File - childPipe *os.File - config *initConfig - manager cgroups.Manager - container *linuxContainer - fds []string - process *Process + cmd *exec.Cmd + parentPipe *os.File + childPipe *os.File + config *initConfig + manager cgroups.Manager + container *linuxContainer + fds []string + process *Process + bootstrapData io.Reader + sharePidns bool } func (p *initProcess) pid() int { @@ -185,15 +196,49 @@ func (p *initProcess) externalDescriptors() []string { return p.fds } -func (p *initProcess) start() (err error) { +// execSetns runs the process that executes C code to perform the setns calls +// because setns support requires the C process to fork off a child and perform the setns +// before the go runtime boots, we wait on the process to die and receive the child's pid +// over the provided pipe. +// This is called by initProcess.start function +func (p *initProcess) execSetns() error { + status, err := p.cmd.Process.Wait() + if err != nil { + p.cmd.Wait() + return err + } + if !status.Success() { + p.cmd.Wait() + return &exec.ExitError{ProcessState: status} + } + var pid *pid + if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { + p.cmd.Wait() + return err + } + process, err := os.FindProcess(pid.Pid) + if err != nil { + return err + } + p.cmd.Process = process + return nil +} + +func (p *initProcess) start() error { defer p.parentPipe.Close() - err = p.cmd.Start() + err := p.cmd.Start() p.process.ops = p p.childPipe.Close() if err != nil { p.process.ops = nil return newSystemError(err) } + if _, err := io.Copy(p.parentPipe, p.bootstrapData); err != nil { + return err + } + if err := p.execSetns(); err != nil { + return newSystemError(err) + } // Save the standard descriptor names before the container process // can potentially move them (e.g., via dup2()). If we don't do this now, // we won't know at checkpoint time which file descriptor to look up. @@ -213,19 +258,6 @@ func (p *initProcess) start() (err error) { p.manager.Destroy() } }() - if p.config.Config.Hooks != nil { - s := configs.HookState{ - Version: p.container.config.Version, - ID: p.container.id, - Pid: p.pid(), - Root: p.config.Config.Rootfs, - } - for _, hook := range p.config.Config.Hooks.Prestart { - if err := hook.Run(s); err != nil { - return newSystemError(err) - } - } - } if err := p.createNetworkInterfaces(); err != nil { return newSystemError(err) } @@ -233,35 +265,80 @@ func (p *initProcess) start() (err error) { return newSystemError(err) } var ( - procSync syncT - sentRun bool - ierr *genericError + procSync syncT + sentRun bool + sentResume bool + ierr *genericError ) + dec := json.NewDecoder(p.parentPipe) loop: for { - if err := json.NewDecoder(p.parentPipe).Decode(&procSync); err != nil { + if err := dec.Decode(&procSync); err != nil { if err == io.EOF { break loop } return newSystemError(err) } switch procSync.Type { - case procStart: - break loop case procReady: if err := p.manager.Set(p.config.Config); err != nil { return newSystemError(err) } + // set oom_score_adj + if err := setOomScoreAdj(p.config.Config.OomScoreAdj, p.pid()); err != nil { + return newSystemError(err) + } + // set rlimits, this has to be done here because we lose permissions + // to raise the limits once we enter a user-namespace + if err := setupRlimits(p.config.Rlimits, p.pid()); err != nil { + return newSystemError(err) + } + // call prestart hooks + if !p.config.Config.Namespaces.Contains(configs.NEWNS) { + if p.config.Config.Hooks != nil { + s := configs.HookState{ + Version: p.container.config.Version, + ID: p.container.id, + Pid: p.pid(), + Root: p.config.Config.Rootfs, + } + for _, hook := range p.config.Config.Hooks.Prestart { + if err := hook.Run(s); err != nil { + return newSystemError(err) + } + } + } + } // Sync with child. if err := utils.WriteJSON(p.parentPipe, syncT{procRun}); err != nil { return newSystemError(err) } sentRun = true + case procHooks: + if p.config.Config.Hooks != nil { + s := configs.HookState{ + Version: p.container.config.Version, + ID: p.container.id, + Pid: p.pid(), + Root: p.config.Config.Rootfs, + BundlePath: utils.SearchLabels(p.config.Config.Labels, "bundle"), + } + for _, hook := range p.config.Config.Hooks.Prestart { + if err := hook.Run(s); err != nil { + return newSystemError(err) + } + } + } + // Sync with child. + if err := utils.WriteJSON(p.parentPipe, syncT{procResume}); err != nil { + return newSystemError(err) + } + sentResume = true case procError: // wait for the child process to fully complete and receive an error message // if one was encoutered - if err := json.NewDecoder(p.parentPipe).Decode(&ierr); err != nil && err != io.EOF { + if err := dec.Decode(&ierr); err != nil && err != io.EOF { return newSystemError(err) } if ierr != nil { @@ -274,7 +351,10 @@ loop: } } if !sentRun { - return newSystemError(fmt.Errorf("could not synchronise with container process")) + return newSystemError(fmt.Errorf("could not synchronise with container process: %v", ierr)) + } + if p.config.Config.Namespaces.Contains(configs.NEWNS) && !sentResume { + return newSystemError(fmt.Errorf("could not synchronise after executing prestart hooks with container process")) } if err := syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR); err != nil { return newSystemError(err) @@ -293,7 +373,7 @@ func (p *initProcess) wait() (*os.ProcessState, error) { return p.cmd.ProcessState, err } // we should kill all processes in cgroup when init is died if we use host PID namespace - if p.cmd.SysProcAttr.Cloneflags&syscall.CLONE_NEWPID == 0 { + if p.sharePidns { killCgroupProcesses(p.manager) } return p.cmd.ProcessState, nil @@ -315,7 +395,9 @@ func (p *initProcess) startTime() (string, error) { } func (p *initProcess) sendConfig() error { - // send the state to the container's init process then shutdown writes for the parent + // send the config to the container's init process, we don't use JSON Encode + // here because there might be a problem in JSON decoder in some cases, see: + // https://github.com/docker/docker/issues/14203#issuecomment-174177790 return utils.WriteJSON(p.parentPipe, p.config) } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go index aa061ab08171..4aa4cbd5ef2c 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go @@ -4,6 +4,7 @@ package libcontainer import ( "fmt" + "io" "io/ioutil" "os" "os/exec" @@ -19,18 +20,29 @@ import ( "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runc/libcontainer/system" + libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils" ) const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV +// setupDev returns true if /dev needs to be set up. +func needsSetupDev(config *configs.Config) bool { + for _, m := range config.Mounts { + if m.Device == "bind" && (m.Destination == "/dev" || m.Destination == "/dev/") { + return false + } + } + return true +} + // setupRootfs sets up the devices, mount points, and filesystems for use inside a // new mount namespace. -func setupRootfs(config *configs.Config, console *linuxConsole) (err error) { +func setupRootfs(config *configs.Config, console *linuxConsole, pipe io.ReadWriter) (err error) { if err := prepareRoot(config); err != nil { return newSystemError(err) } - setupDev := len(config.Devices) != 0 + setupDev := needsSetupDev(config) for _, m := range config.Mounts { for _, precmd := range m.PremountCmds { if err := mountCmd(precmd); err != nil { @@ -58,6 +70,13 @@ func setupRootfs(config *configs.Config, console *linuxConsole) (err error) { return newSystemError(err) } } + // Signal the parent to run the pre-start hooks. + // The hooks are run after the mounts are setup, but before we switch to the new + // root, so that the old root is still available in the hooks for any mount + // manipulations. + if err := syncParentHooks(pipe); err != nil { + return err + } if err := syscall.Chdir(config.Rootfs); err != nil { return newSystemError(err) } @@ -74,6 +93,18 @@ func setupRootfs(config *configs.Config, console *linuxConsole) (err error) { return newSystemError(err) } } + // remount dev as ro if specifed + for _, m := range config.Mounts { + if m.Destination == "/dev" { + if m.Flags&syscall.MS_RDONLY != 0 { + if err := remountReadonly(m.Destination); err != nil { + return newSystemError(err) + } + } + break + } + } + // set rootfs ( / ) as readonly if config.Readonlyfs { if err := setReadonly(); err != nil { return newSystemError(err) @@ -119,8 +150,9 @@ func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error { if err := mountPropagate(m, rootfs, ""); err != nil { return err } + return label.SetFileLabel(dest, mountLabel) } - return label.SetFileLabel(dest, mountLabel) + return nil case "tmpfs": stat, err := os.Stat(dest) if err != nil { @@ -137,16 +169,6 @@ func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error { } } return nil - case "devpts": - if err := os.MkdirAll(dest, 0755); err != nil { - return err - } - return mountPropagate(m, rootfs, mountLabel) - case "securityfs": - if err := os.MkdirAll(dest, 0755); err != nil { - return err - } - return mountPropagate(m, rootfs, mountLabel) case "bind": stat, err := os.Stat(m.Source) if err != nil { @@ -252,7 +274,10 @@ func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error { } } default: - return fmt.Errorf("unknown mount device %q to %q", m.Device, m.Destination) + if err := os.MkdirAll(dest, 0755); err != nil { + return err + } + return mountPropagate(m, rootfs, mountLabel) } return nil } @@ -294,7 +319,7 @@ func getCgroupMounts(m *configs.Mount) ([]*configs.Mount, error) { // checkMountDestination checks to ensure that the mount destination is not over the top of /proc. // dest is required to be an abs path and have any symlinks resolved before calling this function. func checkMountDestination(rootfs, dest string) error { - if filepath.Clean(rootfs) == filepath.Clean(dest) { + if libcontainerUtils.CleanPath(rootfs) == libcontainerUtils.CleanPath(dest) { return fmt.Errorf("mounting into / is prohibited") } invalidDestinations := []string{ @@ -307,7 +332,8 @@ func checkMountDestination(rootfs, dest string) error { "/proc/cpuinfo", "/proc/diskstats", "/proc/meminfo", - "/proc/stats", + "/proc/stat", + "/proc/net/dev", } for _, valid := range validDestinations { path, err := filepath.Rel(filepath.Join(rootfs, valid), dest) @@ -340,7 +366,7 @@ func setupDevSymlinks(rootfs string) error { // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink // in /dev if it exists in /proc. if _, err := os.Stat("/proc/kcore"); err == nil { - links = append(links, [2]string{"/proc/kcore", "/dev/kcore"}) + links = append(links, [2]string{"/proc/kcore", "/dev/core"}) } for _, link := range links { var ( @@ -550,7 +576,7 @@ func setupPtmx(config *configs.Config, console *linuxConsole) error { return nil } -func pivotRoot(rootfs, pivotBaseDir string) error { +func pivotRoot(rootfs, pivotBaseDir string) (err error) { if pivotBaseDir == "" { pivotBaseDir = "/" } @@ -562,6 +588,12 @@ func pivotRoot(rootfs, pivotBaseDir string) error { if err != nil { return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err) } + defer func() { + errVal := os.Remove(pivotDir) + if err == nil { + err = errVal + } + }() if err := syscall.PivotRoot(rootfs, pivotDir); err != nil { return fmt.Errorf("pivot_root %s", err) } @@ -580,7 +612,7 @@ func pivotRoot(rootfs, pivotBaseDir string) error { if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil { return fmt.Errorf("unmount pivot_root dir %s", err) } - return os.Remove(pivotDir) + return nil } func msMoveRoot(rootfs string) error { @@ -669,14 +701,18 @@ func remount(m *configs.Mount, rootfs string) error { // of propagation flags. func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( - dest = m.Destination - data = label.FormatMountLabel(m.Data, mountLabel) + dest = m.Destination + data = label.FormatMountLabel(m.Data, mountLabel) + flags = m.Flags ) + if dest == "/dev" { + flags &= ^syscall.MS_RDONLY + } if !strings.HasPrefix(dest, rootfs) { dest = filepath.Join(rootfs, dest) } - if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil { + if err := syscall.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go index 623e227748d8..ec0ac1c0b245 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go @@ -5,7 +5,6 @@ package seccomp import ( "bufio" "fmt" - "log" "os" "strings" "syscall" @@ -167,7 +166,6 @@ func matchCall(filter *libseccomp.ScmpFilter, call *configs.Syscall) error { // Ignore it, don't error out callNum, err := libseccomp.GetSyscallFromName(call.Name) if err != nil { - log.Printf("Error resolving syscall name %s: %s - ignoring syscall.", call.Name, err) return nil } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go b/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go index 88d612cade28..255080c646eb 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go @@ -13,6 +13,7 @@ import ( "regexp" "strconv" "strings" + "sync" "syscall" "github.com/docker/docker/pkg/mount" @@ -35,6 +36,7 @@ const ( var ( assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`) mcsList = make(map[string]bool) + mcsLock sync.Mutex selinuxfs = "unknown" selinuxEnabled = false // Stores whether selinux is currently enabled selinuxEnabledChecked = false // Stores whether selinux enablement has been checked or established yet @@ -158,12 +160,14 @@ func Setfilecon(path string, scon string) error { // Getfilecon returns the SELinux label for this path or returns an error. func Getfilecon(path string) (string, error) { con, err := system.Lgetxattr(path, xattrNameSelinux) - + if err != nil { + return "", err + } // Trim the NUL byte at the end of the byte buffer, if present. - if con[len(con)-1] == '\x00' { + if len(con) > 0 && con[len(con)-1] == '\x00' { con = con[:len(con)-1] } - return string(con), err + return string(con), nil } func Setfscreatecon(scon string) error { @@ -265,6 +269,8 @@ func SelinuxGetEnforceMode() int { } func mcsAdd(mcs string) error { + mcsLock.Lock() + defer mcsLock.Unlock() if mcsList[mcs] { return fmt.Errorf("MCS Label already exists") } @@ -273,7 +279,9 @@ func mcsAdd(mcs string) error { } func mcsDelete(mcs string) { + mcsLock.Lock() mcsList[mcs] = false + mcsLock.Unlock() } func IntToMcs(id int, catRange uint32) string { diff --git a/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go index 2bde44ffb4ee..b1a198fd13b4 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go @@ -3,9 +3,11 @@ package libcontainer import ( + "fmt" "os" "github.com/opencontainers/runc/libcontainer/apparmor" + "github.com/opencontainers/runc/libcontainer/keys" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runc/libcontainer/seccomp" "github.com/opencontainers/runc/libcontainer/system" @@ -17,12 +19,19 @@ type linuxSetnsInit struct { config *initConfig } +func (l *linuxSetnsInit) getSessionRingName() string { + return fmt.Sprintf("_ses.%s", l.config.ContainerId) +} + func (l *linuxSetnsInit) Init() error { - if err := setupRlimits(l.config.Config); err != nil { + // do not inherit the parent's session keyring + if _, err := keyctl.JoinSessionKeyring(l.getSessionRingName()); err != nil { return err } - if err := setOomScoreAdj(l.config.Config.OomScoreAdj); err != nil { - return err + if l.config.NoNewPrivileges { + if err := system.Prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil { + return err + } } if l.config.Config.Seccomp != nil { if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil { @@ -32,11 +41,11 @@ func (l *linuxSetnsInit) Init() error { if err := finalizeNamespace(l.config); err != nil { return err } - if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil { + if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil { return err } - if l.config.Config.ProcessLabel != "" { - if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil { + if l.config.ProcessLabel != "" { + if err := label.SetProcessLabel(l.config.ProcessLabel); err != nil { return err } } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go index d3b50863bd46..59bd370004a7 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go @@ -3,12 +3,14 @@ package libcontainer import ( + "fmt" "io" "os" "syscall" "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/opencontainers/runc/libcontainer/configs" + "github.com/opencontainers/runc/libcontainer/keys" "github.com/opencontainers/runc/libcontainer/label" "github.com/opencontainers/runc/libcontainer/seccomp" "github.com/opencontainers/runc/libcontainer/system" @@ -20,11 +22,39 @@ type linuxStandardInit struct { config *initConfig } +func (l *linuxStandardInit) getSessionRingParams() (string, uint32, uint32) { + var newperms uint32 + + if l.config.Config.Namespaces.Contains(configs.NEWUSER) { + // with user ns we need 'other' search permissions + newperms = 0x8 + } else { + // without user ns we need 'UID' search permissions + newperms = 0x80000 + } + + // create a unique per session container name that we can + // join in setns; however, other containers can also join it + return fmt.Sprintf("_ses.%s", l.config.ContainerId), 0xffffffff, newperms +} + +// PR_SET_NO_NEW_PRIVS isn't exposed in Golang so we define it ourselves copying the value +// the kernel +const PR_SET_NO_NEW_PRIVS = 0x26 + func (l *linuxStandardInit) Init() error { - // join any namespaces via a path to the namespace fd if provided - if err := joinExistingNamespaces(l.config.Config.Namespaces); err != nil { + ringname, keepperms, newperms := l.getSessionRingParams() + + // do not inherit the parent's session keyring + sessKeyId, err := keyctl.JoinSessionKeyring(ringname) + if err != nil { return err } + // make session keyring searcheable + if err := keyctl.ModKeyringPerm(sessKeyId, keepperms, newperms); err != nil { + return err + } + var console *linuxConsole if l.config.Console != "" { console = newConsoleFromPath(l.config.Console) @@ -32,9 +62,6 @@ func (l *linuxStandardInit) Init() error { return err } } - if _, err := syscall.Setsid(); err != nil { - return err - } if console != nil { if err := system.Setctty(); err != nil { return err @@ -46,16 +73,11 @@ func (l *linuxStandardInit) Init() error { if err := setupRoute(l.config.Config); err != nil { return err } - if err := setupRlimits(l.config.Config); err != nil { - return err - } - if err := setOomScoreAdj(l.config.Config.OomScoreAdj); err != nil { - return err - } + label.Init() // InitializeMountNamespace() can be executed only for a new mount namespace if l.config.Config.Namespaces.Contains(configs.NEWNS) { - if err := setupRootfs(l.config.Config, console); err != nil { + if err := setupRootfs(l.config.Config, console, l.pipe); err != nil { return err } } @@ -64,10 +86,10 @@ func (l *linuxStandardInit) Init() error { return err } } - if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil { + if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil { return err } - if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil { + if err := label.SetProcessLabel(l.config.ProcessLabel); err != nil { return err } @@ -90,6 +112,11 @@ func (l *linuxStandardInit) Init() error { if err != nil { return err } + if l.config.NoNewPrivileges { + if err := system.Prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil { + return err + } + } // Tell our parent that we're ready to Execv. This must be done before the // Seccomp rules have been applied, because we need to be able to read and // write to a socket. @@ -115,5 +142,6 @@ func (l *linuxStandardInit) Init() error { if syscall.Getppid() != l.parentPid { return syscall.Kill(syscall.Getpid(), syscall.SIGKILL) } + return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ()) } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go index fb71ef97d39c..d2618f69b25d 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go @@ -9,6 +9,7 @@ import ( "github.com/Sirupsen/logrus" "github.com/opencontainers/runc/libcontainer/configs" + "github.com/opencontainers/runc/libcontainer/utils" ) func newStateTransitionError(from, to containerState) error { @@ -56,9 +57,10 @@ func destroy(c *linuxContainer) error { func runPoststopHooks(c *linuxContainer) error { if c.config.Hooks != nil { s := configs.HookState{ - Version: c.config.Version, - ID: c.id, - Root: c.config.Rootfs, + Version: c.config.Version, + ID: c.id, + Root: c.config.Rootfs, + BundlePath: utils.SearchLabels(c.config.Labels, "bundle"), } for _, hook := range c.config.Hooks.Poststop { if err := hook.Run(s); err != nil { @@ -219,5 +221,8 @@ func (n *createdState) transition(s containerState) error { } func (n *createdState) destroy() error { - return nil + if err := n.c.refreshState(); err != nil { + return err + } + return n.c.state.destroy() } diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go b/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go index 6c835e68ec26..8b199d92ed5c 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go @@ -11,6 +11,19 @@ import ( "unsafe" ) +// If arg2 is nonzero, set the "child subreaper" attribute of the +// calling process; if arg2 is zero, unset the attribute. When a +// process is marked as a child subreaper, all of the children +// that it creates, and their descendants, will be marked as +// having a subreaper. In effect, a subreaper fulfills the role +// of init(1) for its descendant processes. Upon termination of +// a process that is orphaned (i.e., its immediate parent has +// already terminated) and marked as having a subreaper, the +// nearest still living ancestor subreaper will receive a SIGCHLD +// signal and be able to wait(2) on the process to discover its +// termination status. +const PR_SET_CHILD_SUBREAPER = 36 + type ParentDeathSignal int func (p ParentDeathSignal) Restore() error { @@ -40,6 +53,14 @@ func Execv(cmd string, args []string, env []string) error { return syscall.Exec(name, args, env) } +func Prlimit(pid, resource int, limit syscall.Rlimit) error { + _, _, err := syscall.RawSyscall6(syscall.SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(&limit)), uintptr(unsafe.Pointer(&limit)), 0, 0) + if err != 0 { + return err + } + return nil +} + func SetParentDeathSignal(sig uintptr) error { if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, sig, 0); err != 0 { return err @@ -112,3 +133,16 @@ func RunningInUserNS() bool { } return true } + +// SetSubreaper sets the value i as the subreaper setting for the calling process +func SetSubreaper(i int) error { + return Prctl(PR_SET_CHILD_SUBREAPER, uintptr(i), 0, 0, 0) +} + +func Prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) { + _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0) + if e1 != 0 { + err = e1 + } + return +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go new file mode 100644 index 000000000000..e7cfd62b293c --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go @@ -0,0 +1,9 @@ +// +build !linux + +package system + +// RunningInUserNS is a stub for non-Linux systems +// Always returns false +func RunningInUserNS() bool { + return false +} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go index 6f8a982ff72a..ab1439f3614b 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go @@ -2,13 +2,15 @@ package user import ( "errors" - "fmt" "syscall" ) var ( // The current operating system does not provide the required data for user lookups. ErrUnsupported = errors.New("user lookup: operating system does not provide passwd-formatted data") + // No matching entries found in file. + ErrNoPasswdEntries = errors.New("no matching entries in passwd file") + ErrNoGroupEntries = errors.New("no matching entries in group file") ) func lookupUser(filter func(u User) bool) (User, error) { @@ -27,7 +29,7 @@ func lookupUser(filter func(u User) bool) (User, error) { // No user entries found. if len(users) == 0 { - return User{}, fmt.Errorf("no matching entries in passwd file") + return User{}, ErrNoPasswdEntries } // Assume the first entry is the "correct" one. @@ -75,7 +77,7 @@ func lookupGroup(filter func(g Group) bool) (Group, error) { // No user entries found. if len(groups) == 0 { - return Group{}, fmt.Errorf("no matching entries in group file") + return Group{}, ErrNoGroupEntries } // Assume the first entry is the "correct" one. diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/user.go b/vendor/github.com/opencontainers/runc/libcontainer/user/user.go index e6375ea4dd53..43fd39ef54db 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/user/user.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/user/user.go @@ -15,7 +15,7 @@ const ( ) var ( - ErrRange = fmt.Errorf("Uids and gids must be in range %d-%d", minId, maxId) + ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minId, maxId) ) type User struct { @@ -42,29 +42,30 @@ func parseLine(line string, v ...interface{}) { parts := strings.Split(line, ":") for i, p := range parts { + // Ignore cases where we don't have enough fields to populate the arguments. + // Some configuration files like to misbehave. if len(v) <= i { - // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files break } + // Use the type of the argument to figure out how to parse it, scanf() style. + // This is legit. switch e := v[i].(type) { case *string: - // "root", "adm", "/bin/bash" *e = p case *int: - // "0", "4", "1000" - // ignore string to int conversion errors, for great "tolerance" of naughty configuration files + // "numbers", with conversion errors ignored because of some misbehaving configuration files. *e, _ = strconv.Atoi(p) case *[]string: - // "", "root", "root,adm,daemon" + // Comma-separated lists. if p != "" { *e = strings.Split(p, ",") } else { *e = []string{} } default: - // panic, because this is a programming/logic error, not a runtime one - panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!") + // Someone goof'd when writing code using this function. Scream so they can hear us. + panic(fmt.Sprintf("parseLine only accepts {*string, *int, *[]string} as arguments! %#v is not a pointer!", e)) } } } @@ -106,8 +107,8 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { return nil, err } - text := strings.TrimSpace(s.Text()) - if text == "" { + line := strings.TrimSpace(s.Text()) + if line == "" { continue } @@ -117,10 +118,7 @@ func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { // root:x:0:0:root:/root:/bin/bash // adm:x:3:4:adm:/var/adm:/bin/false p := User{} - parseLine( - text, - &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell, - ) + parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell) if filter == nil || filter(p) { out = append(out, p) @@ -135,6 +133,7 @@ func ParseGroupFile(path string) ([]Group, error) { if err != nil { return nil, err } + defer group.Close() return ParseGroup(group) } @@ -178,10 +177,7 @@ func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { // root:x:0:root // adm:x:4:root,adm,daemon p := Group{} - parseLine( - text, - &p.Name, &p.Pass, &p.Gid, &p.List, - ) + parseLine(text, &p.Name, &p.Pass, &p.Gid, &p.List) if filter == nil || filter(p) { out = append(out, p) @@ -192,9 +188,10 @@ func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { } type ExecUser struct { - Uid, Gid int - Sgids []int - Home string + Uid int + Gid int + Sgids []int + Home string } // GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the @@ -235,12 +232,12 @@ func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath // * "uid:gid // * "user:gid" // * "uid:group" +// +// It should be noted that if you specify a numeric user or group id, they will +// not be evaluated as usernames (only the metadata will be filled). So attempting +// to parse a user with user.Name = "1337" will produce the user with a UID of +// 1337. func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) { - var ( - userArg, groupArg string - name string - ) - if defaults == nil { defaults = new(ExecUser) } @@ -258,87 +255,113 @@ func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) ( user.Sgids = []int{} } - // allow for userArg to have either "user" syntax, or optionally "user:group" syntax + // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax + var userArg, groupArg string parseLine(userSpec, &userArg, &groupArg) + // Convert userArg and groupArg to be numeric, so we don't have to execute + // Atoi *twice* for each iteration over lines. + uidArg, uidErr := strconv.Atoi(userArg) + gidArg, gidErr := strconv.Atoi(groupArg) + + // Find the matching user. users, err := ParsePasswdFilter(passwd, func(u User) bool { if userArg == "" { + // Default to current state of the user. return u.Uid == user.Uid } - return u.Name == userArg || strconv.Itoa(u.Uid) == userArg + + if uidErr == nil { + // If the userArg is numeric, always treat it as a UID. + return uidArg == u.Uid + } + + return u.Name == userArg }) + + // If we can't find the user, we have to bail. if err != nil && passwd != nil { if userArg == "" { userArg = strconv.Itoa(user.Uid) } - return nil, fmt.Errorf("Unable to find user %v: %v", userArg, err) + return nil, fmt.Errorf("unable to find user %s: %v", userArg, err) } - haveUser := users != nil && len(users) > 0 - if haveUser { - // if we found any user entries that matched our filter, let's take the first one as "correct" - name = users[0].Name + var matchedUserName string + if len(users) > 0 { + // First match wins, even if there's more than one matching entry. + matchedUserName = users[0].Name user.Uid = users[0].Uid user.Gid = users[0].Gid user.Home = users[0].Home } else if userArg != "" { - // we asked for a user but didn't find them... let's check to see if we wanted a numeric user - user.Uid, err = strconv.Atoi(userArg) - if err != nil { - // not numeric - we have to bail - return nil, fmt.Errorf("Unable to find user %v", userArg) + // If we can't find a user with the given username, the only other valid + // option is if it's a numeric username with no associated entry in passwd. + + if uidErr != nil { + // Not numeric. + return nil, fmt.Errorf("unable to find user %s: %v", userArg, ErrNoPasswdEntries) } + user.Uid = uidArg // Must be inside valid uid range. if user.Uid < minId || user.Uid > maxId { return nil, ErrRange } - // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit + // Okay, so it's numeric. We can just roll with this. } - if groupArg != "" || name != "" { + // On to the groups. If we matched a username, we need to do this because of + // the supplementary group IDs. + if groupArg != "" || matchedUserName != "" { groups, err := ParseGroupFilter(group, func(g Group) bool { - // Explicit group format takes precedence. - if groupArg != "" { - return g.Name == groupArg || strconv.Itoa(g.Gid) == groupArg + // If the group argument isn't explicit, we'll just search for it. + if groupArg == "" { + // Check if user is a member of this group. + for _, u := range g.List { + if u == matchedUserName { + return true + } + } + return false } - // Check if user is a member. - for _, u := range g.List { - if u == name { - return true - } + if gidErr == nil { + // If the groupArg is numeric, always treat it as a GID. + return gidArg == g.Gid } - return false + return g.Name == groupArg }) if err != nil && group != nil { - return nil, fmt.Errorf("Unable to find groups for user %v: %v", users[0].Name, err) + return nil, fmt.Errorf("unable to find groups for spec %v: %v", matchedUserName, err) } - haveGroup := groups != nil && len(groups) > 0 + // Only start modifying user.Gid if it is in explicit form. if groupArg != "" { - if haveGroup { - // if we found any group entries that matched our filter, let's take the first one as "correct" + if len(groups) > 0 { + // First match wins, even if there's more than one matching entry. user.Gid = groups[0].Gid - } else { - // we asked for a group but didn't find id... let's check to see if we wanted a numeric group - user.Gid, err = strconv.Atoi(groupArg) - if err != nil { - // not numeric - we have to bail - return nil, fmt.Errorf("Unable to find group %v", groupArg) + } else if groupArg != "" { + // If we can't find a group with the given name, the only other valid + // option is if it's a numeric group name with no associated entry in group. + + if gidErr != nil { + // Not numeric. + return nil, fmt.Errorf("unable to find group %s: %v", groupArg, ErrNoGroupEntries) } + user.Gid = gidArg - // Ensure gid is inside gid range. + // Must be inside valid gid range. if user.Gid < minId || user.Gid > maxId { return nil, ErrRange } - // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit + // Okay, so it's numeric. We can just roll with this. } - } else if haveGroup { - // If implicit group format, fill supplementary gids. + } else if len(groups) > 0 { + // Supplementary group ids only make sense if in the implicit form. user.Sgids = make([]int, len(groups)) for i, group := range groups { user.Sgids[i] = group.Gid diff --git a/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go index 1378006b0a69..9e748a6d6f0a 100644 --- a/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go +++ b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go @@ -5,7 +5,9 @@ import ( "encoding/hex" "encoding/json" "io" + "os" "path/filepath" + "strings" "syscall" ) @@ -54,3 +56,47 @@ func WriteJSON(w io.Writer, v interface{}) error { _, err = w.Write(data) return err } + +// CleanPath makes a path safe for use with filepath.Join. This is done by not +// only cleaning the path, but also (if the path is relative) adding a leading +// '/' and cleaning it (then removing the leading '/'). This ensures that a +// path resulting from prepending another path will always resolve to lexically +// be a subdirectory of the prefixed path. This is all done lexically, so paths +// that include symlinks won't be safe as a result of using CleanPath. +func CleanPath(path string) string { + // Deal with empty strings nicely. + if path == "" { + return "" + } + + // Ensure that all paths are cleaned (especially problematic ones like + // "/../../../../../" which can cause lots of issues). + path = filepath.Clean(path) + + // If the path isn't absolute, we need to do more processing to fix paths + // such as "../../../..//some/path". We also shouldn't convert absolute + // paths to relative ones. + if !filepath.IsAbs(path) { + path = filepath.Clean(string(os.PathSeparator) + path) + // This can't fail, as (by definition) all paths are relative to root. + path, _ = filepath.Rel(string(os.PathSeparator), path) + } + + // Clean the path again for good measure. + return filepath.Clean(path) +} + +// SearchLabels searches a list of key-value pairs for the provided key and +// returns the corresponding value. The pairs must be separated with '='. +func SearchLabels(labels []string, query string) string { + for _, l := range labels { + parts := strings.SplitN(l, "=", 2) + if len(parts) < 2 { + continue + } + if parts[0] == query { + return parts[1] + } + } + return "" +} diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE deleted file mode 100644 index c67dad612a3d..000000000000 --- a/vendor/github.com/pmezard/go-difflib/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013, Patrick Mezard -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - The names of its contributors may not be used to endorse or promote -products derived from this software without specific prior written -permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go deleted file mode 100644 index 64cc40fe1dad..000000000000 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ /dev/null @@ -1,758 +0,0 @@ -// Package difflib is a partial port of Python difflib module. -// -// It provides tools to compare sequences of strings and generate textual diffs. -// -// The following class and functions have been ported: -// -// - SequenceMatcher -// -// - unified_diff -// -// - context_diff -// -// Getting unified diffs was the main goal of the port. Keep in mind this code -// is mostly suitable to output text differences in a human friendly way, there -// are no guarantees generated diffs are consumable by patch(1). -package difflib - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strings" -) - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func calculateRatio(matches, length int) float64 { - if length > 0 { - return 2.0 * float64(matches) / float64(length) - } - return 1.0 -} - -type Match struct { - A int - B int - Size int -} - -type OpCode struct { - Tag byte - I1 int - I2 int - J1 int - J2 int -} - -// SequenceMatcher compares sequence of strings. The basic -// algorithm predates, and is a little fancier than, an algorithm -// published in the late 1980's by Ratcliff and Obershelp under the -// hyperbolic name "gestalt pattern matching". The basic idea is to find -// the longest contiguous matching subsequence that contains no "junk" -// elements (R-O doesn't address junk). The same idea is then applied -// recursively to the pieces of the sequences to the left and to the right -// of the matching subsequence. This does not yield minimal edit -// sequences, but does tend to yield matches that "look right" to people. -// -// SequenceMatcher tries to compute a "human-friendly diff" between two -// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the -// longest *contiguous* & junk-free matching subsequence. That's what -// catches peoples' eyes. The Windows(tm) windiff has another interesting -// notion, pairing up elements that appear uniquely in each sequence. -// That, and the method here, appear to yield more intuitive difference -// reports than does diff. This method appears to be the least vulnerable -// to synching up on blocks of "junk lines", though (like blank lines in -// ordinary text files, or maybe "

" lines in HTML files). That may be -// because this is the only method of the 3 that has a *concept* of -// "junk" . -// -// Timing: Basic R-O is cubic time worst case and quadratic time expected -// case. SequenceMatcher is quadratic time for the worst case and has -// expected-case behavior dependent in a complicated way on how many -// elements the sequences have in common; best case time is linear. -type SequenceMatcher struct { - a []string - b []string - b2j map[string][]int - IsJunk func(string) bool - autoJunk bool - bJunk map[string]struct{} - matchingBlocks []Match - fullBCount map[string]int - bPopular map[string]struct{} - opCodes []OpCode -} - -func NewMatcher(a, b []string) *SequenceMatcher { - m := SequenceMatcher{autoJunk: true} - m.SetSeqs(a, b) - return &m -} - -func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { - - m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} - m.SetSeqs(a, b) - return &m -} - -// Set two sequences to be compared. -func (m *SequenceMatcher) SetSeqs(a, b []string) { - m.SetSeq1(a) - m.SetSeq2(b) -} - -// Set the first sequence to be compared. The second sequence to be compared is -// not changed. -// -// SequenceMatcher computes and caches detailed information about the second -// sequence, so if you want to compare one sequence S against many sequences, -// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other -// sequences. -// -// See also SetSeqs() and SetSeq2(). -func (m *SequenceMatcher) SetSeq1(a []string) { - if &a == &m.a { - return - } - m.a = a - m.matchingBlocks = nil - m.opCodes = nil -} - -// Set the second sequence to be compared. The first sequence to be compared is -// not changed. -func (m *SequenceMatcher) SetSeq2(b []string) { - if &b == &m.b { - return - } - m.b = b - m.matchingBlocks = nil - m.opCodes = nil - m.fullBCount = nil - m.chainB() -} - -func (m *SequenceMatcher) chainB() { - // Populate line -> index mapping - b2j := map[string][]int{} - for i, s := range m.b { - indices := b2j[s] - indices = append(indices, i) - b2j[s] = indices - } - - // Purge junk elements - m.bJunk = map[string]struct{}{} - if m.IsJunk != nil { - junk := m.bJunk - for s, _ := range b2j { - if m.IsJunk(s) { - junk[s] = struct{}{} - } - } - for s, _ := range junk { - delete(b2j, s) - } - } - - // Purge remaining popular elements - popular := map[string]struct{}{} - n := len(m.b) - if m.autoJunk && n >= 200 { - ntest := n/100 + 1 - for s, indices := range b2j { - if len(indices) > ntest { - popular[s] = struct{}{} - } - } - for s, _ := range popular { - delete(b2j, s) - } - } - m.bPopular = popular - m.b2j = b2j -} - -func (m *SequenceMatcher) isBJunk(s string) bool { - _, ok := m.bJunk[s] - return ok -} - -// Find longest matching block in a[alo:ahi] and b[blo:bhi]. -// -// If IsJunk is not defined: -// -// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where -// alo <= i <= i+k <= ahi -// blo <= j <= j+k <= bhi -// and for all (i',j',k') meeting those conditions, -// k >= k' -// i <= i' -// and if i == i', j <= j' -// -// In other words, of all maximal matching blocks, return one that -// starts earliest in a, and of all those maximal matching blocks that -// start earliest in a, return the one that starts earliest in b. -// -// If IsJunk is defined, first the longest matching block is -// determined as above, but with the additional restriction that no -// junk element appears in the block. Then that block is extended as -// far as possible by matching (only) junk elements on both sides. So -// the resulting block never matches on junk except as identical junk -// happens to be adjacent to an "interesting" match. -// -// If no blocks match, return (alo, blo, 0). -func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { - // CAUTION: stripping common prefix or suffix would be incorrect. - // E.g., - // ab - // acab - // Longest matching block is "ab", but if common prefix is - // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so - // strip, so ends up claiming that ab is changed to acab by - // inserting "ca" in the middle. That's minimal but unintuitive: - // "it's obvious" that someone inserted "ac" at the front. - // Windiff ends up at the same place as diff, but by pairing up - // the unique 'b's and then matching the first two 'a's. - besti, bestj, bestsize := alo, blo, 0 - - // find longest junk-free match - // during an iteration of the loop, j2len[j] = length of longest - // junk-free match ending with a[i-1] and b[j] - j2len := map[int]int{} - for i := alo; i != ahi; i++ { - // look at all instances of a[i] in b; note that because - // b2j has no junk keys, the loop is skipped if a[i] is junk - newj2len := map[int]int{} - for _, j := range m.b2j[m.a[i]] { - // a[i] matches b[j] - if j < blo { - continue - } - if j >= bhi { - break - } - k := j2len[j-1] + 1 - newj2len[j] = k - if k > bestsize { - besti, bestj, bestsize = i-k+1, j-k+1, k - } - } - j2len = newj2len - } - - // Extend the best by non-junk elements on each end. In particular, - // "popular" non-junk elements aren't in b2j, which greatly speeds - // the inner loop above, but also means "the best" match so far - // doesn't contain any junk *or* popular non-junk elements. - for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - !m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - // Now that we have a wholly interesting match (albeit possibly - // empty!), we may as well suck up the matching junk on each - // side of it too. Can't think of a good reason not to, and it - // saves post-processing the (possibly considerable) expense of - // figuring out what to do with it. In the case of an empty - // interesting match, this is clearly the right thing to do, - // because no other kind of match is possible in the regions. - for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - return Match{A: besti, B: bestj, Size: bestsize} -} - -// Return list of triples describing matching subsequences. -// -// Each triple is of the form (i, j, n), and means that -// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in -// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are -// adjacent triples in the list, and the second is not the last triple in the -// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe -// adjacent equal blocks. -// -// The last triple is a dummy, (len(a), len(b), 0), and is the only -// triple with n==0. -func (m *SequenceMatcher) GetMatchingBlocks() []Match { - if m.matchingBlocks != nil { - return m.matchingBlocks - } - - var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match - matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { - match := m.findLongestMatch(alo, ahi, blo, bhi) - i, j, k := match.A, match.B, match.Size - if match.Size > 0 { - if alo < i && blo < j { - matched = matchBlocks(alo, i, blo, j, matched) - } - matched = append(matched, match) - if i+k < ahi && j+k < bhi { - matched = matchBlocks(i+k, ahi, j+k, bhi, matched) - } - } - return matched - } - matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) - - // It's possible that we have adjacent equal blocks in the - // matching_blocks list now. - nonAdjacent := []Match{} - i1, j1, k1 := 0, 0, 0 - for _, b := range matched { - // Is this block adjacent to i1, j1, k1? - i2, j2, k2 := b.A, b.B, b.Size - if i1+k1 == i2 && j1+k1 == j2 { - // Yes, so collapse them -- this just increases the length of - // the first block by the length of the second, and the first - // block so lengthened remains the block to compare against. - k1 += k2 - } else { - // Not adjacent. Remember the first block (k1==0 means it's - // the dummy we started with), and make the second block the - // new block to compare against. - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - i1, j1, k1 = i2, j2, k2 - } - } - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - - nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) - m.matchingBlocks = nonAdjacent - return m.matchingBlocks -} - -// Return list of 5-tuples describing how to turn a into b. -// -// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple -// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the -// tuple preceding it, and likewise for j1 == the previous j2. -// -// The tags are characters, with these meanings: -// -// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] -// -// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. -// -// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. -// -// 'e' (equal): a[i1:i2] == b[j1:j2] -func (m *SequenceMatcher) GetOpCodes() []OpCode { - if m.opCodes != nil { - return m.opCodes - } - i, j := 0, 0 - matching := m.GetMatchingBlocks() - opCodes := make([]OpCode, 0, len(matching)) - for _, m := range matching { - // invariant: we've pumped out correct diffs to change - // a[:i] into b[:j], and the next matching block is - // a[ai:ai+size] == b[bj:bj+size]. So we need to pump - // out a diff to change a[i:ai] into b[j:bj], pump out - // the matching block, and move (i,j) beyond the match - ai, bj, size := m.A, m.B, m.Size - tag := byte(0) - if i < ai && j < bj { - tag = 'r' - } else if i < ai { - tag = 'd' - } else if j < bj { - tag = 'i' - } - if tag > 0 { - opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) - } - i, j = ai+size, bj+size - // the list of matching blocks is terminated by a - // sentinel with size 0 - if size > 0 { - opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) - } - } - m.opCodes = opCodes - return m.opCodes -} - -// Isolate change clusters by eliminating ranges with no changes. -// -// Return a generator of groups with up to n lines of context. -// Each group is in the same format as returned by GetOpCodes(). -func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { - if n < 0 { - n = 3 - } - codes := m.GetOpCodes() - if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} - } - // Fixup leading and trailing groups if they show no changes. - if codes[0].Tag == 'e' { - c := codes[0] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} - } - if codes[len(codes)-1].Tag == 'e' { - c := codes[len(codes)-1] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} - } - nn := n + n - groups := [][]OpCode{} - group := []OpCode{} - for _, c := range codes { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - // End the current group and start a new one whenever - // there is a large range with no changes. - if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) - groups = append(groups, group) - group = []OpCode{} - i1, j1 = max(i1, i2-n), max(j1, j2-n) - } - group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) - } - if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { - groups = append(groups, group) - } - return groups -} - -// Return a measure of the sequences' similarity (float in [0,1]). -// -// Where T is the total number of elements in both sequences, and -// M is the number of matches, this is 2.0*M / T. -// Note that this is 1 if the sequences are identical, and 0 if -// they have nothing in common. -// -// .Ratio() is expensive to compute if you haven't already computed -// .GetMatchingBlocks() or .GetOpCodes(), in which case you may -// want to try .QuickRatio() or .RealQuickRation() first to get an -// upper bound. -func (m *SequenceMatcher) Ratio() float64 { - matches := 0 - for _, m := range m.GetMatchingBlocks() { - matches += m.Size - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() relatively quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute. -func (m *SequenceMatcher) QuickRatio() float64 { - // viewing a and b as multisets, set matches to the cardinality - // of their intersection; this counts the number of matches - // without regard to order, so is clearly an upper bound - if m.fullBCount == nil { - m.fullBCount = map[string]int{} - for _, s := range m.b { - m.fullBCount[s] = m.fullBCount[s] + 1 - } - } - - // avail[x] is the number of times x appears in 'b' less the - // number of times we've seen it in 'a' so far ... kinda - avail := map[string]int{} - matches := 0 - for _, s := range m.a { - n, ok := avail[s] - if !ok { - n = m.fullBCount[s] - } - avail[s] = n - 1 - if n > 0 { - matches += 1 - } - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() very quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute than either .Ratio() or .QuickRatio(). -func (m *SequenceMatcher) RealQuickRatio() float64 { - la, lb := len(m.a), len(m.b) - return calculateRatio(min(la, lb), la+lb) -} - -// Convert range to the "ed" format -func formatRangeUnified(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 1 { - return fmt.Sprintf("%d", beginning) - } - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - return fmt.Sprintf("%d,%d", beginning, length) -} - -// Unified diff parameters -type UnifiedDiff struct { - A []string // First sequence lines - FromFile string // First file name - FromDate string // First file time - B []string // Second sequence lines - ToFile string // Second file name - ToDate string // Second file time - Eol string // Headers end of line, defaults to LF - Context int // Number of context lines -} - -// Compare two sequences of lines; generate the delta as a unified diff. -// -// Unified diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by 'n' which -// defaults to three. -// -// By default, the diff control lines (those with ---, +++, or @@) are -// created with a trailing newline. This is helpful so that inputs -// created from file.readlines() result in diffs that are suitable for -// file.writelines() since both the inputs and outputs have trailing -// newlines. -// -// For inputs that do not have trailing newlines, set the lineterm -// argument to "" so that the output will be uniformly newline free. -// -// The unidiff format normally has a header for filenames and modification -// times. Any or all of these may be specified using strings for -// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. -// The modification times are normally expressed in the ISO 8601 format. -func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - w := func(format string, args ...interface{}) error { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - return err - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - err := w("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) - if err != nil { - return err - } - err = w("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) - if err != nil { - return err - } - } - first, last := g[0], g[len(g)-1] - range1 := formatRangeUnified(first.I1, last.I2) - range2 := formatRangeUnified(first.J1, last.J2) - if err := w("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { - return err - } - for _, c := range g { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - if c.Tag == 'e' { - for _, line := range diff.A[i1:i2] { - if err := w(" " + line); err != nil { - return err - } - } - continue - } - if c.Tag == 'r' || c.Tag == 'd' { - for _, line := range diff.A[i1:i2] { - if err := w("-" + line); err != nil { - return err - } - } - } - if c.Tag == 'r' || c.Tag == 'i' { - for _, line := range diff.B[j1:j2] { - if err := w("+" + line); err != nil { - return err - } - } - } - } - } - return nil -} - -// Like WriteUnifiedDiff but returns the diff a string. -func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err -} - -// Convert range to the "ed" format. -func formatRangeContext(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - if length <= 1 { - return fmt.Sprintf("%d", beginning) - } - return fmt.Sprintf("%d,%d", beginning, beginning+length-1) -} - -type ContextDiff UnifiedDiff - -// Compare two sequences of lines; generate the delta as a context diff. -// -// Context diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by diff.Context -// which defaults to three. -// -// By default, the diff control lines (those with *** or ---) are -// created with a trailing newline. -// -// For inputs that do not have trailing newlines, set the diff.Eol -// argument to "" so that the output will be uniformly newline free. -// -// The context diff format normally has a header for filenames and -// modification times. Any or all of these may be specified using -// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. -// The modification times are normally expressed in the ISO 8601 format. -// If not specified, the strings default to blanks. -func WriteContextDiff(writer io.Writer, diff ContextDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - var diffErr error - w := func(format string, args ...interface{}) { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - if diffErr == nil && err != nil { - diffErr = err - } - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - prefix := map[byte]string{ - 'i': "+ ", - 'd': "- ", - 'r': "! ", - 'e': " ", - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - w("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) - w("--- %s%s%s", diff.ToFile, toDate, diff.Eol) - } - - first, last := g[0], g[len(g)-1] - w("***************" + diff.Eol) - - range1 := formatRangeContext(first.I1, last.I2) - w("*** %s ****%s", range1, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'd' { - for _, cc := range g { - if cc.Tag == 'i' { - continue - } - for _, line := range diff.A[cc.I1:cc.I2] { - w(prefix[cc.Tag] + line) - } - } - break - } - } - - range2 := formatRangeContext(first.J1, last.J2) - w("--- %s ----%s", range2, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'i' { - for _, cc := range g { - if cc.Tag == 'd' { - continue - } - for _, line := range diff.B[cc.J1:cc.J2] { - w(prefix[cc.Tag] + line) - } - } - break - } - } - } - return diffErr -} - -// Like WriteContextDiff but returns the diff a string. -func GetContextDiffString(diff ContextDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteContextDiff(w, diff) - return string(w.Bytes()), err -} - -// Split a string on "\n" while preserving them. The output can be used -// as input for UnifiedDiff and ContextDiff structures. -func SplitLines(s string) []string { - lines := strings.SplitAfter(s, "\n") - lines[len(lines)-1] += "\n" - return lines -} diff --git a/vendor/github.com/skynetservices/skydns/server/config.go b/vendor/github.com/skynetservices/skydns/server/config.go index 3e4c6cfb0789..b0222a52652c 100644 --- a/vendor/github.com/skynetservices/skydns/server/config.go +++ b/vendor/github.com/skynetservices/skydns/server/config.go @@ -39,7 +39,7 @@ type Config struct { RoundRobin bool `json:"round_robin,omitempty"` // Round robin selection of nameservers from among those listed, rather than have all forwarded requests try the first listed server first every time. NSRotate bool `json:"ns_rotate,omitempty"` - // List of ip:port, seperated by commas of recursive nameservers to forward queries to. + // List of ip:port, separated by commas of recursive nameservers to forward queries to. Nameservers []string `json:"nameservers,omitempty"` // Never provide a recursive service. NoRec bool `json:"no_rec,omitempty"` diff --git a/vendor/github.com/skynetservices/skydns/server/forwarding.go b/vendor/github.com/skynetservices/skydns/server/forwarding.go index a3c8cb32db86..83470af6edc1 100644 --- a/vendor/github.com/skynetservices/skydns/server/forwarding.go +++ b/vendor/github.com/skynetservices/skydns/server/forwarding.go @@ -102,7 +102,7 @@ Redo: r, err := exchangeWithRetry(s.dnsUDPclient, m, s.config.Nameservers[nsid]) if err == nil { if r.Rcode != dns.RcodeSuccess { - return nil, fmt.Errorf("rcode is not equal to success") + return nil, fmt.Errorf("rcode %d is not equal to success", r.Rcode) } // Reset TTLs to rcache TTL to make some of the other code // and the tests not care about TTLs diff --git a/vendor/github.com/skynetservices/skydns/server/server.go b/vendor/github.com/skynetservices/skydns/server/server.go index 883afef9972a..b5799aa23256 100644 --- a/vendor/github.com/skynetservices/skydns/server/server.go +++ b/vendor/github.com/skynetservices/skydns/server/server.go @@ -200,7 +200,7 @@ func (s *server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) { } for zone, ns := range *s.config.stub { - if strings.HasSuffix(name, zone) { + if strings.HasSuffix(name, "." + zone) || name == zone { metrics.ReportRequestCount(req, metrics.Stub) resp := s.ServeDNSStubForward(w, req, ns) @@ -232,7 +232,7 @@ func (s *server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) { return } - if q.Qclass != dns.ClassCHAOS && !strings.HasSuffix(name, s.config.Domain) { + if q.Qclass != dns.ClassCHAOS && !strings.HasSuffix(name, "." +s.config.Domain) && name != s.config.Domain { metrics.ReportRequestCount(req, metrics.Rec) resp := s.ServeDNSForward(w, req) @@ -431,6 +431,7 @@ func (s *server) AddressRecords(q dns.Question, name string, previousRecords []d case ip == nil: // Try to resolve as CNAME if it's not an IP, but only if we don't create loops. if q.Name == dns.Fqdn(serv.Host) { + logf("CNAME loop detected: %q -> %q", q.Name, q.Name) // x CNAME x is a direct loop, don't add those continue } @@ -464,7 +465,7 @@ func (s *server) AddressRecords(q dns.Question, name string, previousRecords []d } m1, e1 := s.Lookup(target, q.Qtype, bufsize, dnssec) if e1 != nil { - logf("incomplete CNAME chain: %s", e1) + logf("incomplete CNAME chain from %q: %s", target, e1) continue } // Len(m1.Answer) > 0 here is well? diff --git a/vendor/github.com/stretchr/objx/.gitignore b/vendor/github.com/stretchr/objx/.gitignore deleted file mode 100644 index 00268614f045..000000000000 --- a/vendor/github.com/stretchr/objx/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/stretchr/objx/README.md b/vendor/github.com/stretchr/objx/README.md deleted file mode 100644 index 4aa180687a7a..000000000000 --- a/vendor/github.com/stretchr/objx/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# objx - - * Jump into the [API Documentation](http://godoc.org/github.com/stretchr/objx) diff --git a/vendor/github.com/stretchr/objx/accessors.go b/vendor/github.com/stretchr/objx/accessors.go deleted file mode 100644 index 721bcac79939..000000000000 --- a/vendor/github.com/stretchr/objx/accessors.go +++ /dev/null @@ -1,179 +0,0 @@ -package objx - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// arrayAccesRegexString is the regex used to extract the array number -// from the access path -const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` - -// arrayAccesRegex is the compiled arrayAccesRegexString -var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) - -// Get gets the value using the specified selector and -// returns it inside a new Obj object. -// -// If it cannot find the value, Get will return a nil -// value inside an instance of Obj. -// -// Get can only operate directly on map[string]interface{} and []interface. -// -// Example -// -// To access the title of the third chapter of the second book, do: -// -// o.Get("books[1].chapters[2].title") -func (m Map) Get(selector string) *Value { - rawObj := access(m, selector, nil, false, false) - return &Value{data: rawObj} -} - -// Set sets the value using the specified selector and -// returns the object on which Set was called. -// -// Set can only operate directly on map[string]interface{} and []interface -// -// Example -// -// To set the title of the third chapter of the second book, do: -// -// o.Set("books[1].chapters[2].title","Time to Go") -func (m Map) Set(selector string, value interface{}) Map { - access(m, selector, value, true, false) - return m -} - -// access accesses the object using the selector and performs the -// appropriate action. -func access(current, selector, value interface{}, isSet, panics bool) interface{} { - - switch selector.(type) { - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - - if array, ok := current.([]interface{}); ok { - index := intFromInterface(selector) - - if index >= len(array) { - if panics { - panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) - } - return nil - } - - return array[index] - } - - return nil - - case string: - - selStr := selector.(string) - selSegs := strings.SplitN(selStr, PathSeparator, 2) - thisSel := selSegs[0] - index := -1 - var err error - - // https://github.com/stretchr/objx/issues/12 - if strings.Contains(thisSel, "[") { - - arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) - - if len(arrayMatches) > 0 { - - // Get the key into the map - thisSel = arrayMatches[1] - - // Get the index into the array at the key - index, err = strconv.Atoi(arrayMatches[2]) - - if err != nil { - // This should never happen. If it does, something has gone - // seriously wrong. Panic. - panic("objx: Array index is not an integer. Must use array[int].") - } - - } - } - - if curMap, ok := current.(Map); ok { - current = map[string]interface{}(curMap) - } - - // get the object in question - switch current.(type) { - case map[string]interface{}: - curMSI := current.(map[string]interface{}) - if len(selSegs) <= 1 && isSet { - curMSI[thisSel] = value - return nil - } else { - current = curMSI[thisSel] - } - default: - current = nil - } - - if current == nil && panics { - panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) - } - - // do we need to access the item of an array? - if index > -1 { - if array, ok := current.([]interface{}); ok { - if index < len(array) { - current = array[index] - } else { - if panics { - panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) - } - current = nil - } - } - } - - if len(selSegs) > 1 { - current = access(current, selSegs[1], value, isSet, panics) - } - - } - - return current - -} - -// intFromInterface converts an interface object to the largest -// representation of an unsigned integer using a type switch and -// assertions -func intFromInterface(selector interface{}) int { - var value int - switch selector.(type) { - case int: - value = selector.(int) - case int8: - value = int(selector.(int8)) - case int16: - value = int(selector.(int16)) - case int32: - value = int(selector.(int32)) - case int64: - value = int(selector.(int64)) - case uint: - value = int(selector.(uint)) - case uint8: - value = int(selector.(uint8)) - case uint16: - value = int(selector.(uint16)) - case uint32: - value = int(selector.(uint32)) - case uint64: - value = int(selector.(uint64)) - default: - panic("objx: array access argument is not an integer type (this should never happen)") - } - - return value -} diff --git a/vendor/github.com/stretchr/objx/constants.go b/vendor/github.com/stretchr/objx/constants.go deleted file mode 100644 index f9eb42a25e0b..000000000000 --- a/vendor/github.com/stretchr/objx/constants.go +++ /dev/null @@ -1,13 +0,0 @@ -package objx - -const ( - // PathSeparator is the character used to separate the elements - // of the keypath. - // - // For example, `location.address.city` - PathSeparator string = "." - - // SignatureSeparator is the character that is used to - // separate the Base64 string from the security signature. - SignatureSeparator = "_" -) diff --git a/vendor/github.com/stretchr/objx/conversions.go b/vendor/github.com/stretchr/objx/conversions.go deleted file mode 100644 index 9cdfa9f9f617..000000000000 --- a/vendor/github.com/stretchr/objx/conversions.go +++ /dev/null @@ -1,117 +0,0 @@ -package objx - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/url" -) - -// JSON converts the contained object to a JSON string -// representation -func (m Map) JSON() (string, error) { - - result, err := json.Marshal(m) - - if err != nil { - err = errors.New("objx: JSON encode failed with: " + err.Error()) - } - - return string(result), err - -} - -// MustJSON converts the contained object to a JSON string -// representation and panics if there is an error -func (m Map) MustJSON() string { - result, err := m.JSON() - if err != nil { - panic(err.Error()) - } - return result -} - -// Base64 converts the contained object to a Base64 string -// representation of the JSON string representation -func (m Map) Base64() (string, error) { - - var buf bytes.Buffer - - jsonData, err := m.JSON() - if err != nil { - return "", err - } - - encoder := base64.NewEncoder(base64.StdEncoding, &buf) - encoder.Write([]byte(jsonData)) - encoder.Close() - - return buf.String(), nil - -} - -// MustBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and panics -// if there is an error -func (m Map) MustBase64() string { - result, err := m.Base64() - if err != nil { - panic(err.Error()) - } - return result -} - -// SignedBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and signs it -// using the provided key. -func (m Map) SignedBase64(key string) (string, error) { - - base64, err := m.Base64() - if err != nil { - return "", err - } - - sig := HashWithKey(base64, key) - - return base64 + SignatureSeparator + sig, nil - -} - -// MustSignedBase64 converts the contained object to a Base64 string -// representation of the JSON string representation and signs it -// using the provided key and panics if there is an error -func (m Map) MustSignedBase64(key string) string { - result, err := m.SignedBase64(key) - if err != nil { - panic(err.Error()) - } - return result -} - -/* - URL Query - ------------------------------------------------ -*/ - -// URLValues creates a url.Values object from an Obj. This -// function requires that the wrapped object be a map[string]interface{} -func (m Map) URLValues() url.Values { - - vals := make(url.Values) - - for k, v := range m { - //TODO: can this be done without sprintf? - vals.Set(k, fmt.Sprintf("%v", v)) - } - - return vals -} - -// URLQuery gets an encoded URL query representing the given -// Obj. This function requires that the wrapped object be a -// map[string]interface{} -func (m Map) URLQuery() (string, error) { - return m.URLValues().Encode(), nil -} diff --git a/vendor/github.com/stretchr/objx/doc.go b/vendor/github.com/stretchr/objx/doc.go deleted file mode 100644 index 47bf85e46349..000000000000 --- a/vendor/github.com/stretchr/objx/doc.go +++ /dev/null @@ -1,72 +0,0 @@ -// objx - Go package for dealing with maps, slices, JSON and other data. -// -// Overview -// -// Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes -// a powerful `Get` method (among others) that allows you to easily and quickly get -// access to data within the map, without having to worry too much about type assertions, -// missing data, default values etc. -// -// Pattern -// -// Objx uses a preditable pattern to make access data from within `map[string]interface{}'s -// easy. -// -// Call one of the `objx.` functions to create your `objx.Map` to get going: -// -// m, err := objx.FromJSON(json) -// -// NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, -// the rest will be optimistic and try to figure things out without panicking. -// -// Use `Get` to access the value you're interested in. You can use dot and array -// notation too: -// -// m.Get("places[0].latlng") -// -// Once you have saught the `Value` you're interested in, you can use the `Is*` methods -// to determine its type. -// -// if m.Get("code").IsStr() { /* ... */ } -// -// Or you can just assume the type, and use one of the strong type methods to -// extract the real value: -// -// m.Get("code").Int() -// -// If there's no value there (or if it's the wrong type) then a default value -// will be returned, or you can be explicit about the default value. -// -// Get("code").Int(-1) -// -// If you're dealing with a slice of data as a value, Objx provides many useful -// methods for iterating, manipulating and selecting that data. You can find out more -// by exploring the index below. -// -// Reading data -// -// A simple example of how to use Objx: -// -// // use MustFromJSON to make an objx.Map from some JSON -// m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) -// -// // get the details -// name := m.Get("name").Str() -// age := m.Get("age").Int() -// -// // get their nickname (or use their name if they -// // don't have one) -// nickname := m.Get("nickname").Str(name) -// -// Ranging -// -// Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For -// example, to `range` the data, do what you would expect: -// -// m := objx.MustFromJSON(json) -// for key, value := range m { -// -// /* ... do your magic ... */ -// -// } -package objx diff --git a/vendor/github.com/stretchr/objx/map.go b/vendor/github.com/stretchr/objx/map.go deleted file mode 100644 index eb6ed8e285cc..000000000000 --- a/vendor/github.com/stretchr/objx/map.go +++ /dev/null @@ -1,222 +0,0 @@ -package objx - -import ( - "encoding/base64" - "encoding/json" - "errors" - "io/ioutil" - "net/url" - "strings" -) - -// MSIConvertable is an interface that defines methods for converting your -// custom types to a map[string]interface{} representation. -type MSIConvertable interface { - // MSI gets a map[string]interface{} (msi) representing the - // object. - MSI() map[string]interface{} -} - -// Map provides extended functionality for working with -// untyped data, in particular map[string]interface (msi). -type Map map[string]interface{} - -// Value returns the internal value instance -func (m Map) Value() *Value { - return &Value{data: m} -} - -// Nil represents a nil Map. -var Nil Map = New(nil) - -// New creates a new Map containing the map[string]interface{} in the data argument. -// If the data argument is not a map[string]interface, New attempts to call the -// MSI() method on the MSIConvertable interface to create one. -func New(data interface{}) Map { - if _, ok := data.(map[string]interface{}); !ok { - if converter, ok := data.(MSIConvertable); ok { - data = converter.MSI() - } else { - return nil - } - } - return Map(data.(map[string]interface{})) -} - -// MSI creates a map[string]interface{} and puts it inside a new Map. -// -// The arguments follow a key, value pattern. -// -// Panics -// -// Panics if any key arugment is non-string or if there are an odd number of arguments. -// -// Example -// -// To easily create Maps: -// -// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) -// -// // creates an Map equivalent to -// m := objx.New(map[string]interface{}{"name": "Mat", "age": 29, "subobj": map[string]interface{}{"active": true}}) -func MSI(keyAndValuePairs ...interface{}) Map { - - newMap := make(map[string]interface{}) - keyAndValuePairsLen := len(keyAndValuePairs) - - if keyAndValuePairsLen%2 != 0 { - panic("objx: MSI must have an even number of arguments following the 'key, value' pattern.") - } - - for i := 0; i < keyAndValuePairsLen; i = i + 2 { - - key := keyAndValuePairs[i] - value := keyAndValuePairs[i+1] - - // make sure the key is a string - keyString, keyStringOK := key.(string) - if !keyStringOK { - panic("objx: MSI must follow 'string, interface{}' pattern. " + keyString + " is not a valid key.") - } - - newMap[keyString] = value - - } - - return New(newMap) -} - -// ****** Conversion Constructors - -// MustFromJSON creates a new Map containing the data specified in the -// jsonString. -// -// Panics if the JSON is invalid. -func MustFromJSON(jsonString string) Map { - o, err := FromJSON(jsonString) - - if err != nil { - panic("objx: MustFromJSON failed with error: " + err.Error()) - } - - return o -} - -// FromJSON creates a new Map containing the data specified in the -// jsonString. -// -// Returns an error if the JSON is invalid. -func FromJSON(jsonString string) (Map, error) { - - var data interface{} - err := json.Unmarshal([]byte(jsonString), &data) - - if err != nil { - return Nil, err - } - - return New(data), nil - -} - -// FromBase64 creates a new Obj containing the data specified -// in the Base64 string. -// -// The string is an encoded JSON string returned by Base64 -func FromBase64(base64String string) (Map, error) { - - decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) - - decoded, err := ioutil.ReadAll(decoder) - if err != nil { - return nil, err - } - - return FromJSON(string(decoded)) -} - -// MustFromBase64 creates a new Obj containing the data specified -// in the Base64 string and panics if there is an error. -// -// The string is an encoded JSON string returned by Base64 -func MustFromBase64(base64String string) Map { - - result, err := FromBase64(base64String) - - if err != nil { - panic("objx: MustFromBase64 failed with error: " + err.Error()) - } - - return result -} - -// FromSignedBase64 creates a new Obj containing the data specified -// in the Base64 string. -// -// The string is an encoded JSON string returned by SignedBase64 -func FromSignedBase64(base64String, key string) (Map, error) { - parts := strings.Split(base64String, SignatureSeparator) - if len(parts) != 2 { - return nil, errors.New("objx: Signed base64 string is malformed.") - } - - sig := HashWithKey(parts[0], key) - if parts[1] != sig { - return nil, errors.New("objx: Signature for base64 data does not match.") - } - - return FromBase64(parts[0]) -} - -// MustFromSignedBase64 creates a new Obj containing the data specified -// in the Base64 string and panics if there is an error. -// -// The string is an encoded JSON string returned by Base64 -func MustFromSignedBase64(base64String, key string) Map { - - result, err := FromSignedBase64(base64String, key) - - if err != nil { - panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) - } - - return result -} - -// FromURLQuery generates a new Obj by parsing the specified -// query. -// -// For queries with multiple values, the first value is selected. -func FromURLQuery(query string) (Map, error) { - - vals, err := url.ParseQuery(query) - - if err != nil { - return nil, err - } - - m := make(map[string]interface{}) - for k, vals := range vals { - m[k] = vals[0] - } - - return New(m), nil -} - -// MustFromURLQuery generates a new Obj by parsing the specified -// query. -// -// For queries with multiple values, the first value is selected. -// -// Panics if it encounters an error -func MustFromURLQuery(query string) Map { - - o, err := FromURLQuery(query) - - if err != nil { - panic("objx: MustFromURLQuery failed with error: " + err.Error()) - } - - return o - -} diff --git a/vendor/github.com/stretchr/objx/mutations.go b/vendor/github.com/stretchr/objx/mutations.go deleted file mode 100644 index b35c86392bf8..000000000000 --- a/vendor/github.com/stretchr/objx/mutations.go +++ /dev/null @@ -1,81 +0,0 @@ -package objx - -// Exclude returns a new Map with the keys in the specified []string -// excluded. -func (d Map) Exclude(exclude []string) Map { - - excluded := make(Map) - for k, v := range d { - var shouldInclude bool = true - for _, toExclude := range exclude { - if k == toExclude { - shouldInclude = false - break - } - } - if shouldInclude { - excluded[k] = v - } - } - - return excluded -} - -// Copy creates a shallow copy of the Obj. -func (m Map) Copy() Map { - copied := make(map[string]interface{}) - for k, v := range m { - copied[k] = v - } - return New(copied) -} - -// Merge blends the specified map with a copy of this map and returns the result. -// -// Keys that appear in both will be selected from the specified map. -// This method requires that the wrapped object be a map[string]interface{} -func (m Map) Merge(merge Map) Map { - return m.Copy().MergeHere(merge) -} - -// Merge blends the specified map with this map and returns the current map. -// -// Keys that appear in both will be selected from the specified map. The original map -// will be modified. This method requires that -// the wrapped object be a map[string]interface{} -func (m Map) MergeHere(merge Map) Map { - - for k, v := range merge { - m[k] = v - } - - return m - -} - -// Transform builds a new Obj giving the transformer a chance -// to change the keys and values as it goes. This method requires that -// the wrapped object be a map[string]interface{} -func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { - newMap := make(map[string]interface{}) - for k, v := range m { - modifiedKey, modifiedVal := transformer(k, v) - newMap[modifiedKey] = modifiedVal - } - return New(newMap) -} - -// TransformKeys builds a new map using the specified key mapping. -// -// Unspecified keys will be unaltered. -// This method requires that the wrapped object be a map[string]interface{} -func (m Map) TransformKeys(mapping map[string]string) Map { - return m.Transform(func(key string, value interface{}) (string, interface{}) { - - if newKey, ok := mapping[key]; ok { - return newKey, value - } - - return key, value - }) -} diff --git a/vendor/github.com/stretchr/objx/security.go b/vendor/github.com/stretchr/objx/security.go deleted file mode 100644 index fdd6be9cfb35..000000000000 --- a/vendor/github.com/stretchr/objx/security.go +++ /dev/null @@ -1,14 +0,0 @@ -package objx - -import ( - "crypto/sha1" - "encoding/hex" -) - -// HashWithKey hashes the specified string using the security -// key. -func HashWithKey(data, key string) string { - hash := sha1.New() - hash.Write([]byte(data + ":" + key)) - return hex.EncodeToString(hash.Sum(nil)) -} diff --git a/vendor/github.com/stretchr/objx/tests.go b/vendor/github.com/stretchr/objx/tests.go deleted file mode 100644 index d9e0b479a4c0..000000000000 --- a/vendor/github.com/stretchr/objx/tests.go +++ /dev/null @@ -1,17 +0,0 @@ -package objx - -// Has gets whether there is something at the specified selector -// or not. -// -// If m is nil, Has will always return false. -func (m Map) Has(selector string) bool { - if m == nil { - return false - } - return !m.Get(selector).IsNil() -} - -// IsNil gets whether the data is nil or not. -func (v *Value) IsNil() bool { - return v == nil || v.data == nil -} diff --git a/vendor/github.com/stretchr/objx/type_specific_codegen.go b/vendor/github.com/stretchr/objx/type_specific_codegen.go deleted file mode 100644 index f3ecb29b9503..000000000000 --- a/vendor/github.com/stretchr/objx/type_specific_codegen.go +++ /dev/null @@ -1,2881 +0,0 @@ -package objx - -/* - Inter (interface{} and []interface{}) - -------------------------------------------------- -*/ - -// Inter gets the value as a interface{}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Inter(optionalDefault ...interface{}) interface{} { - if s, ok := v.data.(interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInter gets the value as a interface{}. -// -// Panics if the object is not a interface{}. -func (v *Value) MustInter() interface{} { - return v.data.(interface{}) -} - -// InterSlice gets the value as a []interface{}, returns the optionalDefault -// value or nil if the value is not a []interface{}. -func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { - if s, ok := v.data.([]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInterSlice gets the value as a []interface{}. -// -// Panics if the object is not a []interface{}. -func (v *Value) MustInterSlice() []interface{} { - return v.data.([]interface{}) -} - -// IsInter gets whether the object contained is a interface{} or not. -func (v *Value) IsInter() bool { - _, ok := v.data.(interface{}) - return ok -} - -// IsInterSlice gets whether the object contained is a []interface{} or not. -func (v *Value) IsInterSlice() bool { - _, ok := v.data.([]interface{}) - return ok -} - -// EachInter calls the specified callback for each object -// in the []interface{}. -// -// Panics if the object is the wrong type. -func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { - - for index, val := range v.MustInterSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInter uses the specified decider function to select items -// from the []interface{}. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { - - var selected []interface{} - - v.EachInter(func(index int, val interface{}) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInter uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]interface{}. -func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { - - groups := make(map[string][]interface{}) - - v.EachInter(func(index int, val interface{}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]interface{}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInter uses the specified function to replace each interface{}s -// by iterating each item. The data in the returned result will be a -// []interface{} containing the replaced items. -func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { - - arr := v.MustInterSlice() - replaced := make([]interface{}, len(arr)) - - v.EachInter(func(index int, val interface{}) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInter uses the specified collector function to collect a value -// for each of the interface{}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { - - arr := v.MustInterSlice() - collected := make([]interface{}, len(arr)) - - v.EachInter(func(index int, val interface{}) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - MSI (map[string]interface{} and []map[string]interface{}) - -------------------------------------------------- -*/ - -// MSI gets the value as a map[string]interface{}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { - if s, ok := v.data.(map[string]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustMSI gets the value as a map[string]interface{}. -// -// Panics if the object is not a map[string]interface{}. -func (v *Value) MustMSI() map[string]interface{} { - return v.data.(map[string]interface{}) -} - -// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault -// value or nil if the value is not a []map[string]interface{}. -func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { - if s, ok := v.data.([]map[string]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustMSISlice gets the value as a []map[string]interface{}. -// -// Panics if the object is not a []map[string]interface{}. -func (v *Value) MustMSISlice() []map[string]interface{} { - return v.data.([]map[string]interface{}) -} - -// IsMSI gets whether the object contained is a map[string]interface{} or not. -func (v *Value) IsMSI() bool { - _, ok := v.data.(map[string]interface{}) - return ok -} - -// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. -func (v *Value) IsMSISlice() bool { - _, ok := v.data.([]map[string]interface{}) - return ok -} - -// EachMSI calls the specified callback for each object -// in the []map[string]interface{}. -// -// Panics if the object is the wrong type. -func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { - - for index, val := range v.MustMSISlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereMSI uses the specified decider function to select items -// from the []map[string]interface{}. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { - - var selected []map[string]interface{} - - v.EachMSI(func(index int, val map[string]interface{}) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupMSI uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]map[string]interface{}. -func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { - - groups := make(map[string][]map[string]interface{}) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]map[string]interface{}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceMSI uses the specified function to replace each map[string]interface{}s -// by iterating each item. The data in the returned result will be a -// []map[string]interface{} containing the replaced items. -func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { - - arr := v.MustMSISlice() - replaced := make([]map[string]interface{}, len(arr)) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectMSI uses the specified collector function to collect a value -// for each of the map[string]interface{}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { - - arr := v.MustMSISlice() - collected := make([]interface{}, len(arr)) - - v.EachMSI(func(index int, val map[string]interface{}) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - ObjxMap ((Map) and [](Map)) - -------------------------------------------------- -*/ - -// ObjxMap gets the value as a (Map), returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { - if s, ok := v.data.((Map)); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return New(nil) -} - -// MustObjxMap gets the value as a (Map). -// -// Panics if the object is not a (Map). -func (v *Value) MustObjxMap() Map { - return v.data.((Map)) -} - -// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault -// value or nil if the value is not a [](Map). -func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { - if s, ok := v.data.([](Map)); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustObjxMapSlice gets the value as a [](Map). -// -// Panics if the object is not a [](Map). -func (v *Value) MustObjxMapSlice() [](Map) { - return v.data.([](Map)) -} - -// IsObjxMap gets whether the object contained is a (Map) or not. -func (v *Value) IsObjxMap() bool { - _, ok := v.data.((Map)) - return ok -} - -// IsObjxMapSlice gets whether the object contained is a [](Map) or not. -func (v *Value) IsObjxMapSlice() bool { - _, ok := v.data.([](Map)) - return ok -} - -// EachObjxMap calls the specified callback for each object -// in the [](Map). -// -// Panics if the object is the wrong type. -func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { - - for index, val := range v.MustObjxMapSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereObjxMap uses the specified decider function to select items -// from the [](Map). The object contained in the result will contain -// only the selected items. -func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { - - var selected [](Map) - - v.EachObjxMap(func(index int, val Map) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupObjxMap uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][](Map). -func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { - - groups := make(map[string][](Map)) - - v.EachObjxMap(func(index int, val Map) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([](Map), 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceObjxMap uses the specified function to replace each (Map)s -// by iterating each item. The data in the returned result will be a -// [](Map) containing the replaced items. -func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { - - arr := v.MustObjxMapSlice() - replaced := make([](Map), len(arr)) - - v.EachObjxMap(func(index int, val Map) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectObjxMap uses the specified collector function to collect a value -// for each of the (Map)s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { - - arr := v.MustObjxMapSlice() - collected := make([]interface{}, len(arr)) - - v.EachObjxMap(func(index int, val Map) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Bool (bool and []bool) - -------------------------------------------------- -*/ - -// Bool gets the value as a bool, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Bool(optionalDefault ...bool) bool { - if s, ok := v.data.(bool); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return false -} - -// MustBool gets the value as a bool. -// -// Panics if the object is not a bool. -func (v *Value) MustBool() bool { - return v.data.(bool) -} - -// BoolSlice gets the value as a []bool, returns the optionalDefault -// value or nil if the value is not a []bool. -func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { - if s, ok := v.data.([]bool); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustBoolSlice gets the value as a []bool. -// -// Panics if the object is not a []bool. -func (v *Value) MustBoolSlice() []bool { - return v.data.([]bool) -} - -// IsBool gets whether the object contained is a bool or not. -func (v *Value) IsBool() bool { - _, ok := v.data.(bool) - return ok -} - -// IsBoolSlice gets whether the object contained is a []bool or not. -func (v *Value) IsBoolSlice() bool { - _, ok := v.data.([]bool) - return ok -} - -// EachBool calls the specified callback for each object -// in the []bool. -// -// Panics if the object is the wrong type. -func (v *Value) EachBool(callback func(int, bool) bool) *Value { - - for index, val := range v.MustBoolSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereBool uses the specified decider function to select items -// from the []bool. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereBool(decider func(int, bool) bool) *Value { - - var selected []bool - - v.EachBool(func(index int, val bool) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupBool uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]bool. -func (v *Value) GroupBool(grouper func(int, bool) string) *Value { - - groups := make(map[string][]bool) - - v.EachBool(func(index int, val bool) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]bool, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceBool uses the specified function to replace each bools -// by iterating each item. The data in the returned result will be a -// []bool containing the replaced items. -func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { - - arr := v.MustBoolSlice() - replaced := make([]bool, len(arr)) - - v.EachBool(func(index int, val bool) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectBool uses the specified collector function to collect a value -// for each of the bools in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { - - arr := v.MustBoolSlice() - collected := make([]interface{}, len(arr)) - - v.EachBool(func(index int, val bool) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Str (string and []string) - -------------------------------------------------- -*/ - -// Str gets the value as a string, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Str(optionalDefault ...string) string { - if s, ok := v.data.(string); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return "" -} - -// MustStr gets the value as a string. -// -// Panics if the object is not a string. -func (v *Value) MustStr() string { - return v.data.(string) -} - -// StrSlice gets the value as a []string, returns the optionalDefault -// value or nil if the value is not a []string. -func (v *Value) StrSlice(optionalDefault ...[]string) []string { - if s, ok := v.data.([]string); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustStrSlice gets the value as a []string. -// -// Panics if the object is not a []string. -func (v *Value) MustStrSlice() []string { - return v.data.([]string) -} - -// IsStr gets whether the object contained is a string or not. -func (v *Value) IsStr() bool { - _, ok := v.data.(string) - return ok -} - -// IsStrSlice gets whether the object contained is a []string or not. -func (v *Value) IsStrSlice() bool { - _, ok := v.data.([]string) - return ok -} - -// EachStr calls the specified callback for each object -// in the []string. -// -// Panics if the object is the wrong type. -func (v *Value) EachStr(callback func(int, string) bool) *Value { - - for index, val := range v.MustStrSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereStr uses the specified decider function to select items -// from the []string. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereStr(decider func(int, string) bool) *Value { - - var selected []string - - v.EachStr(func(index int, val string) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupStr uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]string. -func (v *Value) GroupStr(grouper func(int, string) string) *Value { - - groups := make(map[string][]string) - - v.EachStr(func(index int, val string) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]string, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceStr uses the specified function to replace each strings -// by iterating each item. The data in the returned result will be a -// []string containing the replaced items. -func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { - - arr := v.MustStrSlice() - replaced := make([]string, len(arr)) - - v.EachStr(func(index int, val string) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectStr uses the specified collector function to collect a value -// for each of the strings in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { - - arr := v.MustStrSlice() - collected := make([]interface{}, len(arr)) - - v.EachStr(func(index int, val string) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int (int and []int) - -------------------------------------------------- -*/ - -// Int gets the value as a int, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int(optionalDefault ...int) int { - if s, ok := v.data.(int); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt gets the value as a int. -// -// Panics if the object is not a int. -func (v *Value) MustInt() int { - return v.data.(int) -} - -// IntSlice gets the value as a []int, returns the optionalDefault -// value or nil if the value is not a []int. -func (v *Value) IntSlice(optionalDefault ...[]int) []int { - if s, ok := v.data.([]int); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustIntSlice gets the value as a []int. -// -// Panics if the object is not a []int. -func (v *Value) MustIntSlice() []int { - return v.data.([]int) -} - -// IsInt gets whether the object contained is a int or not. -func (v *Value) IsInt() bool { - _, ok := v.data.(int) - return ok -} - -// IsIntSlice gets whether the object contained is a []int or not. -func (v *Value) IsIntSlice() bool { - _, ok := v.data.([]int) - return ok -} - -// EachInt calls the specified callback for each object -// in the []int. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt(callback func(int, int) bool) *Value { - - for index, val := range v.MustIntSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt uses the specified decider function to select items -// from the []int. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt(decider func(int, int) bool) *Value { - - var selected []int - - v.EachInt(func(index int, val int) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int. -func (v *Value) GroupInt(grouper func(int, int) string) *Value { - - groups := make(map[string][]int) - - v.EachInt(func(index int, val int) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt uses the specified function to replace each ints -// by iterating each item. The data in the returned result will be a -// []int containing the replaced items. -func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { - - arr := v.MustIntSlice() - replaced := make([]int, len(arr)) - - v.EachInt(func(index int, val int) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt uses the specified collector function to collect a value -// for each of the ints in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { - - arr := v.MustIntSlice() - collected := make([]interface{}, len(arr)) - - v.EachInt(func(index int, val int) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int8 (int8 and []int8) - -------------------------------------------------- -*/ - -// Int8 gets the value as a int8, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int8(optionalDefault ...int8) int8 { - if s, ok := v.data.(int8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt8 gets the value as a int8. -// -// Panics if the object is not a int8. -func (v *Value) MustInt8() int8 { - return v.data.(int8) -} - -// Int8Slice gets the value as a []int8, returns the optionalDefault -// value or nil if the value is not a []int8. -func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { - if s, ok := v.data.([]int8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt8Slice gets the value as a []int8. -// -// Panics if the object is not a []int8. -func (v *Value) MustInt8Slice() []int8 { - return v.data.([]int8) -} - -// IsInt8 gets whether the object contained is a int8 or not. -func (v *Value) IsInt8() bool { - _, ok := v.data.(int8) - return ok -} - -// IsInt8Slice gets whether the object contained is a []int8 or not. -func (v *Value) IsInt8Slice() bool { - _, ok := v.data.([]int8) - return ok -} - -// EachInt8 calls the specified callback for each object -// in the []int8. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt8(callback func(int, int8) bool) *Value { - - for index, val := range v.MustInt8Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt8 uses the specified decider function to select items -// from the []int8. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { - - var selected []int8 - - v.EachInt8(func(index int, val int8) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt8 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int8. -func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { - - groups := make(map[string][]int8) - - v.EachInt8(func(index int, val int8) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int8, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt8 uses the specified function to replace each int8s -// by iterating each item. The data in the returned result will be a -// []int8 containing the replaced items. -func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { - - arr := v.MustInt8Slice() - replaced := make([]int8, len(arr)) - - v.EachInt8(func(index int, val int8) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt8 uses the specified collector function to collect a value -// for each of the int8s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { - - arr := v.MustInt8Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt8(func(index int, val int8) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int16 (int16 and []int16) - -------------------------------------------------- -*/ - -// Int16 gets the value as a int16, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int16(optionalDefault ...int16) int16 { - if s, ok := v.data.(int16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt16 gets the value as a int16. -// -// Panics if the object is not a int16. -func (v *Value) MustInt16() int16 { - return v.data.(int16) -} - -// Int16Slice gets the value as a []int16, returns the optionalDefault -// value or nil if the value is not a []int16. -func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { - if s, ok := v.data.([]int16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt16Slice gets the value as a []int16. -// -// Panics if the object is not a []int16. -func (v *Value) MustInt16Slice() []int16 { - return v.data.([]int16) -} - -// IsInt16 gets whether the object contained is a int16 or not. -func (v *Value) IsInt16() bool { - _, ok := v.data.(int16) - return ok -} - -// IsInt16Slice gets whether the object contained is a []int16 or not. -func (v *Value) IsInt16Slice() bool { - _, ok := v.data.([]int16) - return ok -} - -// EachInt16 calls the specified callback for each object -// in the []int16. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt16(callback func(int, int16) bool) *Value { - - for index, val := range v.MustInt16Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt16 uses the specified decider function to select items -// from the []int16. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { - - var selected []int16 - - v.EachInt16(func(index int, val int16) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt16 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int16. -func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { - - groups := make(map[string][]int16) - - v.EachInt16(func(index int, val int16) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int16, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt16 uses the specified function to replace each int16s -// by iterating each item. The data in the returned result will be a -// []int16 containing the replaced items. -func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { - - arr := v.MustInt16Slice() - replaced := make([]int16, len(arr)) - - v.EachInt16(func(index int, val int16) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt16 uses the specified collector function to collect a value -// for each of the int16s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { - - arr := v.MustInt16Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt16(func(index int, val int16) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int32 (int32 and []int32) - -------------------------------------------------- -*/ - -// Int32 gets the value as a int32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int32(optionalDefault ...int32) int32 { - if s, ok := v.data.(int32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt32 gets the value as a int32. -// -// Panics if the object is not a int32. -func (v *Value) MustInt32() int32 { - return v.data.(int32) -} - -// Int32Slice gets the value as a []int32, returns the optionalDefault -// value or nil if the value is not a []int32. -func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { - if s, ok := v.data.([]int32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt32Slice gets the value as a []int32. -// -// Panics if the object is not a []int32. -func (v *Value) MustInt32Slice() []int32 { - return v.data.([]int32) -} - -// IsInt32 gets whether the object contained is a int32 or not. -func (v *Value) IsInt32() bool { - _, ok := v.data.(int32) - return ok -} - -// IsInt32Slice gets whether the object contained is a []int32 or not. -func (v *Value) IsInt32Slice() bool { - _, ok := v.data.([]int32) - return ok -} - -// EachInt32 calls the specified callback for each object -// in the []int32. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt32(callback func(int, int32) bool) *Value { - - for index, val := range v.MustInt32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt32 uses the specified decider function to select items -// from the []int32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { - - var selected []int32 - - v.EachInt32(func(index int, val int32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int32. -func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { - - groups := make(map[string][]int32) - - v.EachInt32(func(index int, val int32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt32 uses the specified function to replace each int32s -// by iterating each item. The data in the returned result will be a -// []int32 containing the replaced items. -func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { - - arr := v.MustInt32Slice() - replaced := make([]int32, len(arr)) - - v.EachInt32(func(index int, val int32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt32 uses the specified collector function to collect a value -// for each of the int32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { - - arr := v.MustInt32Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt32(func(index int, val int32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Int64 (int64 and []int64) - -------------------------------------------------- -*/ - -// Int64 gets the value as a int64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Int64(optionalDefault ...int64) int64 { - if s, ok := v.data.(int64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustInt64 gets the value as a int64. -// -// Panics if the object is not a int64. -func (v *Value) MustInt64() int64 { - return v.data.(int64) -} - -// Int64Slice gets the value as a []int64, returns the optionalDefault -// value or nil if the value is not a []int64. -func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { - if s, ok := v.data.([]int64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustInt64Slice gets the value as a []int64. -// -// Panics if the object is not a []int64. -func (v *Value) MustInt64Slice() []int64 { - return v.data.([]int64) -} - -// IsInt64 gets whether the object contained is a int64 or not. -func (v *Value) IsInt64() bool { - _, ok := v.data.(int64) - return ok -} - -// IsInt64Slice gets whether the object contained is a []int64 or not. -func (v *Value) IsInt64Slice() bool { - _, ok := v.data.([]int64) - return ok -} - -// EachInt64 calls the specified callback for each object -// in the []int64. -// -// Panics if the object is the wrong type. -func (v *Value) EachInt64(callback func(int, int64) bool) *Value { - - for index, val := range v.MustInt64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereInt64 uses the specified decider function to select items -// from the []int64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { - - var selected []int64 - - v.EachInt64(func(index int, val int64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupInt64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]int64. -func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { - - groups := make(map[string][]int64) - - v.EachInt64(func(index int, val int64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]int64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceInt64 uses the specified function to replace each int64s -// by iterating each item. The data in the returned result will be a -// []int64 containing the replaced items. -func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { - - arr := v.MustInt64Slice() - replaced := make([]int64, len(arr)) - - v.EachInt64(func(index int, val int64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectInt64 uses the specified collector function to collect a value -// for each of the int64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { - - arr := v.MustInt64Slice() - collected := make([]interface{}, len(arr)) - - v.EachInt64(func(index int, val int64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint (uint and []uint) - -------------------------------------------------- -*/ - -// Uint gets the value as a uint, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint(optionalDefault ...uint) uint { - if s, ok := v.data.(uint); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint gets the value as a uint. -// -// Panics if the object is not a uint. -func (v *Value) MustUint() uint { - return v.data.(uint) -} - -// UintSlice gets the value as a []uint, returns the optionalDefault -// value or nil if the value is not a []uint. -func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { - if s, ok := v.data.([]uint); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUintSlice gets the value as a []uint. -// -// Panics if the object is not a []uint. -func (v *Value) MustUintSlice() []uint { - return v.data.([]uint) -} - -// IsUint gets whether the object contained is a uint or not. -func (v *Value) IsUint() bool { - _, ok := v.data.(uint) - return ok -} - -// IsUintSlice gets whether the object contained is a []uint or not. -func (v *Value) IsUintSlice() bool { - _, ok := v.data.([]uint) - return ok -} - -// EachUint calls the specified callback for each object -// in the []uint. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint(callback func(int, uint) bool) *Value { - - for index, val := range v.MustUintSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint uses the specified decider function to select items -// from the []uint. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint(decider func(int, uint) bool) *Value { - - var selected []uint - - v.EachUint(func(index int, val uint) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint. -func (v *Value) GroupUint(grouper func(int, uint) string) *Value { - - groups := make(map[string][]uint) - - v.EachUint(func(index int, val uint) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint uses the specified function to replace each uints -// by iterating each item. The data in the returned result will be a -// []uint containing the replaced items. -func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { - - arr := v.MustUintSlice() - replaced := make([]uint, len(arr)) - - v.EachUint(func(index int, val uint) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint uses the specified collector function to collect a value -// for each of the uints in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { - - arr := v.MustUintSlice() - collected := make([]interface{}, len(arr)) - - v.EachUint(func(index int, val uint) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint8 (uint8 and []uint8) - -------------------------------------------------- -*/ - -// Uint8 gets the value as a uint8, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint8(optionalDefault ...uint8) uint8 { - if s, ok := v.data.(uint8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint8 gets the value as a uint8. -// -// Panics if the object is not a uint8. -func (v *Value) MustUint8() uint8 { - return v.data.(uint8) -} - -// Uint8Slice gets the value as a []uint8, returns the optionalDefault -// value or nil if the value is not a []uint8. -func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { - if s, ok := v.data.([]uint8); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint8Slice gets the value as a []uint8. -// -// Panics if the object is not a []uint8. -func (v *Value) MustUint8Slice() []uint8 { - return v.data.([]uint8) -} - -// IsUint8 gets whether the object contained is a uint8 or not. -func (v *Value) IsUint8() bool { - _, ok := v.data.(uint8) - return ok -} - -// IsUint8Slice gets whether the object contained is a []uint8 or not. -func (v *Value) IsUint8Slice() bool { - _, ok := v.data.([]uint8) - return ok -} - -// EachUint8 calls the specified callback for each object -// in the []uint8. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { - - for index, val := range v.MustUint8Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint8 uses the specified decider function to select items -// from the []uint8. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { - - var selected []uint8 - - v.EachUint8(func(index int, val uint8) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint8 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint8. -func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { - - groups := make(map[string][]uint8) - - v.EachUint8(func(index int, val uint8) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint8, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint8 uses the specified function to replace each uint8s -// by iterating each item. The data in the returned result will be a -// []uint8 containing the replaced items. -func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { - - arr := v.MustUint8Slice() - replaced := make([]uint8, len(arr)) - - v.EachUint8(func(index int, val uint8) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint8 uses the specified collector function to collect a value -// for each of the uint8s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { - - arr := v.MustUint8Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint8(func(index int, val uint8) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint16 (uint16 and []uint16) - -------------------------------------------------- -*/ - -// Uint16 gets the value as a uint16, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint16(optionalDefault ...uint16) uint16 { - if s, ok := v.data.(uint16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint16 gets the value as a uint16. -// -// Panics if the object is not a uint16. -func (v *Value) MustUint16() uint16 { - return v.data.(uint16) -} - -// Uint16Slice gets the value as a []uint16, returns the optionalDefault -// value or nil if the value is not a []uint16. -func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { - if s, ok := v.data.([]uint16); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint16Slice gets the value as a []uint16. -// -// Panics if the object is not a []uint16. -func (v *Value) MustUint16Slice() []uint16 { - return v.data.([]uint16) -} - -// IsUint16 gets whether the object contained is a uint16 or not. -func (v *Value) IsUint16() bool { - _, ok := v.data.(uint16) - return ok -} - -// IsUint16Slice gets whether the object contained is a []uint16 or not. -func (v *Value) IsUint16Slice() bool { - _, ok := v.data.([]uint16) - return ok -} - -// EachUint16 calls the specified callback for each object -// in the []uint16. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { - - for index, val := range v.MustUint16Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint16 uses the specified decider function to select items -// from the []uint16. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { - - var selected []uint16 - - v.EachUint16(func(index int, val uint16) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint16 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint16. -func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { - - groups := make(map[string][]uint16) - - v.EachUint16(func(index int, val uint16) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint16, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint16 uses the specified function to replace each uint16s -// by iterating each item. The data in the returned result will be a -// []uint16 containing the replaced items. -func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { - - arr := v.MustUint16Slice() - replaced := make([]uint16, len(arr)) - - v.EachUint16(func(index int, val uint16) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint16 uses the specified collector function to collect a value -// for each of the uint16s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { - - arr := v.MustUint16Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint16(func(index int, val uint16) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint32 (uint32 and []uint32) - -------------------------------------------------- -*/ - -// Uint32 gets the value as a uint32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint32(optionalDefault ...uint32) uint32 { - if s, ok := v.data.(uint32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint32 gets the value as a uint32. -// -// Panics if the object is not a uint32. -func (v *Value) MustUint32() uint32 { - return v.data.(uint32) -} - -// Uint32Slice gets the value as a []uint32, returns the optionalDefault -// value or nil if the value is not a []uint32. -func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { - if s, ok := v.data.([]uint32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint32Slice gets the value as a []uint32. -// -// Panics if the object is not a []uint32. -func (v *Value) MustUint32Slice() []uint32 { - return v.data.([]uint32) -} - -// IsUint32 gets whether the object contained is a uint32 or not. -func (v *Value) IsUint32() bool { - _, ok := v.data.(uint32) - return ok -} - -// IsUint32Slice gets whether the object contained is a []uint32 or not. -func (v *Value) IsUint32Slice() bool { - _, ok := v.data.([]uint32) - return ok -} - -// EachUint32 calls the specified callback for each object -// in the []uint32. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { - - for index, val := range v.MustUint32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint32 uses the specified decider function to select items -// from the []uint32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { - - var selected []uint32 - - v.EachUint32(func(index int, val uint32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint32. -func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { - - groups := make(map[string][]uint32) - - v.EachUint32(func(index int, val uint32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint32 uses the specified function to replace each uint32s -// by iterating each item. The data in the returned result will be a -// []uint32 containing the replaced items. -func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { - - arr := v.MustUint32Slice() - replaced := make([]uint32, len(arr)) - - v.EachUint32(func(index int, val uint32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint32 uses the specified collector function to collect a value -// for each of the uint32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { - - arr := v.MustUint32Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint32(func(index int, val uint32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uint64 (uint64 and []uint64) - -------------------------------------------------- -*/ - -// Uint64 gets the value as a uint64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uint64(optionalDefault ...uint64) uint64 { - if s, ok := v.data.(uint64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUint64 gets the value as a uint64. -// -// Panics if the object is not a uint64. -func (v *Value) MustUint64() uint64 { - return v.data.(uint64) -} - -// Uint64Slice gets the value as a []uint64, returns the optionalDefault -// value or nil if the value is not a []uint64. -func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { - if s, ok := v.data.([]uint64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUint64Slice gets the value as a []uint64. -// -// Panics if the object is not a []uint64. -func (v *Value) MustUint64Slice() []uint64 { - return v.data.([]uint64) -} - -// IsUint64 gets whether the object contained is a uint64 or not. -func (v *Value) IsUint64() bool { - _, ok := v.data.(uint64) - return ok -} - -// IsUint64Slice gets whether the object contained is a []uint64 or not. -func (v *Value) IsUint64Slice() bool { - _, ok := v.data.([]uint64) - return ok -} - -// EachUint64 calls the specified callback for each object -// in the []uint64. -// -// Panics if the object is the wrong type. -func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { - - for index, val := range v.MustUint64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUint64 uses the specified decider function to select items -// from the []uint64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { - - var selected []uint64 - - v.EachUint64(func(index int, val uint64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUint64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uint64. -func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { - - groups := make(map[string][]uint64) - - v.EachUint64(func(index int, val uint64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uint64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUint64 uses the specified function to replace each uint64s -// by iterating each item. The data in the returned result will be a -// []uint64 containing the replaced items. -func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { - - arr := v.MustUint64Slice() - replaced := make([]uint64, len(arr)) - - v.EachUint64(func(index int, val uint64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUint64 uses the specified collector function to collect a value -// for each of the uint64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { - - arr := v.MustUint64Slice() - collected := make([]interface{}, len(arr)) - - v.EachUint64(func(index int, val uint64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Uintptr (uintptr and []uintptr) - -------------------------------------------------- -*/ - -// Uintptr gets the value as a uintptr, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { - if s, ok := v.data.(uintptr); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustUintptr gets the value as a uintptr. -// -// Panics if the object is not a uintptr. -func (v *Value) MustUintptr() uintptr { - return v.data.(uintptr) -} - -// UintptrSlice gets the value as a []uintptr, returns the optionalDefault -// value or nil if the value is not a []uintptr. -func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { - if s, ok := v.data.([]uintptr); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustUintptrSlice gets the value as a []uintptr. -// -// Panics if the object is not a []uintptr. -func (v *Value) MustUintptrSlice() []uintptr { - return v.data.([]uintptr) -} - -// IsUintptr gets whether the object contained is a uintptr or not. -func (v *Value) IsUintptr() bool { - _, ok := v.data.(uintptr) - return ok -} - -// IsUintptrSlice gets whether the object contained is a []uintptr or not. -func (v *Value) IsUintptrSlice() bool { - _, ok := v.data.([]uintptr) - return ok -} - -// EachUintptr calls the specified callback for each object -// in the []uintptr. -// -// Panics if the object is the wrong type. -func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { - - for index, val := range v.MustUintptrSlice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereUintptr uses the specified decider function to select items -// from the []uintptr. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { - - var selected []uintptr - - v.EachUintptr(func(index int, val uintptr) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupUintptr uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]uintptr. -func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { - - groups := make(map[string][]uintptr) - - v.EachUintptr(func(index int, val uintptr) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]uintptr, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceUintptr uses the specified function to replace each uintptrs -// by iterating each item. The data in the returned result will be a -// []uintptr containing the replaced items. -func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { - - arr := v.MustUintptrSlice() - replaced := make([]uintptr, len(arr)) - - v.EachUintptr(func(index int, val uintptr) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectUintptr uses the specified collector function to collect a value -// for each of the uintptrs in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { - - arr := v.MustUintptrSlice() - collected := make([]interface{}, len(arr)) - - v.EachUintptr(func(index int, val uintptr) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Float32 (float32 and []float32) - -------------------------------------------------- -*/ - -// Float32 gets the value as a float32, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Float32(optionalDefault ...float32) float32 { - if s, ok := v.data.(float32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustFloat32 gets the value as a float32. -// -// Panics if the object is not a float32. -func (v *Value) MustFloat32() float32 { - return v.data.(float32) -} - -// Float32Slice gets the value as a []float32, returns the optionalDefault -// value or nil if the value is not a []float32. -func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { - if s, ok := v.data.([]float32); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustFloat32Slice gets the value as a []float32. -// -// Panics if the object is not a []float32. -func (v *Value) MustFloat32Slice() []float32 { - return v.data.([]float32) -} - -// IsFloat32 gets whether the object contained is a float32 or not. -func (v *Value) IsFloat32() bool { - _, ok := v.data.(float32) - return ok -} - -// IsFloat32Slice gets whether the object contained is a []float32 or not. -func (v *Value) IsFloat32Slice() bool { - _, ok := v.data.([]float32) - return ok -} - -// EachFloat32 calls the specified callback for each object -// in the []float32. -// -// Panics if the object is the wrong type. -func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { - - for index, val := range v.MustFloat32Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereFloat32 uses the specified decider function to select items -// from the []float32. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { - - var selected []float32 - - v.EachFloat32(func(index int, val float32) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupFloat32 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]float32. -func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { - - groups := make(map[string][]float32) - - v.EachFloat32(func(index int, val float32) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]float32, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceFloat32 uses the specified function to replace each float32s -// by iterating each item. The data in the returned result will be a -// []float32 containing the replaced items. -func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { - - arr := v.MustFloat32Slice() - replaced := make([]float32, len(arr)) - - v.EachFloat32(func(index int, val float32) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectFloat32 uses the specified collector function to collect a value -// for each of the float32s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { - - arr := v.MustFloat32Slice() - collected := make([]interface{}, len(arr)) - - v.EachFloat32(func(index int, val float32) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Float64 (float64 and []float64) - -------------------------------------------------- -*/ - -// Float64 gets the value as a float64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Float64(optionalDefault ...float64) float64 { - if s, ok := v.data.(float64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustFloat64 gets the value as a float64. -// -// Panics if the object is not a float64. -func (v *Value) MustFloat64() float64 { - return v.data.(float64) -} - -// Float64Slice gets the value as a []float64, returns the optionalDefault -// value or nil if the value is not a []float64. -func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { - if s, ok := v.data.([]float64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustFloat64Slice gets the value as a []float64. -// -// Panics if the object is not a []float64. -func (v *Value) MustFloat64Slice() []float64 { - return v.data.([]float64) -} - -// IsFloat64 gets whether the object contained is a float64 or not. -func (v *Value) IsFloat64() bool { - _, ok := v.data.(float64) - return ok -} - -// IsFloat64Slice gets whether the object contained is a []float64 or not. -func (v *Value) IsFloat64Slice() bool { - _, ok := v.data.([]float64) - return ok -} - -// EachFloat64 calls the specified callback for each object -// in the []float64. -// -// Panics if the object is the wrong type. -func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { - - for index, val := range v.MustFloat64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereFloat64 uses the specified decider function to select items -// from the []float64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { - - var selected []float64 - - v.EachFloat64(func(index int, val float64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupFloat64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]float64. -func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { - - groups := make(map[string][]float64) - - v.EachFloat64(func(index int, val float64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]float64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceFloat64 uses the specified function to replace each float64s -// by iterating each item. The data in the returned result will be a -// []float64 containing the replaced items. -func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { - - arr := v.MustFloat64Slice() - replaced := make([]float64, len(arr)) - - v.EachFloat64(func(index int, val float64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectFloat64 uses the specified collector function to collect a value -// for each of the float64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { - - arr := v.MustFloat64Slice() - collected := make([]interface{}, len(arr)) - - v.EachFloat64(func(index int, val float64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Complex64 (complex64 and []complex64) - -------------------------------------------------- -*/ - -// Complex64 gets the value as a complex64, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Complex64(optionalDefault ...complex64) complex64 { - if s, ok := v.data.(complex64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustComplex64 gets the value as a complex64. -// -// Panics if the object is not a complex64. -func (v *Value) MustComplex64() complex64 { - return v.data.(complex64) -} - -// Complex64Slice gets the value as a []complex64, returns the optionalDefault -// value or nil if the value is not a []complex64. -func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { - if s, ok := v.data.([]complex64); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustComplex64Slice gets the value as a []complex64. -// -// Panics if the object is not a []complex64. -func (v *Value) MustComplex64Slice() []complex64 { - return v.data.([]complex64) -} - -// IsComplex64 gets whether the object contained is a complex64 or not. -func (v *Value) IsComplex64() bool { - _, ok := v.data.(complex64) - return ok -} - -// IsComplex64Slice gets whether the object contained is a []complex64 or not. -func (v *Value) IsComplex64Slice() bool { - _, ok := v.data.([]complex64) - return ok -} - -// EachComplex64 calls the specified callback for each object -// in the []complex64. -// -// Panics if the object is the wrong type. -func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { - - for index, val := range v.MustComplex64Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereComplex64 uses the specified decider function to select items -// from the []complex64. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { - - var selected []complex64 - - v.EachComplex64(func(index int, val complex64) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupComplex64 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]complex64. -func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { - - groups := make(map[string][]complex64) - - v.EachComplex64(func(index int, val complex64) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]complex64, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceComplex64 uses the specified function to replace each complex64s -// by iterating each item. The data in the returned result will be a -// []complex64 containing the replaced items. -func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { - - arr := v.MustComplex64Slice() - replaced := make([]complex64, len(arr)) - - v.EachComplex64(func(index int, val complex64) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectComplex64 uses the specified collector function to collect a value -// for each of the complex64s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { - - arr := v.MustComplex64Slice() - collected := make([]interface{}, len(arr)) - - v.EachComplex64(func(index int, val complex64) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} - -/* - Complex128 (complex128 and []complex128) - -------------------------------------------------- -*/ - -// Complex128 gets the value as a complex128, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) Complex128(optionalDefault ...complex128) complex128 { - if s, ok := v.data.(complex128); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return 0 -} - -// MustComplex128 gets the value as a complex128. -// -// Panics if the object is not a complex128. -func (v *Value) MustComplex128() complex128 { - return v.data.(complex128) -} - -// Complex128Slice gets the value as a []complex128, returns the optionalDefault -// value or nil if the value is not a []complex128. -func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { - if s, ok := v.data.([]complex128); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustComplex128Slice gets the value as a []complex128. -// -// Panics if the object is not a []complex128. -func (v *Value) MustComplex128Slice() []complex128 { - return v.data.([]complex128) -} - -// IsComplex128 gets whether the object contained is a complex128 or not. -func (v *Value) IsComplex128() bool { - _, ok := v.data.(complex128) - return ok -} - -// IsComplex128Slice gets whether the object contained is a []complex128 or not. -func (v *Value) IsComplex128Slice() bool { - _, ok := v.data.([]complex128) - return ok -} - -// EachComplex128 calls the specified callback for each object -// in the []complex128. -// -// Panics if the object is the wrong type. -func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { - - for index, val := range v.MustComplex128Slice() { - carryon := callback(index, val) - if carryon == false { - break - } - } - - return v - -} - -// WhereComplex128 uses the specified decider function to select items -// from the []complex128. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { - - var selected []complex128 - - v.EachComplex128(func(index int, val complex128) bool { - shouldSelect := decider(index, val) - if shouldSelect == false { - selected = append(selected, val) - } - return true - }) - - return &Value{data: selected} - -} - -// GroupComplex128 uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]complex128. -func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { - - groups := make(map[string][]complex128) - - v.EachComplex128(func(index int, val complex128) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]complex128, 0) - } - groups[group] = append(groups[group], val) - return true - }) - - return &Value{data: groups} - -} - -// ReplaceComplex128 uses the specified function to replace each complex128s -// by iterating each item. The data in the returned result will be a -// []complex128 containing the replaced items. -func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { - - arr := v.MustComplex128Slice() - replaced := make([]complex128, len(arr)) - - v.EachComplex128(func(index int, val complex128) bool { - replaced[index] = replacer(index, val) - return true - }) - - return &Value{data: replaced} - -} - -// CollectComplex128 uses the specified collector function to collect a value -// for each of the complex128s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { - - arr := v.MustComplex128Slice() - collected := make([]interface{}, len(arr)) - - v.EachComplex128(func(index int, val complex128) bool { - collected[index] = collector(index, val) - return true - }) - - return &Value{data: collected} -} diff --git a/vendor/github.com/stretchr/objx/value.go b/vendor/github.com/stretchr/objx/value.go deleted file mode 100644 index 956a2211d4d5..000000000000 --- a/vendor/github.com/stretchr/objx/value.go +++ /dev/null @@ -1,56 +0,0 @@ -package objx - -import ( - "fmt" - "strconv" -) - -// Value provides methods for extracting interface{} data in various -// types. -type Value struct { - // data contains the raw data being managed by this Value - data interface{} -} - -// Data returns the raw data contained by this Value -func (v *Value) Data() interface{} { - return v.data -} - -// String returns the value always as a string -func (v *Value) String() string { - switch { - case v.IsStr(): - return v.Str() - case v.IsBool(): - return strconv.FormatBool(v.Bool()) - case v.IsFloat32(): - return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32) - case v.IsFloat64(): - return strconv.FormatFloat(v.Float64(), 'f', -1, 64) - case v.IsInt(): - return strconv.FormatInt(int64(v.Int()), 10) - case v.IsInt(): - return strconv.FormatInt(int64(v.Int()), 10) - case v.IsInt8(): - return strconv.FormatInt(int64(v.Int8()), 10) - case v.IsInt16(): - return strconv.FormatInt(int64(v.Int16()), 10) - case v.IsInt32(): - return strconv.FormatInt(int64(v.Int32()), 10) - case v.IsInt64(): - return strconv.FormatInt(v.Int64(), 10) - case v.IsUint(): - return strconv.FormatUint(uint64(v.Uint()), 10) - case v.IsUint8(): - return strconv.FormatUint(uint64(v.Uint8()), 10) - case v.IsUint16(): - return strconv.FormatUint(uint64(v.Uint16()), 10) - case v.IsUint32(): - return strconv.FormatUint(uint64(v.Uint32()), 10) - case v.IsUint64(): - return strconv.FormatUint(v.Uint64(), 10) - } - - return fmt.Sprintf("%#v", v.Data()) -} diff --git a/vendor/github.com/stretchr/testify/LICENCE.txt b/vendor/github.com/stretchr/testify/LICENCE.txt deleted file mode 100644 index 473b670a7c61..000000000000 --- a/vendor/github.com/stretchr/testify/LICENCE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -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/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE deleted file mode 100644 index 473b670a7c61..000000000000 --- a/vendor/github.com/stretchr/testify/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -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/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index e95357d29c8a..000000000000 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,979 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "math" - "reflect" - "regexp" - "runtime" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - - if expected == nil || actual == nil { - return expected == actual - } - - return reflect.DeepEqual(expected, actual) - -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - if actualType == nil { - return false - } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occured in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - return nil - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - parts := strings.Split(file, "/") - dir := parts[len(parts)-2] - file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -// getWhitespaceString returns a string that is long enough to overwrite the default -// output from the go testing framework. -func getWhitespaceString() string { - - _, file, line, ok := runtime.Caller(1) - if !ok { - return "" - } - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - - return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) - -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's -// test printing (see inner comment for specifics) -func indentMessageLines(message string, tabs int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - if i != 0 { - outBuf.WriteRune('\n') - } - for ii := 0; ii < tabs; ii++ { - outBuf.WriteRune('\t') - // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter - // by 1 prematurely. - if ii == 0 && i > 0 { - ii++ - } - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - - errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t") - if len(message) > 0 { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n"+ - "\r\tMessages:\t%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2), - message) - } else { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2)) - } - - return false -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) - } - - return true - -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(expected, actual) { - diff := diff(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqualValues(expected, actual) { - return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+ - " != %#v (actual)", expected, actual), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if !isNil(object) { - return true - } - return Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if isNil(object) { - return true - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -var numericZeros = []interface{}{ - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - float32(0), - float64(0), -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - if object == nil { - return true - } else if object == "" { - return true - } else if object == false { - return true - } - - for _, v := range numericZeros { - if object == v { - return true - } - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - case reflect.Map: - fallthrough - case reflect.Slice, reflect.Chan: - { - return (objValue.Len() == 0) - } - case reflect.Ptr: - { - if objValue.IsNil() { - return true - } - switch object.(type) { - case *time.Time: - return object.(*time.Time).IsZero() - default: - return false - } - } - } - return false -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != true { - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != false { - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true - -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - if reflect.TypeOf(list).Kind() == reflect.Map { - mapKeys := listValue.MapKeys() - for i := 0; i < len(mapKeys); i++ { - if ObjectsAreEqual(mapKeys[i].Interface(), element) { - return true, true - } - } - return true, false - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - if math.IsNaN(af) { - return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) - } - - if math.IsNaN(bf) { - return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - if !result { - return result - } - } - - return true -} - -// min(|expected|, |actual|) * epsilon -func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 { - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - // invalid input - return 0 - } - - if af < 0 { - af = -af - } - if bf < 0 { - bf = -bf - } - var delta float64 - if af < bf { - delta = af * epsilon - } else { - delta = bf * epsilon - } - return delta -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - delta := calcEpsilonDelta(expected, actual, epsilon) - - return InDelta(t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - if !result { - return result - } - } - - return true -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if isNil(err) { - return true - } - - return Fail(t, fmt.Sprintf("Received unexpected error %q", err), msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - return NotNil(t, err, "An error is expected but got nil. %s", message) - -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - - message := messageFromMsgAndArgs(msgAndArgs...) - if !NotNil(t, theError, "An error is expected but got nil. %s", message) { - return false - } - s := "An error with value \"%s\" is expected but got \"%s\". %s" - return Equal(t, errString, theError.Error(), - s, errString, theError.Error(), message) -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - var expectedJSONAsInterface, actualJSONAsInterface interface{} - - if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice or array. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { - return "" - } - - spew.Config.SortKeys = true - e := spew.Sdump(expected) - a := spew.Sdump(actual) - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return "\n\nDiff:\n" + diff -} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index c9dccc4d6cd0..000000000000 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d1d615..000000000000 --- a/vendor/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index fe6b664e0764..000000000000 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,284 +0,0 @@ -package assert - -import "time" - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - return Fail(a.t, failureMessage, msgAndArgs...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return IsType(a.t, expectedType, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return Exactly(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - return NotNil(a.t, object, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - return Nil(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a -// slice with len == 0. -// -// assert.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - return Empty(a.t, object, msgAndArgs...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a -// slice with len == 0. -// -// if assert.NotEmpty(obj) { -// assert.Equal("two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - return NotEmpty(a.t, object, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - return Len(a.t, object, length, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// assert.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - return True(a.t, value, msgAndArgs...) -} - -// False asserts that the specified value is false. -// -// assert.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - return False(a.t, value, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool { - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// Contains asserts that the specified string contains the specified substring. -// -// assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) bool { - return Contains(a.t, s, contains, msgAndArgs...) -} - -// NotContains asserts that the specified string does NOT contain the specified substring. -// -// assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) bool { - return NotContains(a.t, s, contains, msgAndArgs...) -} - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - return Condition(a.t, comp, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return Panics(a.t, f, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return NotPanics(a.t, f, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(err) { -// assert.Equal(actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) bool { - return NoError(a.t, theError, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) bool { - return Error(a.t, theError, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - return EqualError(a.t, theError, errString, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return Regexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { - return Zero(a.t, i, msgAndArgs...) -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { - return NotZero(a.t, i, msgAndArgs...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { - return JSONEq(a.t, expected, actual, msgAndArgs...) -} diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index 437a86ce476d..000000000000 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,157 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return -1 - } - handler(w, req) - return w.Code -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusOK && code <= http.StatusPartialContent -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusBadRequest -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) - } - - return !contains -} - -// -// Assertions Wrappers -// - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPSuccess(a.t, handler, method, url, values) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPRedirect(a.t, handler, method, url, values) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPError(a.t, handler, method, url, values) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - return HTTPBodyContains(a.t, handler, method, url, values, str) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - return HTTPBodyNotContains(a.t, handler, method, url, values, str) -} diff --git a/vendor/github.com/stretchr/testify/mock/doc.go b/vendor/github.com/stretchr/testify/mock/doc.go deleted file mode 100644 index dd385074bc44..000000000000 --- a/vendor/github.com/stretchr/testify/mock/doc.go +++ /dev/null @@ -1,43 +0,0 @@ -// Provides a system by which it is possible to mock your objects and verify calls are happening as expected. -// -// Example Usage -// -// The mock package provides an object, Mock, that tracks activity on another object. It is usually -// embedded into a test object as shown below: -// -// type MyTestObject struct { -// // add a Mock object instance -// mock.Mock -// -// // other fields go here as normal -// } -// -// When implementing the methods of an interface, you wire your functions up -// to call the Mock.Called(args...) method, and return the appropriate values. -// -// For example, to mock a method that saves the name and age of a person and returns -// the year of their birth or an error, you might write this: -// -// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { -// args := o.Called(firstname, lastname, age) -// return args.Int(0), args.Error(1) -// } -// -// The Int, Error and Bool methods are examples of strongly typed getters that take the argument -// index position. Given this argument list: -// -// (12, true, "Something") -// -// You could read them out strongly typed like this: -// -// args.Int(0) -// args.Bool(1) -// args.String(2) -// -// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: -// -// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) -// -// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those -// cases you should check for nil first. -package mock diff --git a/vendor/github.com/stretchr/testify/mock/mock.go b/vendor/github.com/stretchr/testify/mock/mock.go deleted file mode 100644 index 111a281b4d3f..000000000000 --- a/vendor/github.com/stretchr/testify/mock/mock.go +++ /dev/null @@ -1,624 +0,0 @@ -package mock - -import ( - "fmt" - "reflect" - "regexp" - "runtime" - "strings" - "sync" - "time" - - "github.com/stretchr/objx" - "github.com/stretchr/testify/assert" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Logf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) -} - -/* - Call -*/ - -// Call represents a method call and is used for setting expectations, -// as well as recording activity. -type Call struct { - Parent *Mock - - // The name of the method that was or will be called. - Method string - - // Holds the arguments of the method. - Arguments Arguments - - // Holds the arguments that should be returned when - // this method is called. - ReturnArguments Arguments - - // The number of times to return the return arguments when setting - // expectations. 0 means to always return the value. - Repeatability int - - // Holds a channel that will be used to block the Return until it either - // recieves a message or is closed. nil means it returns immediately. - WaitFor <-chan time.Time - - // Holds a handler used to manipulate arguments content that are passed by - // reference. It's useful when mocking methods such as unmarshalers or - // decoders. - RunFn func(Arguments) -} - -func newCall(parent *Mock, methodName string, methodArguments ...interface{}) *Call { - return &Call{ - Parent: parent, - Method: methodName, - Arguments: methodArguments, - ReturnArguments: make([]interface{}, 0), - Repeatability: 0, - WaitFor: nil, - RunFn: nil, - } -} - -func (self *Call) lock() { - self.Parent.mutex.Lock() -} - -func (self *Call) unlock() { - self.Parent.mutex.Unlock() -} - -func (self *Call) Return(returnArguments ...interface{}) *Call { - self.lock() - defer self.unlock() - - self.ReturnArguments = returnArguments - - return self -} - -// Once indicates that that the mock should only return the value once. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() -func (self *Call) Once() *Call { - return self.Times(1) -} - -// Twice indicates that that the mock should only return the value twice. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() -func (self *Call) Twice() *Call { - return self.Times(2) -} - -// Times indicates that that the mock should only return the indicated number -// of times. -// -// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) -func (self *Call) Times(i int) *Call { - self.lock() - defer self.unlock() - self.Repeatability = i - return self -} - -// WaitUntil sets the channel that will block the mock's return until its closed -// or a message is received. -// -// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) -func (self *Call) WaitUntil(w <-chan time.Time) *Call { - self.lock() - defer self.unlock() - self.WaitFor = w - return self -} - -// After sets how long to block until the call returns -// -// Mock.On("MyMethod", arg1, arg2).After(time.Second) -func (self *Call) After(d time.Duration) *Call { - return self.WaitUntil(time.After(d)) -} - -// Run sets a handler to be called before returning. It can be used when -// mocking a method such as unmarshalers that takes a pointer to a struct and -// sets properties in such struct -// -// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(function(args Arguments) { -// arg := args.Get(0).(*map[string]interface{}) -// arg["foo"] = "bar" -// }) -func (self *Call) Run(fn func(Arguments)) *Call { - self.lock() - defer self.unlock() - self.RunFn = fn - return self -} - -// On chains a new expectation description onto the mocked interface. This -// allows syntax like. -// -// Mock. -// On("MyMethod", 1).Return(nil). -// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) -func (self *Call) On(methodName string, arguments ...interface{}) *Call { - return self.Parent.On(methodName, arguments...) -} - -// Mock is the workhorse used to track activity on another object. -// For an example of its usage, refer to the "Example Usage" section at the top -// of this document. -type Mock struct { - // Represents the calls that are expected of - // an object. - ExpectedCalls []*Call - - // Holds the calls that were made to this mocked object. - Calls []Call - - // TestData holds any data that might be useful for testing. Testify ignores - // this data completely allowing you to do whatever you like with it. - testData objx.Map - - mutex sync.Mutex -} - -// TestData holds any data that might be useful for testing. Testify ignores -// this data completely allowing you to do whatever you like with it. -func (m *Mock) TestData() objx.Map { - - if m.testData == nil { - m.testData = make(objx.Map) - } - - return m.testData -} - -/* - Setting expectations -*/ - -// On starts a description of an expectation of the specified method -// being called. -// -// Mock.On("MyMethod", arg1, arg2) -func (self *Mock) On(methodName string, arguments ...interface{}) *Call { - for _, arg := range arguments { - if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { - panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) - } - } - - self.mutex.Lock() - defer self.mutex.Unlock() - c := newCall(self, methodName, arguments...) - self.ExpectedCalls = append(self.ExpectedCalls, c) - return c -} - -// /* -// Recording and responding to activity -// */ - -func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { - m.mutex.Lock() - defer m.mutex.Unlock() - for i, call := range m.ExpectedCalls { - if call.Method == method && call.Repeatability > -1 { - - _, diffCount := call.Arguments.Diff(arguments) - if diffCount == 0 { - return i, call - } - - } - } - return -1, nil -} - -func (m *Mock) findClosestCall(method string, arguments ...interface{}) (bool, *Call) { - diffCount := 0 - var closestCall *Call = nil - - for _, call := range m.expectedCalls() { - if call.Method == method { - - _, tempDiffCount := call.Arguments.Diff(arguments) - if tempDiffCount < diffCount || diffCount == 0 { - diffCount = tempDiffCount - closestCall = call - } - - } - } - - if closestCall == nil { - return false, nil - } - - return true, closestCall -} - -func callString(method string, arguments Arguments, includeArgumentValues bool) string { - - var argValsString string = "" - if includeArgumentValues { - var argVals []string - for argIndex, arg := range arguments { - argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) - } - argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) - } - - return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) -} - -// Called tells the mock object that a method has been called, and gets an array -// of arguments to return. Panics if the call is unexpected (i.e. not preceeded by -// appropriate .On .Return() calls) -// If Call.WaitFor is set, blocks until the channel is closed or receives a message. -func (m *Mock) Called(arguments ...interface{}) Arguments { - // get the calling function's name - pc, _, _, ok := runtime.Caller(1) - if !ok { - panic("Couldn't get the caller information") - } - functionPath := runtime.FuncForPC(pc).Name() - //Next four lines are required to use GCCGO function naming conventions. - //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock - //uses inteface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree - //With GCCGO we need to remove interface information starting from pN

. - re := regexp.MustCompile("\\.pN\\d+_") - if re.MatchString(functionPath) { - functionPath = re.Split(functionPath, -1)[0] - } - parts := strings.Split(functionPath, ".") - functionName := parts[len(parts)-1] - - found, call := m.findExpectedCall(functionName, arguments...) - - if found < 0 { - // we have to fail here - because we don't know what to do - // as the return arguments. This is because: - // - // a) this is a totally unexpected call to this method, - // b) the arguments are not what was expected, or - // c) the developer has forgotten to add an accompanying On...Return pair. - - closestFound, closestCall := m.findClosestCall(functionName, arguments...) - - if closestFound { - panic(fmt.Sprintf("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n", callString(functionName, arguments, true), callString(functionName, closestCall.Arguments, true))) - } else { - panic(fmt.Sprintf("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", functionName, functionName, callString(functionName, arguments, true), assert.CallerInfo())) - } - } else { - m.mutex.Lock() - switch { - case call.Repeatability == 1: - call.Repeatability = -1 - - case call.Repeatability > 1: - call.Repeatability -= 1 - } - m.mutex.Unlock() - } - - // add the call - m.mutex.Lock() - m.Calls = append(m.Calls, *newCall(m, functionName, arguments...)) - m.mutex.Unlock() - - // block if specified - if call.WaitFor != nil { - <-call.WaitFor - } - - if call.RunFn != nil { - call.RunFn(arguments) - } - - return call.ReturnArguments -} - -/* - Assertions -*/ - -// AssertExpectationsForObjects asserts that everything specified with On and Return -// of the specified objects was in fact called as expected. -// -// Calls may have occurred in any order. -func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { - var success bool = true - for _, obj := range testObjects { - mockObj := obj.(Mock) - success = success && mockObj.AssertExpectations(t) - } - return success -} - -// AssertExpectations asserts that everything specified with On and Return was -// in fact called as expected. Calls may have occurred in any order. -func (m *Mock) AssertExpectations(t TestingT) bool { - var somethingMissing bool = false - var failedExpectations int = 0 - - // iterate through each expectation - expectedCalls := m.expectedCalls() - for _, expectedCall := range expectedCalls { - if !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) { - somethingMissing = true - failedExpectations++ - t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) - } else { - m.mutex.Lock() - if expectedCall.Repeatability > 0 { - somethingMissing = true - failedExpectations++ - } else { - t.Logf("\u2705\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) - } - m.mutex.Unlock() - } - } - - if somethingMissing { - t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) - } - - return !somethingMissing -} - -// AssertNumberOfCalls asserts that the method was called expectedCalls times. -func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { - var actualCalls int = 0 - for _, call := range m.calls() { - if call.Method == methodName { - actualCalls++ - } - } - return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) -} - -// AssertCalled asserts that the method was called. -func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if !assert.True(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method should have been called with %d argument(s), but was not.", methodName, len(arguments))) { - t.Logf("%v", m.expectedCalls()) - return false - } - return true -} - -// AssertNotCalled asserts that the method was not called. -func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { - if !assert.False(t, m.methodWasCalled(methodName, arguments), fmt.Sprintf("The \"%s\" method was called with %d argument(s), but should NOT have been.", methodName, len(arguments))) { - t.Logf("%v", m.expectedCalls()) - return false - } - return true -} - -func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { - for _, call := range m.calls() { - if call.Method == methodName { - - _, differences := Arguments(expected).Diff(call.Arguments) - - if differences == 0 { - // found the expected call - return true - } - - } - } - // we didn't find the expected call - return false -} - -func (m *Mock) expectedCalls() []*Call { - m.mutex.Lock() - defer m.mutex.Unlock() - return append([]*Call{}, m.ExpectedCalls...) -} - -func (m *Mock) calls() []Call { - m.mutex.Lock() - defer m.mutex.Unlock() - return append([]Call{}, m.Calls...) -} - -/* - Arguments -*/ - -// Arguments holds an array of method arguments or return values. -type Arguments []interface{} - -const ( - // The "any" argument. Used in Diff and Assert when - // the argument being tested shouldn't be taken into consideration. - Anything string = "mock.Anything" -) - -// AnythingOfTypeArgument is a string that contains the type of an argument -// for use when type checking. Used in Diff and Assert. -type AnythingOfTypeArgument string - -// AnythingOfType returns an AnythingOfTypeArgument object containing the -// name of the type to check for. Used in Diff and Assert. -// -// For example: -// Assert(t, AnythingOfType("string"), AnythingOfType("int")) -func AnythingOfType(t string) AnythingOfTypeArgument { - return AnythingOfTypeArgument(t) -} - -// Get Returns the argument at the specified index. -func (args Arguments) Get(index int) interface{} { - if index+1 > len(args) { - panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) - } - return args[index] -} - -// Is gets whether the objects match the arguments specified. -func (args Arguments) Is(objects ...interface{}) bool { - for i, obj := range args { - if obj != objects[i] { - return false - } - } - return true -} - -// Diff gets a string describing the differences between the arguments -// and the specified objects. -// -// Returns the diff string and number of differences found. -func (args Arguments) Diff(objects []interface{}) (string, int) { - - var output string = "\n" - var differences int - - var maxArgCount int = len(args) - if len(objects) > maxArgCount { - maxArgCount = len(objects) - } - - for i := 0; i < maxArgCount; i++ { - var actual, expected interface{} - - if len(objects) <= i { - actual = "(Missing)" - } else { - actual = objects[i] - } - - if len(args) <= i { - expected = "(Missing)" - } else { - expected = args[i] - } - - if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { - - // type checking - if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: \u274C type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) - } - - } else { - - // normal checking - - if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { - // match - output = fmt.Sprintf("%s\t%d: \u2705 %s == %s\n", output, i, actual, expected) - } else { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: \u274C %s != %s\n", output, i, actual, expected) - } - } - - } - - if differences == 0 { - return "No differences.", differences - } - - return output, differences - -} - -// Assert compares the arguments with the specified objects and fails if -// they do not exactly match. -func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { - - // get the differences - diff, diffCount := args.Diff(objects) - - if diffCount == 0 { - return true - } - - // there are differences... report them... - t.Logf(diff) - t.Errorf("%sArguments do not match.", assert.CallerInfo()) - - return false - -} - -// String gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -// -// If no index is provided, String() returns a complete string representation -// of the arguments. -func (args Arguments) String(indexOrNil ...int) string { - - if len(indexOrNil) == 0 { - // normal String() method - return a string representation of the args - var argsStr []string - for _, arg := range args { - argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) - } - return strings.Join(argsStr, ",") - } else if len(indexOrNil) == 1 { - // Index has been specified - get the argument at that index - var index int = indexOrNil[0] - var s string - var ok bool - if s, ok = args.Get(index).(string); !ok { - panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) - } - return s - } - - panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) - -} - -// Int gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Int(index int) int { - var s int - var ok bool - if s, ok = args.Get(index).(int); !ok { - panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Error gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Error(index int) error { - obj := args.Get(index) - var s error - var ok bool - if obj == nil { - return nil - } - if s, ok = obj.(error); !ok { - panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} - -// Bool gets the argument at the specified index. Panics if there is no argument, or -// if the argument is of the wrong type. -func (args Arguments) Bool(index int) bool { - var s bool - var ok bool - if s, ok = args.Get(index).(bool); !ok { - panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) - } - return s -} diff --git a/vendor/golang.org/x/crypto/pkcs12/bmp-string.go b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go new file mode 100644 index 000000000000..284d2a68f1ee --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go @@ -0,0 +1,50 @@ +// Copyright 2015 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 pkcs12 + +import ( + "errors" + "unicode/utf16" +) + +// bmpString returns s encoded in UCS-2 with a zero terminator. +func bmpString(s string) ([]byte, error) { + // References: + // https://tools.ietf.org/html/rfc7292#appendix-B.1 + // http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane + // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes + // EncodeRune returns 0xfffd if the rune does not need special encoding + // - the above RFC provides the info that BMPStrings are NULL terminated. + + ret := make([]byte, 0, 2*len(s)+2) + + for _, r := range s { + if t, _ := utf16.EncodeRune(r); t != 0xfffd { + return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2") + } + ret = append(ret, byte(r/256), byte(r%256)) + } + + return append(ret, 0, 0), nil +} + +func decodeBMPString(bmpString []byte) (string, error) { + if len(bmpString)%2 != 0 { + return "", errors.New("pkcs12: odd-length BMP string") + } + + // strip terminator if present + if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { + bmpString = bmpString[:l-2] + } + + s := make([]uint16, 0, len(bmpString)/2) + for len(bmpString) > 0 { + s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) + bmpString = bmpString[2:] + } + + return string(utf16.Decode(s)), nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/crypto.go b/vendor/golang.org/x/crypto/pkcs12/crypto.go new file mode 100644 index 000000000000..4bd4470ec041 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/crypto.go @@ -0,0 +1,131 @@ +// Copyright 2015 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 pkcs12 + +import ( + "bytes" + "crypto/cipher" + "crypto/des" + "crypto/x509/pkix" + "encoding/asn1" + "errors" + + "golang.org/x/crypto/pkcs12/internal/rc2" +) + +var ( + oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) + oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6}) +) + +// pbeCipher is an abstraction of a PKCS#12 cipher. +type pbeCipher interface { + // create returns a cipher.Block given a key. + create(key []byte) (cipher.Block, error) + // deriveKey returns a key derived from the given password and salt. + deriveKey(salt, password []byte, iterations int) []byte + // deriveKey returns an IV derived from the given password and salt. + deriveIV(salt, password []byte, iterations int) []byte +} + +type shaWithTripleDESCBC struct{} + +func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) { + return des.NewTripleDESCipher(key) +} + +func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24) +} + +func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) +} + +type shaWith40BitRC2CBC struct{} + +func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) { + return rc2.New(key, len(key)*8) +} + +func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5) +} + +func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) +} + +type pbeParams struct { + Salt []byte + Iterations int +} + +func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) { + var cipherType pbeCipher + + switch { + case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC): + cipherType = shaWithTripleDESCBC{} + case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC): + cipherType = shaWith40BitRC2CBC{} + default: + return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported") + } + + var params pbeParams + if err := unmarshal(algorithm.Parameters.FullBytes, ¶ms); err != nil { + return nil, 0, err + } + + key := cipherType.deriveKey(params.Salt, password, params.Iterations) + iv := cipherType.deriveIV(params.Salt, password, params.Iterations) + + block, err := cipherType.create(key) + if err != nil { + return nil, 0, err + } + + return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil +} + +func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) { + cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password) + if err != nil { + return nil, err + } + + encrypted := info.Data() + if len(encrypted) == 0 { + return nil, errors.New("pkcs12: empty encrypted data") + } + if len(encrypted)%blockSize != 0 { + return nil, errors.New("pkcs12: input is not a multiple of the block size") + } + decrypted = make([]byte, len(encrypted)) + cbc.CryptBlocks(decrypted, encrypted) + + psLen := int(decrypted[len(decrypted)-1]) + if psLen == 0 || psLen > blockSize { + return nil, ErrDecryption + } + + if len(decrypted) < psLen { + return nil, ErrDecryption + } + ps := decrypted[len(decrypted)-psLen:] + decrypted = decrypted[:len(decrypted)-psLen] + if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { + return nil, ErrDecryption + } + + return +} + +// decryptable abstracts a object that contains ciphertext. +type decryptable interface { + Algorithm() pkix.AlgorithmIdentifier + Data() []byte +} diff --git a/vendor/golang.org/x/crypto/pkcs12/errors.go b/vendor/golang.org/x/crypto/pkcs12/errors.go new file mode 100644 index 000000000000..7377ce6fb2b8 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/errors.go @@ -0,0 +1,23 @@ +// Copyright 2015 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 pkcs12 + +import "errors" + +var ( + // ErrDecryption represents a failure to decrypt the input. + ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") + + // ErrIncorrectPassword is returned when an incorrect password is detected. + // Usually, P12/PFX data is signed to be able to verify the password. + ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") +) + +// NotImplementedError indicates that the input is not currently supported. +type NotImplementedError string + +func (e NotImplementedError) Error() string { + return "pkcs12: " + string(e) +} diff --git a/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go new file mode 100644 index 000000000000..8c7090258c5a --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go @@ -0,0 +1,274 @@ +// Copyright 2015 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 rc2 implements the RC2 cipher +/* +https://www.ietf.org/rfc/rfc2268.txt +http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf + +This code is licensed under the MIT license. +*/ +package rc2 + +import ( + "crypto/cipher" + "encoding/binary" +) + +// The rc2 block size in bytes +const BlockSize = 8 + +type rc2Cipher struct { + k [64]uint16 +} + +// New returns a new rc2 cipher with the given key and effective key length t1 +func New(key []byte, t1 int) (cipher.Block, error) { + // TODO(dgryski): error checking for key length + return &rc2Cipher{ + k: expandKey(key, t1), + }, nil +} + +func (*rc2Cipher) BlockSize() int { return BlockSize } + +var piTable = [256]byte{ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, +} + +func expandKey(key []byte, t1 int) [64]uint16 { + + l := make([]byte, 128) + copy(l, key) + + var t = len(key) + var t8 = (t1 + 7) / 8 + var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) + + for i := len(key); i < 128; i++ { + l[i] = piTable[l[i-1]+l[uint8(i-t)]] + } + + l[128-t8] = piTable[l[128-t8]&tm] + + for i := 127 - t8; i >= 0; i-- { + l[i] = piTable[l[i+1]^l[i+t8]] + } + + var k [64]uint16 + + for i := range k { + k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 + } + + return k +} + +func rotl16(x uint16, b uint) uint16 { + return (x >> (16 - b)) | (x << b) +} + +func (c *rc2Cipher) Encrypt(dst, src []byte) { + + r0 := binary.LittleEndian.Uint16(src[0:]) + r1 := binary.LittleEndian.Uint16(src[2:]) + r2 := binary.LittleEndian.Uint16(src[4:]) + r3 := binary.LittleEndian.Uint16(src[6:]) + + var j int + + for j <= 16 { + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + + } + + r0 = r0 + c.k[r3&63] + r1 = r1 + c.k[r0&63] + r2 = r2 + c.k[r1&63] + r3 = r3 + c.k[r2&63] + + for j <= 40 { + + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + + } + + r0 = r0 + c.k[r3&63] + r1 = r1 + c.k[r0&63] + r2 = r2 + c.k[r1&63] + r3 = r3 + c.k[r2&63] + + for j <= 60 { + + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + } + + binary.LittleEndian.PutUint16(dst[0:], r0) + binary.LittleEndian.PutUint16(dst[2:], r1) + binary.LittleEndian.PutUint16(dst[4:], r2) + binary.LittleEndian.PutUint16(dst[6:], r3) +} + +func (c *rc2Cipher) Decrypt(dst, src []byte) { + + r0 := binary.LittleEndian.Uint16(src[0:]) + r1 := binary.LittleEndian.Uint16(src[2:]) + r2 := binary.LittleEndian.Uint16(src[4:]) + r3 := binary.LittleEndian.Uint16(src[6:]) + + j := 63 + + for j >= 44 { + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + } + + r3 = r3 - c.k[r2&63] + r2 = r2 - c.k[r1&63] + r1 = r1 - c.k[r0&63] + r0 = r0 - c.k[r3&63] + + for j >= 20 { + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + + } + + r3 = r3 - c.k[r2&63] + r2 = r2 - c.k[r1&63] + r1 = r1 - c.k[r0&63] + r0 = r0 - c.k[r3&63] + + for j >= 0 { + + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + + } + + binary.LittleEndian.PutUint16(dst[0:], r0) + binary.LittleEndian.PutUint16(dst[2:], r1) + binary.LittleEndian.PutUint16(dst[4:], r2) + binary.LittleEndian.PutUint16(dst[6:], r3) +} diff --git a/vendor/golang.org/x/crypto/pkcs12/mac.go b/vendor/golang.org/x/crypto/pkcs12/mac.go new file mode 100644 index 000000000000..5f38aa7de83c --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/mac.go @@ -0,0 +1,45 @@ +// Copyright 2015 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 pkcs12 + +import ( + "crypto/hmac" + "crypto/sha1" + "crypto/x509/pkix" + "encoding/asn1" +) + +type macData struct { + Mac digestInfo + MacSalt []byte + Iterations int `asn1:"optional,default:1"` +} + +// from PKCS#7: +type digestInfo struct { + Algorithm pkix.AlgorithmIdentifier + Digest []byte +} + +var ( + oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) +) + +func verifyMac(macData *macData, message, password []byte) error { + if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) { + return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String()) + } + + key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20) + + mac := hmac.New(sha1.New, key) + mac.Write(message) + expectedMAC := mac.Sum(nil) + + if !hmac.Equal(macData.Mac.Digest, expectedMAC) { + return ErrIncorrectPassword + } + return nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/pbkdf.go b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go new file mode 100644 index 000000000000..5c419d41e32c --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go @@ -0,0 +1,170 @@ +// Copyright 2015 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 pkcs12 + +import ( + "bytes" + "crypto/sha1" + "math/big" +) + +var ( + one = big.NewInt(1) +) + +// sha1Sum returns the SHA-1 hash of in. +func sha1Sum(in []byte) []byte { + sum := sha1.Sum(in) + return sum[:] +} + +// fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of +// repeats of pattern. +func fillWithRepeats(pattern []byte, v int) []byte { + if len(pattern) == 0 { + return nil + } + outputLen := v * ((len(pattern) + v - 1) / v) + return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen] +} + +func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) { + // implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments + + // Let H be a hash function built around a compression function f: + + // Z_2^u x Z_2^v -> Z_2^u + + // (that is, H has a chaining variable and output of length u bits, and + // the message input to the compression function of H is v bits). The + // values for u and v are as follows: + + // HASH FUNCTION VALUE u VALUE v + // MD2, MD5 128 512 + // SHA-1 160 512 + // SHA-224 224 512 + // SHA-256 256 512 + // SHA-384 384 1024 + // SHA-512 512 1024 + // SHA-512/224 224 1024 + // SHA-512/256 256 1024 + + // Furthermore, let r be the iteration count. + + // We assume here that u and v are both multiples of 8, as are the + // lengths of the password and salt strings (which we denote by p and s, + // respectively) and the number n of pseudorandom bits required. In + // addition, u and v are of course non-zero. + + // For information on security considerations for MD5 [19], see [25] and + // [1], and on those for MD2, see [18]. + + // The following procedure can be used to produce pseudorandom bits for + // a particular "purpose" that is identified by a byte called "ID". + // This standard specifies 3 different values for the ID byte: + + // 1. If ID=1, then the pseudorandom bits being produced are to be used + // as key material for performing encryption or decryption. + + // 2. If ID=2, then the pseudorandom bits being produced are to be used + // as an IV (Initial Value) for encryption or decryption. + + // 3. If ID=3, then the pseudorandom bits being produced are to be used + // as an integrity key for MACing. + + // 1. Construct a string, D (the "diversifier"), by concatenating v/8 + // copies of ID. + var D []byte + for i := 0; i < v; i++ { + D = append(D, ID) + } + + // 2. Concatenate copies of the salt together to create a string S of + // length v(ceiling(s/v)) bits (the final copy of the salt may be + // truncated to create S). Note that if the salt is the empty + // string, then so is S. + + S := fillWithRepeats(salt, v) + + // 3. Concatenate copies of the password together to create a string P + // of length v(ceiling(p/v)) bits (the final copy of the password + // may be truncated to create P). Note that if the password is the + // empty string, then so is P. + + P := fillWithRepeats(password, v) + + // 4. Set I=S||P to be the concatenation of S and P. + I := append(S, P...) + + // 5. Set c=ceiling(n/u). + c := (size + u - 1) / u + + // 6. For i=1, 2, ..., c, do the following: + A := make([]byte, c*20) + var IjBuf []byte + for i := 0; i < c; i++ { + // A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1, + // H(H(H(... H(D||I)))) + Ai := hash(append(D, I...)) + for j := 1; j < r; j++ { + Ai = hash(Ai) + } + copy(A[i*20:], Ai[:]) + + if i < c-1 { // skip on last iteration + // B. Concatenate copies of Ai to create a string B of length v + // bits (the final copy of Ai may be truncated to create B). + var B []byte + for len(B) < v { + B = append(B, Ai[:]...) + } + B = B[:v] + + // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit + // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by + // setting I_j=(I_j+B+1) mod 2^v for each j. + { + Bbi := new(big.Int).SetBytes(B) + Ij := new(big.Int) + + for j := 0; j < len(I)/v; j++ { + Ij.SetBytes(I[j*v : (j+1)*v]) + Ij.Add(Ij, Bbi) + Ij.Add(Ij, one) + Ijb := Ij.Bytes() + // We expect Ijb to be exactly v bytes, + // if it is longer or shorter we must + // adjust it accordingly. + if len(Ijb) > v { + Ijb = Ijb[len(Ijb)-v:] + } + if len(Ijb) < v { + if IjBuf == nil { + IjBuf = make([]byte, v) + } + bytesShort := v - len(Ijb) + for i := 0; i < bytesShort; i++ { + IjBuf[i] = 0 + } + copy(IjBuf[bytesShort:], Ijb) + Ijb = IjBuf + } + copy(I[j*v:(j+1)*v], Ijb) + } + } + } + } + // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom + // bit string, A. + + // 8. Use the first n bits of A as the output of this entire process. + return A[:size] + + // If the above process is being used to generate a DES key, the process + // should be used to create 64 random bits, and the key's parity bits + // should be set after the 64 bits have been produced. Similar concerns + // hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any + // similar keys with parity bits "built into them". +} diff --git a/vendor/golang.org/x/crypto/pkcs12/pkcs12.go b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go new file mode 100644 index 000000000000..ad6341e60fa4 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go @@ -0,0 +1,342 @@ +// Copyright 2015 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 pkcs12 implements some of PKCS#12. +// +// This implementation is distilled from https://tools.ietf.org/html/rfc7292 +// and referenced documents. It is intended for decoding P12/PFX-stored +// certificates and keys for use with the crypto/tls package. +package pkcs12 + +import ( + "crypto/ecdsa" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/hex" + "encoding/pem" + "errors" +) + +var ( + oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1}) + oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6}) + + oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20}) + oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21}) + oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1}) +) + +type pfxPdu struct { + Version int + AuthSafe contentInfo + MacData macData `asn1:"optional"` +} + +type contentInfo struct { + ContentType asn1.ObjectIdentifier + Content asn1.RawValue `asn1:"tag:0,explicit,optional"` +} + +type encryptedData struct { + Version int + EncryptedContentInfo encryptedContentInfo +} + +type encryptedContentInfo struct { + ContentType asn1.ObjectIdentifier + ContentEncryptionAlgorithm pkix.AlgorithmIdentifier + EncryptedContent []byte `asn1:"tag:0,optional"` +} + +func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier { + return i.ContentEncryptionAlgorithm +} + +func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent } + +type safeBag struct { + Id asn1.ObjectIdentifier + Value asn1.RawValue `asn1:"tag:0,explicit"` + Attributes []pkcs12Attribute `asn1:"set,optional"` +} + +type pkcs12Attribute struct { + Id asn1.ObjectIdentifier + Value asn1.RawValue `asn1:"set"` +} + +type encryptedPrivateKeyInfo struct { + AlgorithmIdentifier pkix.AlgorithmIdentifier + EncryptedData []byte +} + +func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier { + return i.AlgorithmIdentifier +} + +func (i encryptedPrivateKeyInfo) Data() []byte { + return i.EncryptedData +} + +// PEM block types +const ( + certificateType = "CERTIFICATE" + privateKeyType = "PRIVATE KEY" +) + +// unmarshal calls asn1.Unmarshal, but also returns an error if there is any +// trailing data after unmarshaling. +func unmarshal(in []byte, out interface{}) error { + trailing, err := asn1.Unmarshal(in, out) + if err != nil { + return err + } + if len(trailing) != 0 { + return errors.New("pkcs12: trailing data found") + } + return nil +} + +// ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks. +func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { + encodedPassword, err := bmpString(password) + if err != nil { + return nil, ErrIncorrectPassword + } + + bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) + + blocks := make([]*pem.Block, 0, len(bags)) + for _, bag := range bags { + block, err := convertBag(&bag, encodedPassword) + if err != nil { + return nil, err + } + blocks = append(blocks, block) + } + + return blocks, nil +} + +func convertBag(bag *safeBag, password []byte) (*pem.Block, error) { + block := &pem.Block{ + Headers: make(map[string]string), + } + + for _, attribute := range bag.Attributes { + k, v, err := convertAttribute(&attribute) + if err != nil { + return nil, err + } + block.Headers[k] = v + } + + switch { + case bag.Id.Equal(oidCertBag): + block.Type = certificateType + certsData, err := decodeCertBag(bag.Value.Bytes) + if err != nil { + return nil, err + } + block.Bytes = certsData + case bag.Id.Equal(oidPKCS8ShroundedKeyBag): + block.Type = privateKeyType + + key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password) + if err != nil { + return nil, err + } + + switch key := key.(type) { + case *rsa.PrivateKey: + block.Bytes = x509.MarshalPKCS1PrivateKey(key) + case *ecdsa.PrivateKey: + block.Bytes, err = x509.MarshalECPrivateKey(key) + if err != nil { + return nil, err + } + default: + return nil, errors.New("found unknown private key type in PKCS#8 wrapping") + } + default: + return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String()) + } + return block, nil +} + +func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) { + isString := false + + switch { + case attribute.Id.Equal(oidFriendlyName): + key = "friendlyName" + isString = true + case attribute.Id.Equal(oidLocalKeyID): + key = "localKeyId" + case attribute.Id.Equal(oidMicrosoftCSPName): + // This key is chosen to match OpenSSL. + key = "Microsoft CSP Name" + isString = true + default: + return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String()) + } + + if isString { + if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil { + return "", "", err + } + if value, err = decodeBMPString(attribute.Value.Bytes); err != nil { + return "", "", err + } + } else { + var id []byte + if err := unmarshal(attribute.Value.Bytes, &id); err != nil { + return "", "", err + } + value = hex.EncodeToString(id) + } + + return key, value, nil +} + +// Decode extracts a certificate and private key from pfxData. This function +// assumes that there is only one certificate and only one private key in the +// pfxData. +func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) { + encodedPassword, err := bmpString(password) + if err != nil { + return nil, nil, err + } + + bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) + if err != nil { + return nil, nil, err + } + + if len(bags) != 2 { + err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU") + return + } + + for _, bag := range bags { + switch { + case bag.Id.Equal(oidCertBag): + if certificate != nil { + err = errors.New("pkcs12: expected exactly one certificate bag") + } + + certsData, err := decodeCertBag(bag.Value.Bytes) + if err != nil { + return nil, nil, err + } + certs, err := x509.ParseCertificates(certsData) + if err != nil { + return nil, nil, err + } + if len(certs) != 1 { + err = errors.New("pkcs12: expected exactly one certificate in the certBag") + return nil, nil, err + } + certificate = certs[0] + + case bag.Id.Equal(oidPKCS8ShroundedKeyBag): + if privateKey != nil { + err = errors.New("pkcs12: expected exactly one key bag") + } + + if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil { + return nil, nil, err + } + } + } + + if certificate == nil { + return nil, nil, errors.New("pkcs12: certificate missing") + } + if privateKey == nil { + return nil, nil, errors.New("pkcs12: private key missing") + } + + return +} + +func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) { + pfx := new(pfxPdu) + if err := unmarshal(p12Data, pfx); err != nil { + return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error()) + } + + if pfx.Version != 3 { + return nil, nil, NotImplementedError("can only decode v3 PFX PDU's") + } + + if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) { + return nil, nil, NotImplementedError("only password-protected PFX is implemented") + } + + // unmarshal the explicit bytes in the content for type 'data' + if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil { + return nil, nil, err + } + + if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 { + return nil, nil, errors.New("pkcs12: no MAC in data") + } + + if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil { + if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 { + // some implementations use an empty byte array + // for the empty string password try one more + // time with empty-empty password + password = nil + err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password) + } + if err != nil { + return nil, nil, err + } + } + + var authenticatedSafe []contentInfo + if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil { + return nil, nil, err + } + + if len(authenticatedSafe) != 2 { + return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe") + } + + for _, ci := range authenticatedSafe { + var data []byte + + switch { + case ci.ContentType.Equal(oidDataContentType): + if err := unmarshal(ci.Content.Bytes, &data); err != nil { + return nil, nil, err + } + case ci.ContentType.Equal(oidEncryptedDataContentType): + var encryptedData encryptedData + if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil { + return nil, nil, err + } + if encryptedData.Version != 0 { + return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported") + } + if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil { + return nil, nil, err + } + default: + return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe") + } + + var safeContents []safeBag + if err := unmarshal(data, &safeContents); err != nil { + return nil, nil, err + } + bags = append(bags, safeContents...) + } + + return bags, password, nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/safebags.go b/vendor/golang.org/x/crypto/pkcs12/safebags.go new file mode 100644 index 000000000000..def1f7b98d7d --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/safebags.go @@ -0,0 +1,57 @@ +// Copyright 2015 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 pkcs12 + +import ( + "crypto/x509" + "encoding/asn1" + "errors" +) + +var ( + // see https://tools.ietf.org/html/rfc7292#appendix-D + oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) + oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) + oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) +) + +type certBag struct { + Id asn1.ObjectIdentifier + Data []byte `asn1:"tag:0,explicit"` +} + +func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { + pkinfo := new(encryptedPrivateKeyInfo) + if err = unmarshal(asn1Data, pkinfo); err != nil { + return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) + } + + pkData, err := pbDecrypt(pkinfo, password) + if err != nil { + return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) + } + + ret := new(asn1.RawValue) + if err = unmarshal(pkData, ret); err != nil { + return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) + } + + if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { + return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) + } + + return privateKey, nil +} + +func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { + bag := new(certBag) + if err := unmarshal(asn1Data, bag); err != nil { + return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) + } + if !bag.Id.Equal(oidCertTypeX509Certificate) { + return nil, NotImplementedError("only X509 certificates are supported") + } + return bag.Data, nil +} diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index 9962ff0f3d26..385770036a7c 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -85,46 +85,73 @@ func marshalStringList(namelist []string) []byte { return to } +type optionsTuple struct { + Key string + Value []byte +} + +type optionsTupleValue struct { + Value string +} + +// serialize a map of critical options or extensions +// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, +// we need two length prefixes for a non-empty string value func marshalTuples(tups map[string]string) []byte { keys := make([]string, 0, len(tups)) - for k := range tups { - keys = append(keys, k) + for key := range tups { + keys = append(keys, key) } sort.Strings(keys) - var r []byte - for _, k := range keys { - s := struct{ K, V string }{k, tups[k]} - r = append(r, Marshal(&s)...) + var ret []byte + for _, key := range keys { + s := optionsTuple{Key: key} + if value := tups[key]; len(value) > 0 { + s.Value = Marshal(&optionsTupleValue{value}) + } + ret = append(ret, Marshal(&s)...) } - return r + return ret } +// issue #10569 - per [PROTOCOL.certkeys] and SSH implementation, +// we need two length prefixes for a non-empty option value func parseTuples(in []byte) (map[string]string, error) { tups := map[string]string{} var lastKey string var haveLastKey bool for len(in) > 0 { - nameBytes, rest, ok := parseString(in) - if !ok { - return nil, errShortRead - } - data, rest, ok := parseString(rest) - if !ok { + var key, val, extra []byte + var ok bool + + if key, in, ok = parseString(in); !ok { return nil, errShortRead } - name := string(nameBytes) - + keyStr := string(key) // according to [PROTOCOL.certkeys], the names must be in // lexical order. - if haveLastKey && name <= lastKey { + if haveLastKey && keyStr <= lastKey { return nil, fmt.Errorf("ssh: certificate options are not in lexical order") } - lastKey, haveLastKey = name, true - - tups[name] = string(data) - in = rest + lastKey, haveLastKey = keyStr, true + // the next field is a data field, which if non-empty has a string embedded + if val, in, ok = parseString(in); !ok { + return nil, errShortRead + } + if len(val) > 0 { + val, extra, ok = parseString(val) + if !ok { + return nil, errShortRead + } + if len(extra) > 0 { + return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value") + } + tups[keyStr] = string(val) + } else { + tups[keyStr] = "" + } } return tups, nil } @@ -341,7 +368,7 @@ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) { return fmt.Errorf("ssh: cert is not yet valid") } - if before := int64(cert.ValidBefore); cert.ValidBefore != CertTimeInfinity && (unixNow >= before || before < 0) { + if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) { return fmt.Errorf("ssh: cert has expired") } if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil { diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go index b173183851d5..2732963f39e1 100644 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ b/vendor/golang.org/x/crypto/ssh/cipher.go @@ -14,6 +14,7 @@ import ( "fmt" "hash" "io" + "io/ioutil" ) const ( @@ -114,9 +115,12 @@ var cipherModes = map[string]*streamCipherMode{ // should invest a cleaner way to do this. gcmCipherID: {16, 12, 0, nil}, - // insecure cipher, see http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf - // uncomment below to enable it. - // aes128cbcID: {16, aes.BlockSize, 0, nil}, + // CBC mode is insecure and so is not included in the default config. + // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely + // needed, it's possible to specify a custom Config to enable it. + // You should expect that an active attacker can recover plaintext if + // you do. + aes128cbcID: {16, aes.BlockSize, 0, nil}, } // prefixLen is the length of the packet prefix that contains the packet length @@ -350,6 +354,7 @@ func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1 type cbcCipher struct { mac hash.Hash + macSize uint32 decrypter cipher.BlockMode encrypter cipher.BlockMode @@ -357,6 +362,10 @@ type cbcCipher struct { seqNumBytes [4]byte packetData []byte macResult []byte + + // Amount of data we should still read to hide which + // verification error triggered. + oracleCamouflage uint32 } func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { @@ -364,12 +373,18 @@ func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCi if err != nil { return nil, err } - return &cbcCipher{ + + cbc := &cbcCipher{ mac: macModes[algs.MAC].new(macKey), decrypter: cipher.NewCBCDecrypter(c, iv), encrypter: cipher.NewCBCEncrypter(c, iv), packetData: make([]byte, 1024), - }, nil + } + if cbc.mac != nil { + cbc.macSize = uint32(cbc.mac.Size()) + } + + return cbc, nil } func maxUInt32(a, b int) uint32 { @@ -385,42 +400,58 @@ const ( cbcMinPaddingSize = 4 ) +// cbcError represents a verification error that may leak information. +type cbcError string + +func (e cbcError) Error() string { return string(e) } + func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { + p, err := c.readPacketLeaky(seqNum, r) + if err != nil { + if _, ok := err.(cbcError); ok { + // Verification error: read a fixed amount of + // data, to make distinguishing between + // failing MAC and failing length check more + // difficult. + io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage)) + } + } + return p, err +} + +func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) { blockSize := c.decrypter.BlockSize() // Read the header, which will include some of the subsequent data in the // case of block ciphers - this is copied back to the payload later. // How many bytes of payload/padding will be read with this first read. - firstBlockLength := (prefixLen + blockSize - 1) / blockSize * blockSize + firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize) firstBlock := c.packetData[:firstBlockLength] if _, err := io.ReadFull(r, firstBlock); err != nil { return nil, err } + c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength + c.decrypter.CryptBlocks(firstBlock, firstBlock) length := binary.BigEndian.Uint32(firstBlock[:4]) if length > maxPacket { - return nil, errors.New("ssh: packet too large") + return nil, cbcError("ssh: packet too large") } if length+4 < maxUInt32(cbcMinPacketSize, blockSize) { // The minimum size of a packet is 16 (or the cipher block size, whichever // is larger) bytes. - return nil, errors.New("ssh: packet too small") + return nil, cbcError("ssh: packet too small") } // The length of the packet (including the length field but not the MAC) must // be a multiple of the block size or 8, whichever is larger. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 { - return nil, errors.New("ssh: invalid packet length multiple") + return nil, cbcError("ssh: invalid packet length multiple") } paddingLength := uint32(firstBlock[4]) if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 { - return nil, errors.New("ssh: invalid packet length") - } - - var macSize uint32 - if c.mac != nil { - macSize = uint32(c.mac.Size()) + return nil, cbcError("ssh: invalid packet length") } // Positions within the c.packetData buffer: @@ -428,7 +459,7 @@ func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { paddingStart := macStart - paddingLength // Entire packet size, starting before length, ending at end of mac. - entirePacketSize := macStart + macSize + entirePacketSize := macStart + c.macSize // Ensure c.packetData is large enough for the entire packet data. if uint32(cap(c.packetData)) < entirePacketSize { @@ -440,8 +471,10 @@ func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { c.packetData = c.packetData[:entirePacketSize] } - if _, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { + if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { return nil, err + } else { + c.oracleCamouflage -= uint32(n) } remainingCrypted := c.packetData[firstBlockLength:macStart] @@ -455,7 +488,7 @@ func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { c.mac.Write(c.packetData[:macStart]) c.macResult = c.mac.Sum(c.macResult[:0]) if subtle.ConstantTimeCompare(c.macResult, mac) != 1 { - return nil, errors.New("ssh: MAC failure") + return nil, cbcError("ssh: MAC failure") } } @@ -474,13 +507,9 @@ func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, pack length := encLength - 4 paddingLength := int(length) - (1 + len(packet)) - var macSize uint32 - if c.mac != nil { - macSize = uint32(c.mac.Size()) - } // Overall buffer contains: header, payload, padding, mac. // Space for the MAC is reserved in the capacity but not the slice length. - bufferSize := encLength + macSize + bufferSize := encLength + c.macSize if uint32(cap(c.packetData)) < bufferSize { c.packetData = make([]byte, encLength, bufferSize) } else { diff --git a/vendor/golang.org/x/crypto/ssh/client.go b/vendor/golang.org/x/crypto/ssh/client.go index 72bd27f1ca79..0b9fbe5002af 100644 --- a/vendor/golang.org/x/crypto/ssh/client.go +++ b/vendor/golang.org/x/crypto/ssh/client.go @@ -203,4 +203,11 @@ type ClientConfig struct { // ClientVersion contains the version identification string that will // be used for the connection. If empty, a reasonable default is used. ClientVersion string + + // HostKeyAlgorithms lists the key types that the client will + // accept from the server as host key, in order of + // preference. If empty, a reasonable default is used. Any + // string returned from PublicKey.Type method may be used, or + // any of the CertAlgoXxxx and KeyAlgoXxxx constants. + HostKeyAlgorithms []string } diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index b03a3dfd8e31..9fc739e1d01b 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -33,6 +33,7 @@ var supportedCiphers = []string{ // supportedKexAlgos specifies the supported key-exchange algorithms in // preference order. var supportedKexAlgos = []string{ + kexAlgoCurve25519SHA256, // P384 and P521 are not constant-time yet, but since we don't // reuse ephemeral keys, using them for ECDH should be OK. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521, @@ -53,7 +54,7 @@ var supportedHostKeyAlgos = []string{ // This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed // because they have reached the end of their useful life. var supportedMACs = []string{ - "hmac-sha1", "hmac-sha1-96", + "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96", } var supportedCompressions = []string{compressionNone} @@ -84,27 +85,15 @@ func parseError(tag uint8) error { return fmt.Errorf("ssh: parse error in message type %d", tag) } -func findCommonAlgorithm(clientAlgos []string, serverAlgos []string) (commonAlgo string, ok bool) { - for _, clientAlgo := range clientAlgos { - for _, serverAlgo := range serverAlgos { - if clientAlgo == serverAlgo { - return clientAlgo, true +func findCommon(what string, client []string, server []string) (common string, err error) { + for _, c := range client { + for _, s := range server { + if c == s { + return c, nil } } } - return -} - -func findCommonCipher(clientCiphers []string, serverCiphers []string) (commonCipher string, ok bool) { - for _, clientCipher := range clientCiphers { - for _, serverCipher := range serverCiphers { - // reject the cipher if we have no cipherModes definition - if clientCipher == serverCipher && cipherModes[clientCipher] != nil { - return clientCipher, true - } - } - } - return + return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server) } type directionAlgorithms struct { @@ -120,50 +109,50 @@ type algorithms struct { r directionAlgorithms } -func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms) { - var ok bool +func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) { result := &algorithms{} - result.kex, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos) - if !ok { + + result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos) + if err != nil { return } - result.hostKey, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) - if !ok { + result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos) + if err != nil { return } - result.w.Cipher, ok = findCommonCipher(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) - if !ok { + result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer) + if err != nil { return } - result.r.Cipher, ok = findCommonCipher(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) - if !ok { + result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient) + if err != nil { return } - result.w.MAC, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) - if !ok { + result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer) + if err != nil { return } - result.r.MAC, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) - if !ok { + result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient) + if err != nil { return } - result.w.Compression, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) - if !ok { + result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer) + if err != nil { return } - result.r.Compression, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) - if !ok { + result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient) + if err != nil { return } - return result + return result, nil } // If rekeythreshold is too small, we can't make any progress sending diff --git a/vendor/golang.org/x/crypto/ssh/connection.go b/vendor/golang.org/x/crypto/ssh/connection.go index 93551e241f37..979d919e81e6 100644 --- a/vendor/golang.org/x/crypto/ssh/connection.go +++ b/vendor/golang.org/x/crypto/ssh/connection.go @@ -33,7 +33,7 @@ type ConnMetadata interface { // into the session ID. ClientVersion() []byte - // ServerVersion returns the client's version string as hashed + // ServerVersion returns the server's version string as hashed // into the session ID. ServerVersion() []byte diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go index a1e2c23dad63..1c54f758781e 100644 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ b/vendor/golang.org/x/crypto/ssh/handshake.go @@ -59,7 +59,14 @@ type handshakeTransport struct { serverVersion []byte clientVersion []byte - hostKeys []Signer // If hostKeys are given, we are the server. + // hostKeys is non-empty if we are the server. In that case, + // it contains all host keys that can be used to sign the + // connection. + hostKeys []Signer + + // hostKeyAlgorithms is non-empty if we are the client. In that case, + // we accept these key types from the server as host key. + hostKeyAlgorithms []string // On read error, incoming is closed, and readError is set. incoming chan []byte @@ -98,6 +105,11 @@ func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byt t.dialAddress = dialAddr t.remoteAddr = addr t.hostKeyCallback = config.HostKeyCallback + if config.HostKeyAlgorithms != nil { + t.hostKeyAlgorithms = config.HostKeyAlgorithms + } else { + t.hostKeyAlgorithms = supportedHostKeyAlgos + } go t.readLoop() return t } @@ -141,6 +153,14 @@ func (t *handshakeTransport) readLoop() { } t.incoming <- p } + + // If we can't read, declare the writing part dead too. + t.mu.Lock() + defer t.mu.Unlock() + if t.writeError == nil { + t.writeError = t.readError + } + t.cond.Broadcast() } func (t *handshakeTransport) readOnePacket() ([]byte, error) { @@ -234,7 +254,7 @@ func (t *handshakeTransport) sendKexInitLocked() (*kexInitMsg, []byte, error) { msg.ServerHostKeyAlgos, k.PublicKey().Type()) } } else { - msg.ServerHostKeyAlgos = supportedHostKeyAlgos + msg.ServerHostKeyAlgos = t.hostKeyAlgorithms } packet := Marshal(msg) @@ -253,10 +273,12 @@ func (t *handshakeTransport) sendKexInitLocked() (*kexInitMsg, []byte, error) { func (t *handshakeTransport) writePacket(p []byte) error { t.mu.Lock() + defer t.mu.Unlock() + if t.writtenSinceKex > t.config.RekeyThreshold { t.sendKexInitLocked() } - for t.sentInitMsg != nil { + for t.sentInitMsg != nil && t.writeError == nil { t.cond.Wait() } if t.writeError != nil { @@ -264,17 +286,14 @@ func (t *handshakeTransport) writePacket(p []byte) error { } t.writtenSinceKex += uint64(len(p)) - var err error switch p[0] { case msgKexInit: - err = errors.New("ssh: only handshakeTransport can send kexInit") + return errors.New("ssh: only handshakeTransport can send kexInit") case msgNewKeys: - err = errors.New("ssh: only handshakeTransport can send newKeys") + return errors.New("ssh: only handshakeTransport can send newKeys") default: - err = t.conn.writePacket(p) + return t.conn.writePacket(p) } - t.mu.Unlock() - return err } func (t *handshakeTransport) Close() error { @@ -313,9 +332,9 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { magics.serverKexInit = otherInitPacket } - algs := findAgreedAlgorithms(clientInit, serverInit) - if algs == nil { - return errors.New("ssh: no common algorithms") + algs, err := findAgreedAlgorithms(clientInit, serverInit) + if err != nil { + return err } // We don't send FirstKexFollows, but we handle receiving it. diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go index 6a835c7630d3..3ec603c0a159 100644 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ b/vendor/golang.org/x/crypto/ssh/kex.go @@ -9,17 +9,21 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "crypto/subtle" "errors" "io" "math/big" + + "golang.org/x/crypto/curve25519" ) const ( - kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" - kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" - kexAlgoECDH256 = "ecdh-sha2-nistp256" - kexAlgoECDH384 = "ecdh-sha2-nistp384" - kexAlgoECDH521 = "ecdh-sha2-nistp521" + kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1" + kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1" + kexAlgoECDH256 = "ecdh-sha2-nistp256" + kexAlgoECDH384 = "ecdh-sha2-nistp384" + kexAlgoECDH521 = "ecdh-sha2-nistp521" + kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org" ) // kexResult captures the outcome of a key exchange. @@ -383,4 +387,140 @@ func init() { kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()} kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()} kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()} + kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{} +} + +// curve25519sha256 implements the curve25519-sha256@libssh.org key +// agreement protocol, as described in +// https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt +type curve25519sha256 struct{} + +type curve25519KeyPair struct { + priv [32]byte + pub [32]byte +} + +func (kp *curve25519KeyPair) generate(rand io.Reader) error { + if _, err := io.ReadFull(rand, kp.priv[:]); err != nil { + return err + } + curve25519.ScalarBaseMult(&kp.pub, &kp.priv) + return nil +} + +// curve25519Zeros is just an array of 32 zero bytes so that we have something +// convenient to compare against in order to reject curve25519 points with the +// wrong order. +var curve25519Zeros [32]byte + +func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) { + var kp curve25519KeyPair + if err := kp.generate(rand); err != nil { + return nil, err + } + if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil { + return nil, err + } + + packet, err := c.readPacket() + if err != nil { + return nil, err + } + + var reply kexECDHReplyMsg + if err = Unmarshal(packet, &reply); err != nil { + return nil, err + } + if len(reply.EphemeralPubKey) != 32 { + return nil, errors.New("ssh: peer's curve25519 public value has wrong length") + } + + var servPub, secret [32]byte + copy(servPub[:], reply.EphemeralPubKey) + curve25519.ScalarMult(&secret, &kp.priv, &servPub) + if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { + return nil, errors.New("ssh: peer's curve25519 public value has wrong order") + } + + h := crypto.SHA256.New() + magics.write(h) + writeString(h, reply.HostKey) + writeString(h, kp.pub[:]) + writeString(h, reply.EphemeralPubKey) + + kInt := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(kInt)) + marshalInt(K, kInt) + h.Write(K) + + return &kexResult{ + H: h.Sum(nil), + K: K, + HostKey: reply.HostKey, + Signature: reply.Signature, + Hash: crypto.SHA256, + }, nil +} + +func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { + packet, err := c.readPacket() + if err != nil { + return + } + var kexInit kexECDHInitMsg + if err = Unmarshal(packet, &kexInit); err != nil { + return + } + + if len(kexInit.ClientPubKey) != 32 { + return nil, errors.New("ssh: peer's curve25519 public value has wrong length") + } + + var kp curve25519KeyPair + if err := kp.generate(rand); err != nil { + return nil, err + } + + var clientPub, secret [32]byte + copy(clientPub[:], kexInit.ClientPubKey) + curve25519.ScalarMult(&secret, &kp.priv, &clientPub) + if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 { + return nil, errors.New("ssh: peer's curve25519 public value has wrong order") + } + + hostKeyBytes := priv.PublicKey().Marshal() + + h := crypto.SHA256.New() + magics.write(h) + writeString(h, hostKeyBytes) + writeString(h, kexInit.ClientPubKey) + writeString(h, kp.pub[:]) + + kInt := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(kInt)) + marshalInt(K, kInt) + h.Write(K) + + H := h.Sum(nil) + + sig, err := signAndMarshal(priv, rand, H) + if err != nil { + return nil, err + } + + reply := kexECDHReplyMsg{ + EphemeralPubKey: kp.pub[:], + HostKey: hostKeyBytes, + Signature: sig, + } + if err := c.writePacket(Marshal(&reply)); err != nil { + return nil, err + } + return &kexResult{ + H: H, + K: K, + HostKey: hostKeyBytes, + Signature: sig, + Hash: crypto.SHA256, + }, nil } diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index e8af511eeb0c..cfc970b2cd2f 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -19,6 +19,7 @@ import ( "fmt" "io" "math/big" + "strings" ) // These constants represent the algorithm names for key types supported by this @@ -77,6 +78,79 @@ func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) { return out, comment, nil } +// ParseKnownHosts parses an entry in the format of the known_hosts file. +// +// The known_hosts format is documented in the sshd(8) manual page. This +// function will parse a single entry from in. On successful return, marker +// will contain the optional marker value (i.e. "cert-authority" or "revoked") +// or else be empty, hosts will contain the hosts that this entry matches, +// pubKey will contain the public key and comment will contain any trailing +// comment at the end of the line. See the sshd(8) manual page for the various +// forms that a host string can take. +// +// The unparsed remainder of the input will be returned in rest. This function +// can be called repeatedly to parse multiple entries. +// +// If no entries were found in the input then err will be io.EOF. Otherwise a +// non-nil err value indicates a parse error. +func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) { + for len(in) > 0 { + end := bytes.IndexByte(in, '\n') + if end != -1 { + rest = in[end+1:] + in = in[:end] + } else { + rest = nil + } + + end = bytes.IndexByte(in, '\r') + if end != -1 { + in = in[:end] + } + + in = bytes.TrimSpace(in) + if len(in) == 0 || in[0] == '#' { + in = rest + continue + } + + i := bytes.IndexAny(in, " \t") + if i == -1 { + in = rest + continue + } + + // Strip out the begining of the known_host key. + // This is either an optional marker or a (set of) hostname(s). + keyFields := bytes.Fields(in) + if len(keyFields) < 3 || len(keyFields) > 5 { + return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data") + } + + // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated + // list of hosts + marker := "" + if keyFields[0][0] == '@' { + marker = string(keyFields[0][1:]) + keyFields = keyFields[1:] + } + + hosts := string(keyFields[0]) + // keyFields[1] contains the key type (e.g. “ssh-rsa”). + // However, that information is duplicated inside the + // base64-encoded key and so is ignored here. + + key := bytes.Join(keyFields[2:], []byte(" ")) + if pubKey, comment, err = parseAuthorizedKey(key); err != nil { + return "", nil, nil, "", nil, err + } + + return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil + } + + return "", nil, nil, "", nil, io.EOF +} + // ParseAuthorizedKeys parses a public key from an authorized_keys // file used in OpenSSH according to the sshd(8) manual page. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) { @@ -267,28 +341,6 @@ func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error { return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob) } -type rsaPrivateKey struct { - *rsa.PrivateKey -} - -func (r *rsaPrivateKey) PublicKey() PublicKey { - return (*rsaPublicKey)(&r.PrivateKey.PublicKey) -} - -func (r *rsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { - h := crypto.SHA1.New() - h.Write(data) - digest := h.Sum(nil) - blob, err := rsa.SignPKCS1v15(rand, r.PrivateKey, crypto.SHA1, digest) - if err != nil { - return nil, err - } - return &Signature{ - Format: r.PublicKey().Type(), - Blob: blob, - }, nil -} - type dsaPublicKey dsa.PublicKey func (r *dsaPublicKey) Type() string { @@ -422,14 +474,19 @@ func ecHash(curve elliptic.Curve) crypto.Hash { // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { - identifier, in, ok := parseString(in) - if !ok { - return nil, nil, errShortRead + var w struct { + Curve string + KeyBytes []byte + Rest []byte `ssh:"rest"` + } + + if err := Unmarshal(in, &w); err != nil { + return nil, nil, err } key := new(ecdsa.PublicKey) - switch string(identifier) { + switch w.Curve { case "nistp256": key.Curve = elliptic.P256() case "nistp384": @@ -440,16 +497,11 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { return nil, nil, errors.New("ssh: unsupported curve") } - var keyBytes []byte - if keyBytes, in, ok = parseString(in); !ok { - return nil, nil, errShortRead - } - - key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes) + key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) if key.X == nil || key.Y == nil { return nil, nil, errors.New("ssh: invalid curve point") } - return (*ecdsaPublicKey)(key), in, nil + return (*ecdsaPublicKey)(key), w.Rest, nil } func (key *ecdsaPublicKey) Marshal() []byte { @@ -496,72 +548,112 @@ func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { return errors.New("ssh: signature did not verify") } -type ecdsaPrivateKey struct { - *ecdsa.PrivateKey +// NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, +// *ecdsa.PrivateKey or any other crypto.Signer and returns a corresponding +// Signer instance. ECDSA keys must use P-256, P-384 or P-521. +func NewSignerFromKey(key interface{}) (Signer, error) { + switch key := key.(type) { + case crypto.Signer: + return NewSignerFromSigner(key) + case *dsa.PrivateKey: + return &dsaPrivateKey{key}, nil + default: + return nil, fmt.Errorf("ssh: unsupported key type %T", key) + } } -func (k *ecdsaPrivateKey) PublicKey() PublicKey { - return (*ecdsaPublicKey)(&k.PrivateKey.PublicKey) +type wrappedSigner struct { + signer crypto.Signer + pubKey PublicKey } -func (k *ecdsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { - h := ecHash(k.PrivateKey.PublicKey.Curve).New() - h.Write(data) - digest := h.Sum(nil) - r, s, err := ecdsa.Sign(rand, k.PrivateKey, digest) +// NewSignerFromSigner takes any crypto.Signer implementation and +// returns a corresponding Signer interface. This can be used, for +// example, with keys kept in hardware modules. +func NewSignerFromSigner(signer crypto.Signer) (Signer, error) { + pubKey, err := NewPublicKey(signer.Public()) if err != nil { return nil, err } - sig := make([]byte, intLength(r)+intLength(s)) - rest := marshalInt(sig, r) - marshalInt(rest, s) - return &Signature{ - Format: k.PublicKey().Type(), - Blob: sig, - }, nil + return &wrappedSigner{signer, pubKey}, nil } -// NewSignerFromKey takes a pointer to rsa, dsa or ecdsa PrivateKey -// returns a corresponding Signer instance. EC keys should use P256, -// P384 or P521. -func NewSignerFromKey(k interface{}) (Signer, error) { - var sshKey Signer - switch t := k.(type) { - case *rsa.PrivateKey: - sshKey = &rsaPrivateKey{t} - case *dsa.PrivateKey: - sshKey = &dsaPrivateKey{t} - case *ecdsa.PrivateKey: - if !supportedEllipticCurve(t.Curve) { - return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.") - } +func (s *wrappedSigner) PublicKey() PublicKey { + return s.pubKey +} - sshKey = &ecdsaPrivateKey{t} +func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { + var hashFunc crypto.Hash + + switch key := s.pubKey.(type) { + case *rsaPublicKey, *dsaPublicKey: + hashFunc = crypto.SHA1 + case *ecdsaPublicKey: + hashFunc = ecHash(key.Curve) default: - return nil, fmt.Errorf("ssh: unsupported key type %T", k) + return nil, fmt.Errorf("ssh: unsupported key type %T", key) + } + + h := hashFunc.New() + h.Write(data) + digest := h.Sum(nil) + + signature, err := s.signer.Sign(rand, digest, hashFunc) + if err != nil { + return nil, err } - return sshKey, nil + + // crypto.Signer.Sign is expected to return an ASN.1-encoded signature + // for ECDSA and DSA, but that's not the encoding expected by SSH, so + // re-encode. + switch s.pubKey.(type) { + case *ecdsaPublicKey, *dsaPublicKey: + type asn1Signature struct { + R, S *big.Int + } + asn1Sig := new(asn1Signature) + _, err := asn1.Unmarshal(signature, asn1Sig) + if err != nil { + return nil, err + } + + switch s.pubKey.(type) { + case *ecdsaPublicKey: + signature = Marshal(asn1Sig) + + case *dsaPublicKey: + signature = make([]byte, 40) + r := asn1Sig.R.Bytes() + s := asn1Sig.S.Bytes() + copy(signature[20-len(r):20], r) + copy(signature[40-len(s):40], s) + } + } + + return &Signature{ + Format: s.pubKey.Type(), + Blob: signature, + }, nil } -// NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey -// and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521. -func NewPublicKey(k interface{}) (PublicKey, error) { - var sshKey PublicKey - switch t := k.(type) { +// NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey or +// any other crypto.Signer and returns a corresponding Signer instance. ECDSA +// keys must use P-256, P-384 or P-521. +func NewPublicKey(key interface{}) (PublicKey, error) { + switch key := key.(type) { case *rsa.PublicKey: - sshKey = (*rsaPublicKey)(t) + return (*rsaPublicKey)(key), nil case *ecdsa.PublicKey: - if !supportedEllipticCurve(t.Curve) { - return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.") + if !supportedEllipticCurve(key.Curve) { + return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.") } - sshKey = (*ecdsaPublicKey)(t) + return (*ecdsaPublicKey)(key), nil case *dsa.PublicKey: - sshKey = (*dsaPublicKey)(t) + return (*dsaPublicKey)(key), nil default: - return nil, fmt.Errorf("ssh: unsupported key type %T", k) + return nil, fmt.Errorf("ssh: unsupported key type %T", key) } - return sshKey, nil } // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports diff --git a/vendor/golang.org/x/crypto/ssh/mac.go b/vendor/golang.org/x/crypto/ssh/mac.go index aff40429131e..07744ad67138 100644 --- a/vendor/golang.org/x/crypto/ssh/mac.go +++ b/vendor/golang.org/x/crypto/ssh/mac.go @@ -9,6 +9,7 @@ package ssh import ( "crypto/hmac" "crypto/sha1" + "crypto/sha256" "hash" ) @@ -44,6 +45,9 @@ func (t truncatingMAC) Size() int { func (t truncatingMAC) BlockSize() int { return t.hmac.BlockSize() } var macModes = map[string]*macMode{ + "hmac-sha2-256": {32, func(key []byte) hash.Hash { + return hmac.New(sha256.New, key) + }}, "hmac-sha1": {20, func(key []byte) hash.Hash { return hmac.New(sha1.New, key) }}, diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go index f9e44bb1eb1e..eaf6106698e7 100644 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ b/vendor/golang.org/x/crypto/ssh/messages.go @@ -484,11 +484,12 @@ func parseString(in []byte) (out, rest []byte, ok bool) { return } length := binary.BigEndian.Uint32(in) - if uint32(len(in)) < 4+length { + in = in[4:] + if uint32(len(in)) < length { return } - out = in[4 : 4+length] - rest = in[4+length:] + out = in[:length] + rest = in[length:] ok = true return } diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go index 52aee11e3b1c..4781eb78050d 100644 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ b/vendor/golang.org/x/crypto/ssh/server.go @@ -66,9 +66,11 @@ type ServerConfig struct { // attempts. AuthLogCallback func(conn ConnMetadata, method string, err error) - // ServerVersion is the version identification string to - // announce in the public handshake. + // ServerVersion is the version identification string to announce in + // the public handshake. // If empty, a reasonable default is used. + // Note that RFC 4253 section 4.2 requires that this string start with + // "SSH-2.0-". ServerVersion string } @@ -168,6 +170,10 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) return nil, errors.New("ssh: server has no host keys") } + if !config.NoClientAuth && config.PasswordCallback == nil && config.PublicKeyCallback == nil && config.KeyboardInteractiveCallback == nil { + return nil, errors.New("ssh: no authentication methods configured but NoClientAuth is also false") + } + if config.ServerVersion != "" { s.serverVersion = []byte(config.ServerVersion) } else { diff --git a/vendor/golang.org/x/crypto/ssh/session.go b/vendor/golang.org/x/crypto/ssh/session.go index 3b42b508a81b..fd10cd1aaf2f 100644 --- a/vendor/golang.org/x/crypto/ssh/session.go +++ b/vendor/golang.org/x/crypto/ssh/session.go @@ -339,7 +339,7 @@ func (s *Session) Shell() error { ok, err := s.ch.SendRequest("shell", true, nil) if err == nil && !ok { - return fmt.Errorf("ssh: cound not start shell") + return errors.New("ssh: could not start shell") } if err != nil { return err diff --git a/vendor/golang.org/x/crypto/ssh/tcpip.go b/vendor/golang.org/x/crypto/ssh/tcpip.go index 4ecad0b3ff11..6151241ff08e 100644 --- a/vendor/golang.org/x/crypto/ssh/tcpip.go +++ b/vendor/golang.org/x/crypto/ssh/tcpip.go @@ -355,6 +355,9 @@ func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel lport: uint32(lport), } ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg)) + if err != nil { + return nil, err + } go DiscardRequests(in) return ch, err } diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go index 11bd8d34e6c5..ea1a7cd53a12 100644 --- a/vendor/golang.org/x/net/context/context.go +++ b/vendor/golang.org/x/net/context/context.go @@ -36,12 +36,7 @@ // Contexts. package context -import ( - "errors" - "fmt" - "sync" - "time" -) +import "time" // A Context carries a deadline, a cancelation signal, and other values across // API boundaries. @@ -66,7 +61,7 @@ type Context interface { // // // Stream generates values with DoSomething and sends them to out // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out <-chan Value) error { + // func Stream(ctx context.Context, out chan<- Value) error { // for { // v, err := DoSomething(ctx) // if err != nil { @@ -138,48 +133,6 @@ type Context interface { Value(key interface{}) interface{} } -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - // Background returns a non-nil, empty Context. It is never canceled, has no // values, and has no deadline. It is typically used by the main function, // initialization, and tests, and as the top-level Context for incoming @@ -201,247 +154,3 @@ func TODO() Context { // A CancelFunc does not wait for the work to stop. // After the first call, subsequent calls to a CancelFunc do nothing. type CancelFunc func() - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, &c) - return &c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) cancelCtx { - return cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return &c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/cancelreq.go b/vendor/golang.org/x/net/context/ctxhttp/cancelreq.go deleted file mode 100644 index e3170e3333ac..000000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/cancelreq.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package ctxhttp - -import "net/http" - -func canceler(client *http.Client, req *http.Request) func() { - // TODO(djd): Respect any existing value of req.Cancel. - ch := make(chan struct{}) - req.Cancel = ch - - return func() { - close(ch) - } -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go b/vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go deleted file mode 100644 index 56bcbadb85fc..000000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/cancelreq_go14.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package ctxhttp - -import "net/http" - -type requestCanceler interface { - CancelRequest(*http.Request) -} - -func canceler(client *http.Client, req *http.Request) func() { - rc, ok := client.Transport.(requestCanceler) - if !ok { - return func() {} - } - return func() { - rc.CancelRequest(req) - } -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go index 26a5e19ac3d6..f31d88273674 100644 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go @@ -1,7 +1,9 @@ -// Copyright 2015 The Go Authors. All rights reserved. +// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// +build go1.7 + // Package ctxhttp provides helper functions for performing context-aware HTTP requests. package ctxhttp @@ -14,71 +16,18 @@ import ( "golang.org/x/net/context" ) -func nop() {} - -var ( - testHookContextDoneBeforeHeaders = nop - testHookDoReturned = nop - testHookDidBodyClose = nop -) - -// Do sends an HTTP request with the provided http.Client and returns an HTTP response. +// Do sends an HTTP request with the provided http.Client and returns +// an HTTP response. +// // If the client is nil, http.DefaultClient is used. -// If the context is canceled or times out, ctx.Err() will be returned. +// +// The provided ctx must be non-nil. If it is canceled or times out, +// ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } - - // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. - cancel := canceler(client, req) - - type responseAndError struct { - resp *http.Response - err error - } - result := make(chan responseAndError, 1) - - go func() { - resp, err := client.Do(req) - testHookDoReturned() - result <- responseAndError{resp, err} - }() - - var resp *http.Response - - select { - case <-ctx.Done(): - testHookContextDoneBeforeHeaders() - cancel() - // Clean up after the goroutine calling client.Do: - go func() { - if r := <-result; r.resp != nil { - testHookDidBodyClose() - r.resp.Body.Close() - } - }() - return nil, ctx.Err() - case r := <-result: - var err error - resp, err = r.resp, r.err - if err != nil { - return resp, err - } - } - - c := make(chan struct{}) - go func() { - select { - case <-ctx.Done(): - cancel() - case <-c: - // The response's Body is closed. - } - }() - resp.Body = ¬ifyingReader{resp.Body, c} - - return resp, nil + return client.Do(req.WithContext(ctx)) } // Get issues a GET request via the Do function. @@ -113,28 +62,3 @@ func Post(ctx context.Context, client *http.Client, url string, bodyType string, func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } - -// notifyingReader is an io.ReadCloser that closes the notify channel after -// Close is called or a Read fails on the underlying ReadCloser. -type notifyingReader struct { - io.ReadCloser - notify chan<- struct{} -} - -func (r *notifyingReader) Read(p []byte) (int, error) { - n, err := r.ReadCloser.Read(p) - if err != nil && r.notify != nil { - close(r.notify) - r.notify = nil - } - return n, err -} - -func (r *notifyingReader) Close() error { - err := r.ReadCloser.Close() - if r.notify != nil { - close(r.notify) - r.notify = nil - } - return err -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go new file mode 100644 index 000000000000..7564b203276a --- /dev/null +++ b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go @@ -0,0 +1,147 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.7 + +package ctxhttp + +import ( + "io" + "net/http" + "net/url" + "strings" + + "golang.org/x/net/context" +) + +func nop() {} + +var ( + testHookContextDoneBeforeHeaders = nop + testHookDoReturned = nop + testHookDidBodyClose = nop +) + +// Do sends an HTTP request with the provided http.Client and returns an HTTP response. +// If the client is nil, http.DefaultClient is used. +// If the context is canceled or times out, ctx.Err() will be returned. +func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + + // TODO(djd): Respect any existing value of req.Cancel. + cancel := make(chan struct{}) + req.Cancel = cancel + + type responseAndError struct { + resp *http.Response + err error + } + result := make(chan responseAndError, 1) + + // Make local copies of test hooks closed over by goroutines below. + // Prevents data races in tests. + testHookDoReturned := testHookDoReturned + testHookDidBodyClose := testHookDidBodyClose + + go func() { + resp, err := client.Do(req) + testHookDoReturned() + result <- responseAndError{resp, err} + }() + + var resp *http.Response + + select { + case <-ctx.Done(): + testHookContextDoneBeforeHeaders() + close(cancel) + // Clean up after the goroutine calling client.Do: + go func() { + if r := <-result; r.resp != nil { + testHookDidBodyClose() + r.resp.Body.Close() + } + }() + return nil, ctx.Err() + case r := <-result: + var err error + resp, err = r.resp, r.err + if err != nil { + return resp, err + } + } + + c := make(chan struct{}) + go func() { + select { + case <-ctx.Done(): + close(cancel) + case <-c: + // The response's Body is closed. + } + }() + resp.Body = ¬ifyingReader{resp.Body, c} + + return resp, nil +} + +// Get issues a GET request via the Do function. +func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + return Do(ctx, client, req) +} + +// Head issues a HEAD request via the Do function. +func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { + req, err := http.NewRequest("HEAD", url, nil) + if err != nil { + return nil, err + } + return Do(ctx, client, req) +} + +// Post issues a POST request via the Do function. +func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { + req, err := http.NewRequest("POST", url, body) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", bodyType) + return Do(ctx, client, req) +} + +// PostForm issues a POST request via the Do function. +func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { + return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) +} + +// notifyingReader is an io.ReadCloser that closes the notify channel after +// Close is called or a Read fails on the underlying ReadCloser. +type notifyingReader struct { + io.ReadCloser + notify chan<- struct{} +} + +func (r *notifyingReader) Read(p []byte) (int, error) { + n, err := r.ReadCloser.Read(p) + if err != nil && r.notify != nil { + close(r.notify) + r.notify = nil + } + return n, err +} + +func (r *notifyingReader) Close() error { + err := r.ReadCloser.Close() + if r.notify != nil { + close(r.notify) + r.notify = nil + } + return err +} diff --git a/vendor/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go new file mode 100644 index 000000000000..f8cda19adaee --- /dev/null +++ b/vendor/golang.org/x/net/context/go17.go @@ -0,0 +1,72 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.7 + +package context + +import ( + "context" // standard library's context, as of Go 1.7 + "time" +) + +var ( + todo = context.TODO() + background = context.Background() +) + +// Canceled is the error returned by Context.Err when the context is canceled. +var Canceled = context.Canceled + +// DeadlineExceeded is the error returned by Context.Err when the context's +// deadline passes. +var DeadlineExceeded = context.DeadlineExceeded + +// WithCancel returns a copy of parent with a new Done channel. The returned +// context's Done channel is closed when the returned cancel function is called +// or when the parent context's Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete. +func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { + ctx, f := context.WithCancel(parent) + return ctx, CancelFunc(f) +} + +// WithDeadline returns a copy of the parent context with the deadline adjusted +// to be no later than d. If the parent's deadline is already earlier than d, +// WithDeadline(parent, d) is semantically equivalent to parent. The returned +// context's Done channel is closed when the deadline expires, when the returned +// cancel function is called, or when the parent context's Done channel is +// closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete. +func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { + ctx, f := context.WithDeadline(parent, deadline) + return ctx, CancelFunc(f) +} + +// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete: +// +// func slowOperationWithTimeout(ctx context.Context) (Result, error) { +// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) +// defer cancel() // releases resources if slowOperation completes before timeout elapses +// return slowOperation(ctx) +// } +func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { + return WithDeadline(parent, time.Now().Add(timeout)) +} + +// WithValue returns a copy of parent in which the value associated with key is +// val. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +func WithValue(parent Context, key interface{}, val interface{}) Context { + return context.WithValue(parent, key, val) +} diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go new file mode 100644 index 000000000000..5a30acabd03c --- /dev/null +++ b/vendor/golang.org/x/net/context/pre_go17.go @@ -0,0 +1,300 @@ +// 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. + +// +build !go1.7 + +package context + +import ( + "errors" + "fmt" + "sync" + "time" +) + +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (*emptyCtx) Done() <-chan struct{} { + return nil +} + +func (*emptyCtx) Err() error { + return nil +} + +func (*emptyCtx) Value(key interface{}) interface{} { + return nil +} + +func (e *emptyCtx) String() string { + switch e { + case background: + return "context.Background" + case todo: + return "context.TODO" + } + return "unknown empty Context" +} + +var ( + background = new(emptyCtx) + todo = new(emptyCtx) +) + +// Canceled is the error returned by Context.Err when the context is canceled. +var Canceled = errors.New("context canceled") + +// DeadlineExceeded is the error returned by Context.Err when the context's +// deadline passes. +var DeadlineExceeded = errors.New("context deadline exceeded") + +// WithCancel returns a copy of parent with a new Done channel. The returned +// context's Done channel is closed when the returned cancel function is called +// or when the parent context's Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete. +func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { + c := newCancelCtx(parent) + propagateCancel(parent, c) + return c, func() { c.cancel(true, Canceled) } +} + +// newCancelCtx returns an initialized cancelCtx. +func newCancelCtx(parent Context) *cancelCtx { + return &cancelCtx{ + Context: parent, + done: make(chan struct{}), + } +} + +// propagateCancel arranges for child to be canceled when parent is. +func propagateCancel(parent Context, child canceler) { + if parent.Done() == nil { + return // parent is never canceled + } + if p, ok := parentCancelCtx(parent); ok { + p.mu.Lock() + if p.err != nil { + // parent has already been canceled + child.cancel(false, p.err) + } else { + if p.children == nil { + p.children = make(map[canceler]bool) + } + p.children[child] = true + } + p.mu.Unlock() + } else { + go func() { + select { + case <-parent.Done(): + child.cancel(false, parent.Err()) + case <-child.Done(): + } + }() + } +} + +// parentCancelCtx follows a chain of parent references until it finds a +// *cancelCtx. This function understands how each of the concrete types in this +// package represents its parent. +func parentCancelCtx(parent Context) (*cancelCtx, bool) { + for { + switch c := parent.(type) { + case *cancelCtx: + return c, true + case *timerCtx: + return c.cancelCtx, true + case *valueCtx: + parent = c.Context + default: + return nil, false + } + } +} + +// removeChild removes a context from its parent. +func removeChild(parent Context, child canceler) { + p, ok := parentCancelCtx(parent) + if !ok { + return + } + p.mu.Lock() + if p.children != nil { + delete(p.children, child) + } + p.mu.Unlock() +} + +// A canceler is a context type that can be canceled directly. The +// implementations are *cancelCtx and *timerCtx. +type canceler interface { + cancel(removeFromParent bool, err error) + Done() <-chan struct{} +} + +// A cancelCtx can be canceled. When canceled, it also cancels any children +// that implement canceler. +type cancelCtx struct { + Context + + done chan struct{} // closed by the first cancel call. + + mu sync.Mutex + children map[canceler]bool // set to nil by the first cancel call + err error // set to non-nil by the first cancel call +} + +func (c *cancelCtx) Done() <-chan struct{} { + return c.done +} + +func (c *cancelCtx) Err() error { + c.mu.Lock() + defer c.mu.Unlock() + return c.err +} + +func (c *cancelCtx) String() string { + return fmt.Sprintf("%v.WithCancel", c.Context) +} + +// cancel closes c.done, cancels each of c's children, and, if +// removeFromParent is true, removes c from its parent's children. +func (c *cancelCtx) cancel(removeFromParent bool, err error) { + if err == nil { + panic("context: internal error: missing cancel error") + } + c.mu.Lock() + if c.err != nil { + c.mu.Unlock() + return // already canceled + } + c.err = err + close(c.done) + for child := range c.children { + // NOTE: acquiring the child's lock while holding parent's lock. + child.cancel(false, err) + } + c.children = nil + c.mu.Unlock() + + if removeFromParent { + removeChild(c.Context, c) + } +} + +// WithDeadline returns a copy of the parent context with the deadline adjusted +// to be no later than d. If the parent's deadline is already earlier than d, +// WithDeadline(parent, d) is semantically equivalent to parent. The returned +// context's Done channel is closed when the deadline expires, when the returned +// cancel function is called, or when the parent context's Done channel is +// closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete. +func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { + if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { + // The current deadline is already sooner than the new one. + return WithCancel(parent) + } + c := &timerCtx{ + cancelCtx: newCancelCtx(parent), + deadline: deadline, + } + propagateCancel(parent, c) + d := deadline.Sub(time.Now()) + if d <= 0 { + c.cancel(true, DeadlineExceeded) // deadline has already passed + return c, func() { c.cancel(true, Canceled) } + } + c.mu.Lock() + defer c.mu.Unlock() + if c.err == nil { + c.timer = time.AfterFunc(d, func() { + c.cancel(true, DeadlineExceeded) + }) + } + return c, func() { c.cancel(true, Canceled) } +} + +// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to +// implement Done and Err. It implements cancel by stopping its timer then +// delegating to cancelCtx.cancel. +type timerCtx struct { + *cancelCtx + timer *time.Timer // Under cancelCtx.mu. + + deadline time.Time +} + +func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { + return c.deadline, true +} + +func (c *timerCtx) String() string { + return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) +} + +func (c *timerCtx) cancel(removeFromParent bool, err error) { + c.cancelCtx.cancel(false, err) + if removeFromParent { + // Remove this timerCtx from its parent cancelCtx's children. + removeChild(c.cancelCtx.Context, c) + } + c.mu.Lock() + if c.timer != nil { + c.timer.Stop() + c.timer = nil + } + c.mu.Unlock() +} + +// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete: +// +// func slowOperationWithTimeout(ctx context.Context) (Result, error) { +// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) +// defer cancel() // releases resources if slowOperation completes before timeout elapses +// return slowOperation(ctx) +// } +func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { + return WithDeadline(parent, time.Now().Add(timeout)) +} + +// WithValue returns a copy of parent in which the value associated with key is +// val. +// +// Use context Values only for request-scoped data that transits processes and +// APIs, not for passing optional parameters to functions. +func WithValue(parent Context, key interface{}, val interface{}) Context { + return &valueCtx{parent, key, val} +} + +// A valueCtx carries a key-value pair. It implements Value for that key and +// delegates all other calls to the embedded Context. +type valueCtx struct { + Context + key, val interface{} +} + +func (c *valueCtx) String() string { + return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) +} + +func (c *valueCtx) Value(key interface{}) interface{} { + if c.key == key { + return c.val + } + return c.Context.Value(key) +} diff --git a/vendor/golang.org/x/net/http2/client_conn_pool.go b/vendor/golang.org/x/net/http2/client_conn_pool.go index 772ea5e92441..547e238a5858 100644 --- a/vendor/golang.org/x/net/http2/client_conn_pool.go +++ b/vendor/golang.org/x/net/http2/client_conn_pool.go @@ -18,6 +18,18 @@ type ClientConnPool interface { MarkDead(*ClientConn) } +// clientConnPoolIdleCloser is the interface implemented by ClientConnPool +// implementations which can close their idle connections. +type clientConnPoolIdleCloser interface { + ClientConnPool + closeIdleConnections() +} + +var ( + _ clientConnPoolIdleCloser = (*clientConnPool)(nil) + _ clientConnPoolIdleCloser = noDialClientConnPool{} +) + // TODO: use singleflight for dialing and addConnCalls? type clientConnPool struct { t *Transport @@ -40,7 +52,16 @@ const ( noDialOnMiss = false ) -func (p *clientConnPool) getClientConn(_ *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { +func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { + if req.Close && dialOnMiss { + // It gets its own connection. + cc, err := p.t.dialClientConn(addr) + if err != nil { + return nil, err + } + cc.singleUse = true + return cc, nil + } p.mu.Lock() for _, cc := range p.conns[addr] { if cc.CanTakeNewRequest() { @@ -223,3 +244,12 @@ func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn { } return out } + +// noDialClientConnPool is an implementation of http2.ClientConnPool +// which never dials. We let the HTTP/1.1 client dial and use its TLS +// connection instead. +type noDialClientConnPool struct{ *clientConnPool } + +func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { + return p.getClientConn(req, addr, noDialOnMiss) +} diff --git a/vendor/golang.org/x/net/http2/configure_transport.go b/vendor/golang.org/x/net/http2/configure_transport.go index daa17f5d43ba..4f720f530b00 100644 --- a/vendor/golang.org/x/net/http2/configure_transport.go +++ b/vendor/golang.org/x/net/http2/configure_transport.go @@ -32,7 +32,7 @@ func configureTransport(t1 *http.Transport) (*Transport, error) { t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1") } upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper { - addr := authorityAddr(authority) + addr := authorityAddr("https", authority) if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil { go c.Close() return erringRoundTripper{err} @@ -67,15 +67,6 @@ func registerHTTPSProtocol(t *http.Transport, rt http.RoundTripper) (err error) return nil } -// noDialClientConnPool is an implementation of http2.ClientConnPool -// which never dials. We let the HTTP/1.1 client dial and use its TLS -// connection instead. -type noDialClientConnPool struct{ *clientConnPool } - -func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { - return p.getClientConn(req, addr, noDialOnMiss) -} - // noDialH2RoundTripper is a RoundTripper which only tries to complete the request // if there's already has a cached connection to the host. type noDialH2RoundTripper struct{ t *Transport } diff --git a/vendor/golang.org/x/net/http2/errors.go b/vendor/golang.org/x/net/http2/errors.go index f320b2c09efb..71a4e2905683 100644 --- a/vendor/golang.org/x/net/http2/errors.go +++ b/vendor/golang.org/x/net/http2/errors.go @@ -4,7 +4,10 @@ package http2 -import "fmt" +import ( + "errors" + "fmt" +) // An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec. type ErrCode uint32 @@ -88,3 +91,32 @@ type connError struct { func (e connError) Error() string { return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason) } + +type pseudoHeaderError string + +func (e pseudoHeaderError) Error() string { + return fmt.Sprintf("invalid pseudo-header %q", string(e)) +} + +type duplicatePseudoHeaderError string + +func (e duplicatePseudoHeaderError) Error() string { + return fmt.Sprintf("duplicate pseudo-header %q", string(e)) +} + +type headerFieldNameError string + +func (e headerFieldNameError) Error() string { + return fmt.Sprintf("invalid header field name %q", string(e)) +} + +type headerFieldValueError string + +func (e headerFieldValueError) Error() string { + return fmt.Sprintf("invalid header field value %q", string(e)) +} + +var ( + errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers") + errPseudoAfterRegular = errors.New("pseudo header field after regular") +) diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index e1e837cc8a21..981d407a714c 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -11,7 +11,11 @@ import ( "fmt" "io" "log" + "strings" "sync" + + "golang.org/x/net/http2/hpack" + "golang.org/x/net/lex/httplex" ) const frameHeaderLen = 9 @@ -261,7 +265,7 @@ type Frame interface { type Framer struct { r io.Reader lastFrame Frame - errReason string + errDetail error // lastHeaderStream is non-zero if the last frame was an // unfinished HEADERS/CONTINUATION. @@ -293,8 +297,20 @@ type Framer struct { // to return non-compliant frames or frame orders. // This is for testing and permits using the Framer to test // other HTTP/2 implementations' conformance to the spec. + // It is not compatible with ReadMetaHeaders. AllowIllegalReads bool + // ReadMetaHeaders if non-nil causes ReadFrame to merge + // HEADERS and CONTINUATION frames together and return + // MetaHeadersFrame instead. + ReadMetaHeaders *hpack.Decoder + + // MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE. + // It's used only if ReadMetaHeaders is set; 0 means a sane default + // (currently 16MB) + // If the limit is hit, MetaHeadersFrame.Truncated is set true. + MaxHeaderListSize uint32 + // TODO: track which type of frame & with which flags was sent // last. Then return an error (unless AllowIllegalWrites) if // we're in the middle of a header block and a @@ -307,6 +323,13 @@ type Framer struct { debugFramerBuf *bytes.Buffer } +func (fr *Framer) maxHeaderListSize() uint32 { + if fr.MaxHeaderListSize == 0 { + return 16 << 20 // sane default, per docs + } + return fr.MaxHeaderListSize +} + func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) { // Write the FrameHeader. f.wbuf = append(f.wbuf[:0], @@ -402,6 +425,17 @@ func (fr *Framer) SetMaxReadFrameSize(v uint32) { fr.maxReadSize = v } +// ErrorDetail returns a more detailed error of the last error +// returned by Framer.ReadFrame. For instance, if ReadFrame +// returns a StreamError with code PROTOCOL_ERROR, ErrorDetail +// will say exactly what was invalid. ErrorDetail is not guaranteed +// to return a non-nil value and like the rest of the http2 package, +// its return value is not protected by an API compatibility promise. +// ErrorDetail is reset after the next call to ReadFrame. +func (fr *Framer) ErrorDetail() error { + return fr.errDetail +} + // ErrFrameTooLarge is returned from Framer.ReadFrame when the peer // sends a frame that is larger than declared with SetMaxReadFrameSize. var ErrFrameTooLarge = errors.New("http2: frame too large") @@ -420,9 +454,10 @@ func terminalReadFrameError(err error) bool { // // If the frame is larger than previously set with SetMaxReadFrameSize, the // returned error is ErrFrameTooLarge. Other errors may be of type -// ConnectionError, StreamError, or anything else from from the underlying +// ConnectionError, StreamError, or anything else from the underlying // reader. func (fr *Framer) ReadFrame() (Frame, error) { + fr.errDetail = nil if fr.lastFrame != nil { fr.lastFrame.invalidate() } @@ -450,6 +485,9 @@ func (fr *Framer) ReadFrame() (Frame, error) { if fr.logReads { log.Printf("http2: Framer %p: read %v", fr, summarizeFrame(f)) } + if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil { + return fr.readMetaFrame(f.(*HeadersFrame)) + } return f, nil } @@ -458,7 +496,7 @@ func (fr *Framer) ReadFrame() (Frame, error) { // to the peer before hanging up on them. This might help others debug // their implementations. func (fr *Framer) connError(code ErrCode, reason string) error { - fr.errReason = reason + fr.errDetail = errors.New(reason) return ConnectionError(code) } @@ -553,7 +591,14 @@ func parseDataFrame(fh FrameHeader, payload []byte) (Frame, error) { return f, nil } -var errStreamID = errors.New("invalid streamid") +var ( + errStreamID = errors.New("invalid stream ID") + errDepStreamID = errors.New("invalid dependent stream ID") +) + +func validStreamIDOrZero(streamID uint32) bool { + return streamID&(1<<31) == 0 +} func validStreamID(streamID uint32) bool { return streamID != 0 && streamID&(1<<31) == 0 @@ -940,8 +985,8 @@ func (f *Framer) WriteHeaders(p HeadersFrameParam) error { } if !p.Priority.IsZero() { v := p.Priority.StreamDep - if !validStreamID(v) && !f.AllowIllegalWrites { - return errors.New("invalid dependent stream id") + if !validStreamIDOrZero(v) && !f.AllowIllegalWrites { + return errDepStreamID } if p.Priority.Exclusive { v |= 1 << 31 @@ -1009,6 +1054,9 @@ func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error { if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } + if !validStreamIDOrZero(p.StreamDep) { + return errDepStreamID + } f.startWrite(FramePriority, 0, streamID) v := p.StreamDep if p.Exclusive { @@ -1225,6 +1273,196 @@ type headersEnder interface { HeadersEnded() bool } +type headersOrContinuation interface { + headersEnder + HeaderBlockFragment() []byte +} + +// A MetaHeadersFrame is the representation of one HEADERS frame and +// zero or more contiguous CONTINUATION frames and the decoding of +// their HPACK-encoded contents. +// +// This type of frame does not appear on the wire and is only returned +// by the Framer when Framer.ReadMetaHeaders is set. +type MetaHeadersFrame struct { + *HeadersFrame + + // Fields are the fields contained in the HEADERS and + // CONTINUATION frames. The underlying slice is owned by the + // Framer and must not be retained after the next call to + // ReadFrame. + // + // Fields are guaranteed to be in the correct http2 order and + // not have unknown pseudo header fields or invalid header + // field names or values. Required pseudo header fields may be + // missing, however. Use the MetaHeadersFrame.Pseudo accessor + // method access pseudo headers. + Fields []hpack.HeaderField + + // Truncated is whether the max header list size limit was hit + // and Fields is incomplete. The hpack decoder state is still + // valid, however. + Truncated bool +} + +// PseudoValue returns the given pseudo header field's value. +// The provided pseudo field should not contain the leading colon. +func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string { + for _, hf := range mh.Fields { + if !hf.IsPseudo() { + return "" + } + if hf.Name[1:] == pseudo { + return hf.Value + } + } + return "" +} + +// RegularFields returns the regular (non-pseudo) header fields of mh. +// The caller does not own the returned slice. +func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField { + for i, hf := range mh.Fields { + if !hf.IsPseudo() { + return mh.Fields[i:] + } + } + return nil +} + +// PseudoFields returns the pseudo header fields of mh. +// The caller does not own the returned slice. +func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField { + for i, hf := range mh.Fields { + if !hf.IsPseudo() { + return mh.Fields[:i] + } + } + return mh.Fields +} + +func (mh *MetaHeadersFrame) checkPseudos() error { + var isRequest, isResponse bool + pf := mh.PseudoFields() + for i, hf := range pf { + switch hf.Name { + case ":method", ":path", ":scheme", ":authority": + isRequest = true + case ":status": + isResponse = true + default: + return pseudoHeaderError(hf.Name) + } + // Check for duplicates. + // This would be a bad algorithm, but N is 4. + // And this doesn't allocate. + for _, hf2 := range pf[:i] { + if hf.Name == hf2.Name { + return duplicatePseudoHeaderError(hf.Name) + } + } + } + if isRequest && isResponse { + return errMixPseudoHeaderTypes + } + return nil +} + +func (fr *Framer) maxHeaderStringLen() int { + v := fr.maxHeaderListSize() + if uint32(int(v)) == v { + return int(v) + } + // They had a crazy big number for MaxHeaderBytes anyway, + // so give them unlimited header lengths: + return 0 +} + +// readMetaFrame returns 0 or more CONTINUATION frames from fr and +// merge them into into the provided hf and returns a MetaHeadersFrame +// with the decoded hpack values. +func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { + if fr.AllowIllegalReads { + return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders") + } + mh := &MetaHeadersFrame{ + HeadersFrame: hf, + } + var remainSize = fr.maxHeaderListSize() + var sawRegular bool + + var invalid error // pseudo header field errors + hdec := fr.ReadMetaHeaders + hdec.SetEmitEnabled(true) + hdec.SetMaxStringLength(fr.maxHeaderStringLen()) + hdec.SetEmitFunc(func(hf hpack.HeaderField) { + if !httplex.ValidHeaderFieldValue(hf.Value) { + invalid = headerFieldValueError(hf.Value) + } + isPseudo := strings.HasPrefix(hf.Name, ":") + if isPseudo { + if sawRegular { + invalid = errPseudoAfterRegular + } + } else { + sawRegular = true + if !validWireHeaderFieldName(hf.Name) { + invalid = headerFieldNameError(hf.Name) + } + } + + if invalid != nil { + hdec.SetEmitEnabled(false) + return + } + + size := hf.Size() + if size > remainSize { + hdec.SetEmitEnabled(false) + mh.Truncated = true + return + } + remainSize -= size + + mh.Fields = append(mh.Fields, hf) + }) + // Lose reference to MetaHeadersFrame: + defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {}) + + var hc headersOrContinuation = hf + for { + frag := hc.HeaderBlockFragment() + if _, err := hdec.Write(frag); err != nil { + return nil, ConnectionError(ErrCodeCompression) + } + + if hc.HeadersEnded() { + break + } + if f, err := fr.ReadFrame(); err != nil { + return nil, err + } else { + hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder + } + } + + mh.HeadersFrame.headerFragBuf = nil + mh.HeadersFrame.invalidate() + + if err := hdec.Close(); err != nil { + return nil, ConnectionError(ErrCodeCompression) + } + if invalid != nil { + fr.errDetail = invalid + return nil, StreamError{mh.StreamID, ErrCodeProtocol} + } + if err := mh.checkPseudos(); err != nil { + fr.errDetail = err + return nil, StreamError{mh.StreamID, ErrCodeProtocol} + } + return mh, nil +} + func summarizeFrame(f Frame) string { var buf bytes.Buffer f.Header().writeDebug(&buf) diff --git a/vendor/golang.org/x/net/http2/go15.go b/vendor/golang.org/x/net/http2/go15.go deleted file mode 100644 index f0a562414155..000000000000 --- a/vendor/golang.org/x/net/http2/go15.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package http2 - -import "net/http" - -func requestCancel(req *http.Request) <-chan struct{} { return req.Cancel } diff --git a/vendor/golang.org/x/net/http2/go16.go b/vendor/golang.org/x/net/http2/go16.go new file mode 100644 index 000000000000..2b72855f5521 --- /dev/null +++ b/vendor/golang.org/x/net/http2/go16.go @@ -0,0 +1,43 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.6 + +package http2 + +import ( + "crypto/tls" + "net/http" + "time" +) + +func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { + return t1.ExpectContinueTimeout +} + +// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. +func isBadCipher(cipher uint16) bool { + switch cipher { + case tls.TLS_RSA_WITH_RC4_128_SHA, + tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, + tls.TLS_RSA_WITH_AES_128_CBC_SHA, + tls.TLS_RSA_WITH_AES_256_CBC_SHA, + tls.TLS_RSA_WITH_AES_128_GCM_SHA256, + tls.TLS_RSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, + tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: + // Reject cipher suites from Appendix A. + // "This list includes those cipher suites that do not + // offer an ephemeral key exchange and those that are + // based on the TLS null, stream or block cipher type" + return true + default: + return false + } +} diff --git a/vendor/golang.org/x/net/http2/go17.go b/vendor/golang.org/x/net/http2/go17.go new file mode 100644 index 000000000000..730319dd5ac7 --- /dev/null +++ b/vendor/golang.org/x/net/http2/go17.go @@ -0,0 +1,94 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.7 + +package http2 + +import ( + "context" + "net" + "net/http" + "net/http/httptrace" + "time" +) + +type contextContext interface { + context.Context +} + +func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { + ctx, cancel = context.WithCancel(context.Background()) + ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) + if hs := opts.baseConfig(); hs != nil { + ctx = context.WithValue(ctx, http.ServerContextKey, hs) + } + return +} + +func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { + return context.WithCancel(ctx) +} + +func requestWithContext(req *http.Request, ctx contextContext) *http.Request { + return req.WithContext(ctx) +} + +type clientTrace httptrace.ClientTrace + +func reqContext(r *http.Request) context.Context { return r.Context() } + +func setResponseUncompressed(res *http.Response) { res.Uncompressed = true } + +func traceGotConn(req *http.Request, cc *ClientConn) { + trace := httptrace.ContextClientTrace(req.Context()) + if trace == nil || trace.GotConn == nil { + return + } + ci := httptrace.GotConnInfo{Conn: cc.tconn} + cc.mu.Lock() + ci.Reused = cc.nextStreamID > 1 + ci.WasIdle = len(cc.streams) == 0 && ci.Reused + if ci.WasIdle && !cc.lastActive.IsZero() { + ci.IdleTime = time.Now().Sub(cc.lastActive) + } + cc.mu.Unlock() + + trace.GotConn(ci) +} + +func traceWroteHeaders(trace *clientTrace) { + if trace != nil && trace.WroteHeaders != nil { + trace.WroteHeaders() + } +} + +func traceGot100Continue(trace *clientTrace) { + if trace != nil && trace.Got100Continue != nil { + trace.Got100Continue() + } +} + +func traceWait100Continue(trace *clientTrace) { + if trace != nil && trace.Wait100Continue != nil { + trace.Wait100Continue() + } +} + +func traceWroteRequest(trace *clientTrace, err error) { + if trace != nil && trace.WroteRequest != nil { + trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) + } +} + +func traceFirstResponseByte(trace *clientTrace) { + if trace != nil && trace.GotFirstResponseByte != nil { + trace.GotFirstResponseByte() + } +} + +func requestTrace(req *http.Request) *clientTrace { + trace := httptrace.ContextClientTrace(req.Context()) + return (*clientTrace)(trace) +} diff --git a/vendor/golang.org/x/net/http2/hpack/encode.go b/vendor/golang.org/x/net/http2/hpack/encode.go index 80d621cf3555..f9bb03398483 100644 --- a/vendor/golang.org/x/net/http2/hpack/encode.go +++ b/vendor/golang.org/x/net/http2/hpack/encode.go @@ -144,7 +144,7 @@ func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) { // shouldIndex reports whether f should be indexed. func (e *Encoder) shouldIndex(f HeaderField) bool { - return !f.Sensitive && f.size() <= e.dynTab.maxSize + return !f.Sensitive && f.Size() <= e.dynTab.maxSize } // appendIndexed appends index i, as encoded in "Indexed Header Field" diff --git a/vendor/golang.org/x/net/http2/hpack/hpack.go b/vendor/golang.org/x/net/http2/hpack/hpack.go index 2ea4949ab089..8aa197ad678d 100644 --- a/vendor/golang.org/x/net/http2/hpack/hpack.go +++ b/vendor/golang.org/x/net/http2/hpack/hpack.go @@ -41,6 +41,14 @@ type HeaderField struct { Sensitive bool } +// IsPseudo reports whether the header field is an http2 pseudo header. +// That is, it reports whether it starts with a colon. +// It is not otherwise guaranteed to be a valid pseudo header field, +// though. +func (hf HeaderField) IsPseudo() bool { + return len(hf.Name) != 0 && hf.Name[0] == ':' +} + func (hf HeaderField) String() string { var suffix string if hf.Sensitive { @@ -49,7 +57,8 @@ func (hf HeaderField) String() string { return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix) } -func (hf *HeaderField) size() uint32 { +// Size returns the size of an entry per RFC 7540 section 5.2. +func (hf HeaderField) Size() uint32 { // http://http2.github.io/http2-spec/compression.html#rfc.section.4.1 // "The size of the dynamic table is the sum of the size of // its entries. The size of an entry is the sum of its name's @@ -171,7 +180,7 @@ func (dt *dynamicTable) setMaxSize(v uint32) { func (dt *dynamicTable) add(f HeaderField) { dt.ents = append(dt.ents, f) - dt.size += f.size() + dt.size += f.Size() dt.evict() } @@ -179,7 +188,7 @@ func (dt *dynamicTable) add(f HeaderField) { func (dt *dynamicTable) evict() { base := dt.ents // keep base pointer of slice for dt.size > dt.maxSize { - dt.size -= dt.ents[0].size() + dt.size -= dt.ents[0].Size() dt.ents = dt.ents[1:] } diff --git a/vendor/golang.org/x/net/http2/hpack/huffman.go b/vendor/golang.org/x/net/http2/hpack/huffman.go index eb4b1f05cd04..8850e3946770 100644 --- a/vendor/golang.org/x/net/http2/hpack/huffman.go +++ b/vendor/golang.org/x/net/http2/hpack/huffman.go @@ -48,12 +48,16 @@ var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data") // maxLen bytes will return ErrStringLength. func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { n := rootHuffmanNode - cur, nbits := uint(0), uint8(0) + // cur is the bit buffer that has not been fed into n. + // cbits is the number of low order bits in cur that are valid. + // sbits is the number of bits of the symbol prefix being decoded. + cur, cbits, sbits := uint(0), uint8(0), uint8(0) for _, b := range v { cur = cur<<8 | uint(b) - nbits += 8 - for nbits >= 8 { - idx := byte(cur >> (nbits - 8)) + cbits += 8 + sbits += 8 + for cbits >= 8 { + idx := byte(cur >> (cbits - 8)) n = n.children[idx] if n == nil { return ErrInvalidHuffman @@ -63,22 +67,40 @@ func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { return ErrStringLength } buf.WriteByte(n.sym) - nbits -= n.codeLen + cbits -= n.codeLen n = rootHuffmanNode + sbits = cbits } else { - nbits -= 8 + cbits -= 8 } } } - for nbits > 0 { - n = n.children[byte(cur<<(8-nbits))] - if n.children != nil || n.codeLen > nbits { + for cbits > 0 { + n = n.children[byte(cur<<(8-cbits))] + if n == nil { + return ErrInvalidHuffman + } + if n.children != nil || n.codeLen > cbits { break } + if maxLen != 0 && buf.Len() == maxLen { + return ErrStringLength + } buf.WriteByte(n.sym) - nbits -= n.codeLen + cbits -= n.codeLen n = rootHuffmanNode + sbits = cbits + } + if sbits > 7 { + // Either there was an incomplete symbol, or overlong padding. + // Both are decoding errors per RFC 7541 section 5.2. + return ErrInvalidHuffman } + if mask := uint(1<= len(isTokenTable) || ('A' <= r && r <= 'Z') { - return false - } - if !isTokenTable[byte(r)] { + if !httplex.IsTokenRune(r) { return false } - } - return true -} - -// validHeaderFieldValue reports whether v is a valid header field value. -// -// RFC 7230 says: -// field-value = *( field-content / obs-fold ) -// obj-fold = N/A to http2, and deprecated -// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] -// field-vchar = VCHAR / obs-text -// obs-text = %x80-FF -// VCHAR = "any visible [USASCII] character" -// -// http2 further says: "Similarly, HTTP/2 allows header field values -// that are not valid. While most of the values that can be encoded -// will not alter header field parsing, carriage return (CR, ASCII -// 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII -// 0x0) might be exploited by an attacker if they are translated -// verbatim. Any request or response that contains a character not -// permitted in a header field value MUST be treated as malformed -// (Section 8.1.2.6). Valid characters are defined by the -// field-content ABNF rule in Section 3.2 of [RFC7230]." -// -// This function does not (yet?) properly handle the rejection of -// strings that begin or end with SP or HTAB. -func validHeaderFieldValue(v string) bool { - for i := 0; i < len(v); i++ { - if b := v[i]; b < ' ' && b != '\t' || b == 0x7f { + if 'A' <= r && r <= 'Z' { return false } } @@ -320,7 +289,7 @@ func mustUint31(v int32) uint32 { } // bodyAllowedForStatus reports whether a given response status code -// permits a body. See RFC2616, section 4.4. +// permits a body. See RFC 2616, section 4.4. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: @@ -344,86 +313,39 @@ func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} -var isTokenTable = [127]bool{ - '!': true, - '#': true, - '$': true, - '%': true, - '&': true, - '\'': true, - '*': true, - '+': true, - '-': true, - '.': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'W': true, - 'V': true, - 'X': true, - 'Y': true, - 'Z': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '|': true, - '~': true, -} - type connectionStater interface { ConnectionState() tls.ConnectionState } + +var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} + +type sorter struct { + v []string // owned by sorter +} + +func (s *sorter) Len() int { return len(s.v) } +func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } +func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } + +// Keys returns the sorted keys of h. +// +// The returned slice is only valid until s used again or returned to +// its pool. +func (s *sorter) Keys(h http.Header) []string { + keys := s.v[:0] + for k := range h { + keys = append(keys, k) + } + s.v = keys + sort.Sort(s) + return keys +} + +func (s *sorter) SortStrings(ss []string) { + // Our sorter works on s.v, which sorter owners, so + // stash it away while we sort the user's buffer. + save := s.v + s.v = ss + sort.Sort(s) + s.v = save +} diff --git a/vendor/golang.org/x/net/http2/not_go15.go b/vendor/golang.org/x/net/http2/not_go15.go deleted file mode 100644 index d0fa5c890691..000000000000 --- a/vendor/golang.org/x/net/http2/not_go15.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package http2 - -import "net/http" - -func requestCancel(req *http.Request) <-chan struct{} { return nil } diff --git a/vendor/golang.org/x/net/http2/not_go16.go b/vendor/golang.org/x/net/http2/not_go16.go index db53c5b8cbfc..efd2e1282cf6 100644 --- a/vendor/golang.org/x/net/http2/not_go16.go +++ b/vendor/golang.org/x/net/http2/not_go16.go @@ -6,8 +6,41 @@ package http2 -import "net/http" +import ( + "crypto/tls" + "net/http" + "time" +) func configureTransport(t1 *http.Transport) (*Transport, error) { return nil, errTransportVersion } + +func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { + return 0 + +} + +// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. +func isBadCipher(cipher uint16) bool { + switch cipher { + case tls.TLS_RSA_WITH_RC4_128_SHA, + tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, + tls.TLS_RSA_WITH_AES_128_CBC_SHA, + tls.TLS_RSA_WITH_AES_256_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, + tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: + // Reject cipher suites from Appendix A. + // "This list includes those cipher suites that do not + // offer an ephemeral key exchange and those that are + // based on the TLS null, stream or block cipher type" + return true + default: + return false + } +} diff --git a/vendor/golang.org/x/net/http2/not_go17.go b/vendor/golang.org/x/net/http2/not_go17.go new file mode 100644 index 000000000000..28df0c16bf00 --- /dev/null +++ b/vendor/golang.org/x/net/http2/not_go17.go @@ -0,0 +1,51 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.7 + +package http2 + +import ( + "net" + "net/http" +) + +type contextContext interface{} + +type fakeContext struct{} + +func (fakeContext) Done() <-chan struct{} { return nil } +func (fakeContext) Err() error { panic("should not be called") } + +func reqContext(r *http.Request) fakeContext { + return fakeContext{} +} + +func setResponseUncompressed(res *http.Response) { + // Nothing. +} + +type clientTrace struct{} + +func requestTrace(*http.Request) *clientTrace { return nil } +func traceGotConn(*http.Request, *ClientConn) {} +func traceFirstResponseByte(*clientTrace) {} +func traceWroteHeaders(*clientTrace) {} +func traceWroteRequest(*clientTrace, error) {} +func traceGot100Continue(trace *clientTrace) {} +func traceWait100Continue(trace *clientTrace) {} + +func nop() {} + +func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { + return nil, nop +} + +func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { + return ctx, nop +} + +func requestWithContext(req *http.Request, ctx contextContext) *http.Request { + return req +} diff --git a/vendor/golang.org/x/net/http2/pipe.go b/vendor/golang.org/x/net/http2/pipe.go index 69446e7a3701..53b7a1daf630 100644 --- a/vendor/golang.org/x/net/http2/pipe.go +++ b/vendor/golang.org/x/net/http2/pipe.go @@ -29,6 +29,12 @@ type pipeBuffer interface { io.Reader } +func (p *pipe) Len() int { + p.mu.Lock() + defer p.mu.Unlock() + return p.b.Len() +} + // Read waits until data is available and copies bytes // from the buffer into p. func (p *pipe) Read(d []byte) (n int, err error) { diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index 6f4c2bb7cd9c..f368738f7c76 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -51,7 +51,6 @@ import ( "os" "reflect" "runtime" - "sort" "strconv" "strings" "sync" @@ -251,10 +250,14 @@ func (o *ServeConnOpts) handler() http.Handler { // // The opts parameter is optional. If nil, default values are used. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { + baseCtx, cancel := serverConnBaseContext(c, opts) + defer cancel() + sc := &serverConn{ srv: s, hs: opts.baseConfig(), conn: c, + baseCtx: baseCtx, remoteAddrStr: c.RemoteAddr().String(), bw: newBufferedWriter(c), handler: opts.handler(), @@ -273,13 +276,14 @@ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { serveG: newGoroutineLock(), pushEnabled: true, } + sc.flow.add(initialWindowSize) sc.inflow.add(initialWindowSize) sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) - sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, nil) - sc.hpackDecoder.SetMaxStringLength(sc.maxHeaderStringLen()) fr := NewFramer(sc.bw, c) + fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) + fr.MaxHeaderListSize = sc.maxHeaderListSize() fr.SetMaxReadFrameSize(s.maxReadFrameSize()) sc.framer = fr @@ -335,30 +339,6 @@ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { sc.serve() } -// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. -func isBadCipher(cipher uint16) bool { - switch cipher { - case tls.TLS_RSA_WITH_RC4_128_SHA, - tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: - // Reject cipher suites from Appendix A. - // "This list includes those cipher suites that do not - // offer an ephemeral key exchange and those that are - // based on the TLS null, stream or block cipher type" - return true - default: - return false - } -} - func (sc *serverConn) rejectConn(err ErrCode, debug string) { sc.vlogf("http2: server rejecting conn: %v, %s", err, debug) // ignoring errors. hanging up anyway. @@ -374,8 +354,8 @@ type serverConn struct { conn net.Conn bw *bufferedWriter // writing to conn handler http.Handler + baseCtx contextContext framer *Framer - hpackDecoder *hpack.Decoder doneServing chan struct{} // closed when serverConn.serve ends readFrameCh chan readFrameResult // written by serverConn.readFrames wantWriteFrameCh chan frameWriteMsg // from handlers -> serve @@ -402,7 +382,6 @@ type serverConn struct { headerTableSize uint32 peerMaxHeaderListSize uint32 // zero means unknown (default) canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case - req requestParam // non-zero while reading request headers writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh needsFrameFlush bool // last frame write wasn't a flush writeSched writeScheduler @@ -411,22 +390,13 @@ type serverConn struct { goAwayCode ErrCode shutdownTimerCh <-chan time.Time // nil until used shutdownTimer *time.Timer // nil until used + freeRequestBodyBuf []byte // if non-nil, a free initialWindowSize buffer for getRequestBodyBuf // Owned by the writeFrameAsync goroutine: headerWriteBuf bytes.Buffer hpackEncoder *hpack.Encoder } -func (sc *serverConn) maxHeaderStringLen() int { - v := sc.maxHeaderListSize() - if uint32(int(v)) == v { - return int(v) - } - // They had a crazy big number for MaxHeaderBytes anyway, - // so give them unlimited header lengths: - return 0 -} - func (sc *serverConn) maxHeaderListSize() uint32 { n := sc.hs.MaxHeaderBytes if n <= 0 { @@ -439,21 +409,6 @@ func (sc *serverConn) maxHeaderListSize() uint32 { return uint32(n + typicalHeaders*perFieldOverhead) } -// requestParam is the state of the next request, initialized over -// potentially several frames HEADERS + zero or more CONTINUATION -// frames. -type requestParam struct { - // stream is non-nil if we're reading (HEADER or CONTINUATION) - // frames for a request (but not DATA). - stream *stream - header http.Header - method, path string - scheme, authority string - sawRegularHeader bool // saw a non-pseudo header already - invalidHeader bool // an invalid header was seen - headerListSize int64 // actually uint32, but easier math this way -} - // stream represents a stream. This is the minimal metadata needed by // the serve goroutine. Most of the actual stream state is owned by // the http.Handler's goroutine in the responseWriter. Because the @@ -463,10 +418,12 @@ type requestParam struct { // responseWriter's state field. type stream struct { // immutable: - sc *serverConn - id uint32 - body *pipe // non-nil if expecting DATA frames - cw closeWaiter // closed wait stream transitions to closed state + sc *serverConn + id uint32 + body *pipe // non-nil if expecting DATA frames + cw closeWaiter // closed wait stream transitions to closed state + ctx contextContext + cancelCtx func() // owned by serverConn's serve loop: bodyBytes int64 // body bytes seen so far @@ -480,6 +437,8 @@ type stream struct { sentReset bool // only true once detached from streams map gotReset bool // only true once detacted from streams map gotTrailerHeader bool // HEADER frame for trailers was seen + wroteHeaders bool // whether we wrote headers (not status 100) + reqBuf []byte trailer http.Header // accumulated trailers reqTrailer http.Header // handler's Request.Trailer @@ -589,87 +548,6 @@ func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { } } -func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) { - sc.serveG.check() - if VerboseLogs { - sc.vlogf("http2: server decoded %v", f) - } - switch { - case !validHeaderFieldValue(f.Value): // f.Name checked _after_ pseudo check, since ':' is invalid - sc.req.invalidHeader = true - case strings.HasPrefix(f.Name, ":"): - if sc.req.sawRegularHeader { - sc.logf("pseudo-header after regular header") - sc.req.invalidHeader = true - return - } - var dst *string - switch f.Name { - case ":method": - dst = &sc.req.method - case ":path": - dst = &sc.req.path - case ":scheme": - dst = &sc.req.scheme - case ":authority": - dst = &sc.req.authority - default: - // 8.1.2.1 Pseudo-Header Fields - // "Endpoints MUST treat a request or response - // that contains undefined or invalid - // pseudo-header fields as malformed (Section - // 8.1.2.6)." - sc.logf("invalid pseudo-header %q", f.Name) - sc.req.invalidHeader = true - return - } - if *dst != "" { - sc.logf("duplicate pseudo-header %q sent", f.Name) - sc.req.invalidHeader = true - return - } - *dst = f.Value - case !validHeaderFieldName(f.Name): - sc.req.invalidHeader = true - default: - sc.req.sawRegularHeader = true - sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value) - const headerFieldOverhead = 32 // per spec - sc.req.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead - if sc.req.headerListSize > int64(sc.maxHeaderListSize()) { - sc.hpackDecoder.SetEmitEnabled(false) - } - } -} - -func (st *stream) onNewTrailerField(f hpack.HeaderField) { - sc := st.sc - sc.serveG.check() - if VerboseLogs { - sc.vlogf("http2: server decoded trailer %v", f) - } - switch { - case strings.HasPrefix(f.Name, ":"): - sc.req.invalidHeader = true - return - case !validHeaderFieldName(f.Name) || !validHeaderFieldValue(f.Value): - sc.req.invalidHeader = true - return - default: - key := sc.canonicalHeader(f.Name) - if st.trailer != nil { - vv := append(st.trailer[key], f.Value) - st.trailer[key] = vv - - // arbitrary; TODO: read spec about header list size limits wrt trailers - const tooBig = 1000 - if len(vv) >= tooBig { - sc.hpackDecoder.SetEmitEnabled(false) - } - } - } -} - func (sc *serverConn) canonicalHeader(v string) string { sc.serveG.check() cv, ok := commonCanonHeader[v] @@ -704,10 +582,11 @@ type readFrameResult struct { // It's run on its own goroutine. func (sc *serverConn) readFrames() { gate := make(gate) + gateDone := gate.Done for { f, err := sc.framer.ReadFrame() select { - case sc.readFrameCh <- readFrameResult{f, err, gate.Done}: + case sc.readFrameCh <- readFrameResult{f, err, gateDone}: case <-sc.doneServing: return } @@ -946,7 +825,23 @@ func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error { // If you're not on the serve goroutine, use writeFrameFromHandler instead. func (sc *serverConn) writeFrame(wm frameWriteMsg) { sc.serveG.check() - sc.writeSched.add(wm) + + var ignoreWrite bool + + // Don't send a 100-continue response if we've already sent headers. + // See golang.org/issue/14030. + switch wm.write.(type) { + case *writeResHeaders: + wm.stream.wroteHeaders = true + case write100ContinueHeadersFrame: + if wm.stream.wroteHeaders { + ignoreWrite = true + } + } + + if !ignoreWrite { + sc.writeSched.add(wm) + } sc.scheduleFrameWrite() } @@ -1183,10 +1078,8 @@ func (sc *serverConn) processFrame(f Frame) error { switch f := f.(type) { case *SettingsFrame: return sc.processSettings(f) - case *HeadersFrame: + case *MetaHeadersFrame: return sc.processHeaders(f) - case *ContinuationFrame: - return sc.processContinuation(f) case *WindowUpdateFrame: return sc.processWindowUpdate(f) case *PingFrame: @@ -1265,6 +1158,7 @@ func (sc *serverConn) processResetStream(f *RSTStreamFrame) error { } if st != nil { st.gotReset = true + st.cancelCtx() sc.closeStream(st, StreamError{f.StreamID, f.ErrCode}) } return nil @@ -1286,6 +1180,18 @@ func (sc *serverConn) closeStream(st *stream, err error) { } st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc sc.writeSched.forgetStream(st.id) + if st.reqBuf != nil { + // Stash this request body buffer (64k) away for reuse + // by a future POST/PUT/etc. + // + // TODO(bradfitz): share on the server? sync.Pool? + // Server requires locks and might hurt contention. + // sync.Pool might work, or might be worse, depending + // on goroutine CPU migrations. (get and put on + // separate CPUs). Maybe a mix of strategies. But + // this is an easy win for now. + sc.freeRequestBodyBuf = st.reqBuf + } } func (sc *serverConn) processSettings(f *SettingsFrame) error { @@ -1442,7 +1348,7 @@ func (st *stream) copyTrailersToHandlerRequest() { } } -func (sc *serverConn) processHeaders(f *HeadersFrame) error { +func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { sc.serveG.check() id := f.Header().StreamID if sc.inGoAway { @@ -1471,17 +1377,18 @@ func (sc *serverConn) processHeaders(f *HeadersFrame) error { // endpoint has opened or reserved. [...] An endpoint that // receives an unexpected stream identifier MUST respond with // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. - if id <= sc.maxStreamID || sc.req.stream != nil { + if id <= sc.maxStreamID { return ConnectionError(ErrCodeProtocol) } + sc.maxStreamID = id - if id > sc.maxStreamID { - sc.maxStreamID = id - } + ctx, cancelCtx := contextWithCancel(sc.baseCtx) st = &stream{ - sc: sc, - id: id, - state: stateOpen, + sc: sc, + id: id, + state: stateOpen, + ctx: ctx, + cancelCtx: cancelCtx, } if f.StreamEnded() { st.state = stateHalfClosedRemote @@ -1501,50 +1408,6 @@ func (sc *serverConn) processHeaders(f *HeadersFrame) error { if sc.curOpenStreams == 1 { sc.setConnState(http.StateActive) } - sc.req = requestParam{ - stream: st, - header: make(http.Header), - } - sc.hpackDecoder.SetEmitFunc(sc.onNewHeaderField) - sc.hpackDecoder.SetEmitEnabled(true) - return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded()) -} - -func (st *stream) processTrailerHeaders(f *HeadersFrame) error { - sc := st.sc - sc.serveG.check() - if st.gotTrailerHeader { - return ConnectionError(ErrCodeProtocol) - } - st.gotTrailerHeader = true - if !f.StreamEnded() { - return StreamError{st.id, ErrCodeProtocol} - } - sc.resetPendingRequest() // we use invalidHeader from it for trailers - return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded()) -} - -func (sc *serverConn) processContinuation(f *ContinuationFrame) error { - sc.serveG.check() - st := sc.streams[f.Header().StreamID] - if st.gotTrailerHeader { - return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded()) - } - return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded()) -} - -func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error { - sc.serveG.check() - if _, err := sc.hpackDecoder.Write(frag); err != nil { - return ConnectionError(ErrCodeCompression) - } - if !end { - return nil - } - if err := sc.hpackDecoder.Close(); err != nil { - return ConnectionError(ErrCodeCompression) - } - defer sc.resetPendingRequest() if sc.curOpenStreams > sc.advMaxStreams { // "Endpoints MUST NOT exceed the limit set by their // peer. An endpoint that receives a HEADERS frame @@ -1564,7 +1427,7 @@ func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bo return StreamError{st.id, ErrCodeRefusedStream} } - rw, req, err := sc.newWriterAndRequest() + rw, req, err := sc.newWriterAndRequest(st, f) if err != nil { return err } @@ -1576,36 +1439,44 @@ func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bo st.declBodyBytes = req.ContentLength handler := sc.handler.ServeHTTP - if !sc.hpackDecoder.EmitEnabled() { + if f.Truncated { // Their header list was too long. Send a 431 error. handler = handleHeaderListTooLong + } else if err := checkValidHTTP2Request(req); err != nil { + handler = new400Handler(err) } go sc.runHandler(rw, req, handler) return nil } -func (st *stream) processTrailerHeaderBlockFragment(frag []byte, end bool) error { +func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error { sc := st.sc sc.serveG.check() - sc.hpackDecoder.SetEmitFunc(st.onNewTrailerField) - if _, err := sc.hpackDecoder.Write(frag); err != nil { - return ConnectionError(ErrCodeCompression) + if st.gotTrailerHeader { + return ConnectionError(ErrCodeProtocol) } - if !end { - return nil + st.gotTrailerHeader = true + if !f.StreamEnded() { + return StreamError{st.id, ErrCodeProtocol} } - rp := &sc.req - if rp.invalidHeader { - return StreamError{rp.stream.id, ErrCodeProtocol} + if len(f.PseudoFields()) > 0 { + return StreamError{st.id, ErrCodeProtocol} } - - err := sc.hpackDecoder.Close() - st.endStream() - if err != nil { - return ConnectionError(ErrCodeCompression) + if st.trailer != nil { + for _, hf := range f.RegularFields() { + key := sc.canonicalHeader(hf.Name) + if !ValidTrailerHeader(key) { + // TODO: send more details to the peer somehow. But http2 has + // no way to send debug data at a stream level. Discuss with + // HTTP folk. + return StreamError{st.id, ErrCodeProtocol} + } + st.trailer[key] = append(st.trailer[key], hf.Value) + } } + st.endStream() return nil } @@ -1650,29 +1521,21 @@ func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority } } -// resetPendingRequest zeros out all state related to a HEADERS frame -// and its zero or more CONTINUATION frames sent to start a new -// request. -func (sc *serverConn) resetPendingRequest() { - sc.serveG.check() - sc.req = requestParam{} -} - -func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) { +func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) { sc.serveG.check() - rp := &sc.req - if rp.invalidHeader { - return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} - } + method := f.PseudoValue("method") + path := f.PseudoValue("path") + scheme := f.PseudoValue("scheme") + authority := f.PseudoValue("authority") - isConnect := rp.method == "CONNECT" + isConnect := method == "CONNECT" if isConnect { - if rp.path != "" || rp.scheme != "" || rp.authority == "" { - return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} + if path != "" || scheme != "" || authority == "" { + return nil, nil, StreamError{f.StreamID, ErrCodeProtocol} } - } else if rp.method == "" || rp.path == "" || - (rp.scheme != "https" && rp.scheme != "http") { + } else if method == "" || path == "" || + (scheme != "https" && scheme != "http") { // See 8.1.2.6 Malformed Requests and Responses: // // Malformed requests or responses that are detected @@ -1683,35 +1546,40 @@ func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, err // "All HTTP/2 requests MUST include exactly one valid // value for the :method, :scheme, and :path // pseudo-header fields" - return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} + return nil, nil, StreamError{f.StreamID, ErrCodeProtocol} } - bodyOpen := rp.stream.state == stateOpen - if rp.method == "HEAD" && bodyOpen { + bodyOpen := !f.StreamEnded() + if method == "HEAD" && bodyOpen { // HEAD requests can't have bodies - return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} + return nil, nil, StreamError{f.StreamID, ErrCodeProtocol} } var tlsState *tls.ConnectionState // nil if not scheme https - if rp.scheme == "https" { + if scheme == "https" { tlsState = sc.tlsState } - authority := rp.authority + + header := make(http.Header) + for _, hf := range f.RegularFields() { + header.Add(sc.canonicalHeader(hf.Name), hf.Value) + } + if authority == "" { - authority = rp.header.Get("Host") + authority = header.Get("Host") } - needsContinue := rp.header.Get("Expect") == "100-continue" + needsContinue := header.Get("Expect") == "100-continue" if needsContinue { - rp.header.Del("Expect") + header.Del("Expect") } // Merge Cookie headers into one "; "-delimited value. - if cookies := rp.header["Cookie"]; len(cookies) > 1 { - rp.header.Set("Cookie", strings.Join(cookies, "; ")) + if cookies := header["Cookie"]; len(cookies) > 1 { + header.Set("Cookie", strings.Join(cookies, "; ")) } // Setup Trailers var trailer http.Header - for _, v := range rp.header["Trailer"] { + for _, v := range header["Trailer"] { for _, key := range strings.Split(v, ",") { key = http.CanonicalHeaderKey(strings.TrimSpace(key)) switch key { @@ -1726,31 +1594,31 @@ func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, err } } } - delete(rp.header, "Trailer") + delete(header, "Trailer") body := &requestBody{ conn: sc, - stream: rp.stream, + stream: st, needsContinue: needsContinue, } var url_ *url.URL var requestURI string if isConnect { - url_ = &url.URL{Host: rp.authority} - requestURI = rp.authority // mimic HTTP/1 server behavior + url_ = &url.URL{Host: authority} + requestURI = authority // mimic HTTP/1 server behavior } else { var err error - url_, err = url.ParseRequestURI(rp.path) + url_, err = url.ParseRequestURI(path) if err != nil { - return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} + return nil, nil, StreamError{f.StreamID, ErrCodeProtocol} } - requestURI = rp.path + requestURI = path } req := &http.Request{ - Method: rp.method, + Method: method, URL: url_, RemoteAddr: sc.remoteAddrStr, - Header: rp.header, + Header: header, RequestURI: requestURI, Proto: "HTTP/2.0", ProtoMajor: 2, @@ -1760,12 +1628,18 @@ func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, err Body: body, Trailer: trailer, } + req = requestWithContext(req, st.ctx) if bodyOpen { + // Disabled, per golang.org/issue/14960: + // st.reqBuf = sc.getRequestBodyBuf() + // TODO: remove this 64k of garbage per request (again, but without a data race): + buf := make([]byte, initialWindowSize) + body.pipe = &pipe{ - b: &fixedBuffer{buf: make([]byte, initialWindowSize)}, // TODO: garbage + b: &fixedBuffer{buf: buf}, } - if vv, ok := rp.header["Content-Length"]; ok { + if vv, ok := header["Content-Length"]; ok { req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64) } else { req.ContentLength = -1 @@ -1778,7 +1652,7 @@ func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, err rws.conn = sc rws.bw = bwSave rws.bw.Reset(chunkWriter{rws}) - rws.stream = rp.stream + rws.stream = st rws.req = req rws.body = body @@ -1786,10 +1660,20 @@ func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, err return rw, req, nil } +func (sc *serverConn) getRequestBodyBuf() []byte { + sc.serveG.check() + if buf := sc.freeRequestBodyBuf; buf != nil { + sc.freeRequestBodyBuf = nil + return buf + } + return make([]byte, initialWindowSize) +} + // Run on its own goroutine. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) { didPanic := true defer func() { + rw.rws.stream.cancelCtx() if didPanic { e := recover() // Same as net/http: @@ -1942,7 +1826,7 @@ type requestBody struct { func (b *requestBody) Close() error { if b.pipe != nil { - b.pipe.CloseWithError(errClosedBody) + b.pipe.BreakWithError(errClosedBody) } b.closed = true return nil @@ -2017,9 +1901,9 @@ func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != // written in the trailers at the end of the response. func (rws *responseWriterState) declareTrailer(k string) { k = http.CanonicalHeaderKey(k) - switch k { - case "Transfer-Encoding", "Content-Length", "Trailer": + if !ValidTrailerHeader(k) { // Forbidden by RFC 2616 14.40. + rws.conn.logf("ignoring invalid trailer %q", k) return } if !strSliceContains(rws.trailers, k) { @@ -2160,7 +2044,12 @@ func (rws *responseWriterState) promoteUndeclaredTrailers() { rws.declareTrailer(trailerKey) rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv } - sort.Strings(rws.trailers) + + if len(rws.trailers) > 1 { + sorter := sorterPool.Get().(*sorter) + sorter.SortStrings(rws.trailers) + sorterPool.Put(sorter) + } } func (w *responseWriter) Flush() { @@ -2306,3 +2195,69 @@ func foreachHeaderElement(v string, fn func(string)) { } } } + +// From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2 +var connHeaders = []string{ + "Connection", + "Keep-Alive", + "Proxy-Connection", + "Transfer-Encoding", + "Upgrade", +} + +// checkValidHTTP2Request checks whether req is a valid HTTP/2 request, +// per RFC 7540 Section 8.1.2.2. +// The returned error is reported to users. +func checkValidHTTP2Request(req *http.Request) error { + for _, h := range connHeaders { + if _, ok := req.Header[h]; ok { + return fmt.Errorf("request header %q is not valid in HTTP/2", h) + } + } + te := req.Header["Te"] + if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) { + return errors.New(`request header "TE" may only be "trailers" in HTTP/2`) + } + return nil +} + +func new400Handler(err error) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + http.Error(w, err.Error(), http.StatusBadRequest) + } +} + +// ValidTrailerHeader reports whether name is a valid header field name to appear +// in trailers. +// See: http://tools.ietf.org/html/rfc7230#section-4.1.2 +func ValidTrailerHeader(name string) bool { + name = http.CanonicalHeaderKey(name) + if strings.HasPrefix(name, "If-") || badTrailer[name] { + return false + } + return true +} + +var badTrailer = map[string]bool{ + "Authorization": true, + "Cache-Control": true, + "Connection": true, + "Content-Encoding": true, + "Content-Length": true, + "Content-Range": true, + "Content-Type": true, + "Expect": true, + "Host": true, + "Keep-Alive": true, + "Max-Forwards": true, + "Pragma": true, + "Proxy-Authenticate": true, + "Proxy-Authorization": true, + "Proxy-Connection": true, + "Range": true, + "Realm": true, + "Te": true, + "Trailer": true, + "Transfer-Encoding": true, + "Www-Authenticate": true, +} diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index c3a1bdb8cb74..fb8dd997b743 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -25,6 +25,7 @@ import ( "time" "golang.org/x/net/http2/hpack" + "golang.org/x/net/lex/httplex" ) const ( @@ -76,6 +77,10 @@ type Transport struct { // uncompressed. DisableCompression bool + // AllowHTTP, if true, permits HTTP/2 requests using the insecure, + // plain-text "http" scheme. Note that this does not enable h2c support. + AllowHTTP bool + // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to // send in the initial settings frame. It is how many bytes // of response headers are allow. Unlike the http2 spec, zero here @@ -134,9 +139,10 @@ func (t *Transport) initConnPool() { // ClientConn is the state of a single HTTP/2 client connection to an // HTTP/2 server. type ClientConn struct { - t *Transport - tconn net.Conn // usually *tls.Conn, except specialized impls - tlsState *tls.ConnectionState // nil only for specialized impls + t *Transport + tconn net.Conn // usually *tls.Conn, except specialized impls + tlsState *tls.ConnectionState // nil only for specialized impls + singleUse bool // whether being used for a single http.Request // readLoop goroutine fields: readerDone chan struct{} // closed on error @@ -148,11 +154,14 @@ type ClientConn struct { inflow flow // peer's conn-level flow control closed bool goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received + goAwayDebug string // goAway frame's debug data, retained as a string streams map[uint32]*clientStream // client-initiated nextStreamID uint32 bw *bufio.Writer br *bufio.Reader fr *Framer + lastActive time.Time + // Settings from peer: maxFrameSize uint32 maxConcurrentStreams uint32 @@ -170,10 +179,12 @@ type ClientConn struct { type clientStream struct { cc *ClientConn req *http.Request + trace *clientTrace // or nil ID uint32 resc chan resAndError bufPipe pipe // buffered pipe with the flow-controlled response payload requestedGzip bool + on100 func() // optional code to run if get a 100 continue response flow flow // guarded by cc.mu inflow flow // guarded by cc.mu @@ -187,36 +198,43 @@ type clientStream struct { done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu // owned by clientConnReadLoop: - pastHeaders bool // got HEADERS w/ END_HEADERS - pastTrailers bool // got second HEADERS frame w/ END_HEADERS + firstByte bool // got the first response byte + pastHeaders bool // got first MetaHeadersFrame (actual headers) + pastTrailers bool // got optional second MetaHeadersFrame (trailers) trailer http.Header // accumulated trailers resTrailer *http.Header // client's Response.Trailer } // awaitRequestCancel runs in its own goroutine and waits for the user -// to either cancel a RoundTrip request (using the provided -// Request.Cancel channel), or for the request to be done (any way it -// might be removed from the cc.streams map: peer reset, successful -// completion, TCP connection breakage, etc) -func (cs *clientStream) awaitRequestCancel(cancel <-chan struct{}) { - if cancel == nil { +// to cancel a RoundTrip request, its context to expire, or for the +// request to be done (any way it might be removed from the cc.streams +// map: peer reset, successful completion, TCP connection breakage, +// etc) +func (cs *clientStream) awaitRequestCancel(req *http.Request) { + ctx := reqContext(req) + if req.Cancel == nil && ctx.Done() == nil { return } select { - case <-cancel: + case <-req.Cancel: cs.bufPipe.CloseWithError(errRequestCanceled) cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) + case <-ctx.Done(): + cs.bufPipe.CloseWithError(ctx.Err()) + cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) case <-cs.done: } } -// checkReset reports any error sent in a RST_STREAM frame by the -// server. -func (cs *clientStream) checkReset() error { +// checkResetOrDone reports any error sent in a RST_STREAM frame by the +// server, or errStreamClosed if the stream is complete. +func (cs *clientStream) checkResetOrDone() error { select { case <-cs.peerReset: return cs.resetErr + case <-cs.done: + return errStreamClosed default: return nil } @@ -264,26 +282,31 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { // authorityAddr returns a given authority (a host/IP, or host:port / ip:port) // and returns a host:port. The port 443 is added if needed. -func authorityAddr(authority string) (addr string) { +func authorityAddr(scheme string, authority string) (addr string) { if _, _, err := net.SplitHostPort(authority); err == nil { return authority } - return net.JoinHostPort(authority, "443") + port := "443" + if scheme == "http" { + port = "80" + } + return net.JoinHostPort(authority, port) } // RoundTripOpt is like RoundTrip, but takes options. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { - if req.URL.Scheme != "https" { + if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { return nil, errors.New("http2: unsupported scheme") } - addr := authorityAddr(req.URL.Host) + addr := authorityAddr(req.URL.Scheme, req.URL.Host) for { cc, err := t.connPool().GetClientConn(req, addr) if err != nil { t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err) return nil, err } + traceGotConn(req, cc) res, err := cc.RoundTrip(req) if shouldRetryRequest(req, err) { continue @@ -300,7 +323,7 @@ func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res // connected from previous requests but are now sitting idle. // It does not interrupt any connections currently in use. func (t *Transport) CloseIdleConnections() { - if cp, ok := t.connPool().(*clientConnPool); ok { + if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok { cp.closeIdleConnections() } } @@ -333,8 +356,12 @@ func (t *Transport) newTLSConfig(host string) *tls.Config { if t.TLSClientConfig != nil { *cfg = *t.TLSClientConfig } - cfg.NextProtos = []string{NextProtoTLS} // TODO: don't override if already in list - cfg.ServerName = host + if !strSliceContains(cfg.NextProtos, NextProtoTLS) { + cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) + } + if cfg.ServerName == "" { + cfg.ServerName = host + } return cfg } @@ -374,6 +401,13 @@ func (t *Transport) disableKeepAlives() bool { return t.t1 != nil && t.t1.DisableKeepAlives } +func (t *Transport) expectContinueTimeout() time.Duration { + if t.t1 == nil { + return 0 + } + return transportExpectContinueTimeout(t.t1) +} + func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { if VerboseLogs { t.vlogf("http2: Transport creating client conn to %v", c.RemoteAddr()) @@ -401,6 +435,8 @@ func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr}) cc.br = bufio.NewReader(c) cc.fr = NewFramer(cc.bw, cc.br) + cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) + cc.fr.MaxHeaderListSize = t.maxHeaderListSize() // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on // henc in response to SETTINGS frames? @@ -412,8 +448,8 @@ func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { } initialSettings := []Setting{ - Setting{ID: SettingEnablePush, Val: 0}, - Setting{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, + {ID: SettingEnablePush, Val: 0}, + {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, } if max := t.maxHeaderListSize(); max != 0 { initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max}) @@ -460,7 +496,17 @@ func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { func (cc *ClientConn) setGoAway(f *GoAwayFrame) { cc.mu.Lock() defer cc.mu.Unlock() + + old := cc.goAway cc.goAway = f + + // Merge the previous and current GoAway error frames. + if cc.goAwayDebug == "" { + cc.goAwayDebug = string(f.DebugData()) + } + if old != nil && old.ErrCode != ErrCodeNo { + cc.goAway.ErrCode = old.ErrCode + } } func (cc *ClientConn) CanTakeNewRequest() bool { @@ -470,6 +516,9 @@ func (cc *ClientConn) CanTakeNewRequest() bool { } func (cc *ClientConn) canTakeNewRequestLocked() bool { + if cc.singleUse && cc.nextStreamID > 1 { + return false + } return cc.goAway == nil && !cc.closed && int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) && cc.nextStreamID < 2147483647 @@ -578,6 +627,33 @@ func checkConnHeaders(req *http.Request) error { return nil } +func bodyAndLength(req *http.Request) (body io.Reader, contentLen int64) { + body = req.Body + if body == nil { + return nil, 0 + } + if req.ContentLength != 0 { + return req.Body, req.ContentLength + } + + // We have a body but a zero content length. Test to see if + // it's actually zero or just unset. + var buf [1]byte + n, rerr := io.ReadFull(body, buf[:]) + if rerr != nil && rerr != io.EOF { + return errorReader{rerr}, -1 + } + if n == 1 { + // Oh, guess there is data in this Body Reader after all. + // The ContentLength field just wasn't set. + // Stich the Body back together again, re-attaching our + // consumed byte. + return io.MultiReader(bytes.NewReader(buf[:]), body), -1 + } + // Body is actually zero bytes. + return nil, 0 +} + func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { if err := checkConnHeaders(req); err != nil { return nil, err @@ -589,39 +665,18 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { } hasTrailers := trailers != "" - var body io.Reader = req.Body - contentLen := req.ContentLength - if req.Body != nil && contentLen == 0 { - // Test to see if it's actually zero or just unset. - var buf [1]byte - n, rerr := io.ReadFull(body, buf[:]) - if rerr != nil && rerr != io.EOF { - contentLen = -1 - body = errorReader{rerr} - } else if n == 1 { - // Oh, guess there is data in this Body Reader after all. - // The ContentLength field just wasn't set. - // Stich the Body back together again, re-attaching our - // consumed byte. - contentLen = -1 - body = io.MultiReader(bytes.NewReader(buf[:]), body) - } else { - // Body is actually empty. - body = nil - } - } + body, contentLen := bodyAndLength(req) + hasBody := body != nil cc.mu.Lock() + cc.lastActive = time.Now() if cc.closed || !cc.canTakeNewRequestLocked() { cc.mu.Unlock() return nil, errClientConnUnusable } - cs := cc.newStream() - cs.req = req - hasBody := body != nil - // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? + var requestedGzip bool if !cc.t.disableCompression() && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" && @@ -638,37 +693,49 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { // We don't request gzip if the request is for a range, since // auto-decoding a portion of a gzipped document will just fail // anyway. See https://golang.org/issue/8923 - cs.requestedGzip = true + requestedGzip = true } // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is // sent by writeRequestBody below, along with any Trailers, // again in form HEADERS{1}, CONTINUATION{0,}) - hdrs := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen) + hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen) + if err != nil { + cc.mu.Unlock() + return nil, err + } + + cs := cc.newStream() + cs.req = req + cs.trace = requestTrace(req) + cs.requestedGzip = requestedGzip + bodyWriter := cc.t.getBodyWriterState(cs, body) + cs.on100 = bodyWriter.on100 + cc.wmu.Lock() endStream := !hasBody && !hasTrailers werr := cc.writeHeaders(cs.ID, endStream, hdrs) cc.wmu.Unlock() + traceWroteHeaders(cs.trace) cc.mu.Unlock() if werr != nil { if hasBody { req.Body.Close() // per RoundTripper contract + bodyWriter.cancel() } cc.forgetStreamID(cs.ID) // Don't bother sending a RST_STREAM (our write already failed; // no need to keep writing) + traceWroteRequest(cs.trace, werr) return nil, werr } var respHeaderTimer <-chan time.Time - var bodyCopyErrc chan error // result of body copy if hasBody { - bodyCopyErrc = make(chan error, 1) - go func() { - bodyCopyErrc <- cs.writeRequestBody(body, req.Body) - }() + bodyWriter.scheduleBodyWrite() } else { + traceWroteRequest(cs.trace, nil) if d := cc.responseHeaderTimeout(); d != 0 { timer := time.NewTimer(d) defer timer.Stop() @@ -677,8 +744,8 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { } readLoopResCh := cs.resc - requestCanceledCh := requestCancel(req) bodyWritten := false + ctx := reqContext(req) for { select { @@ -694,6 +761,7 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { // doesn't, they'll RST_STREAM us soon enough. This is a // heuristic to avoid adding knobs to Transport. Hopefully // we can keep it. + bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWrite) } if re.err != nil { @@ -708,14 +776,25 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { + bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } return nil, errTimeout - case <-requestCanceledCh: + case <-ctx.Done(): + cc.forgetStreamID(cs.ID) + if !hasBody || bodyWritten { + cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) + } else { + bodyWriter.cancel() + cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) + } + return nil, ctx.Err() + case <-req.Cancel: cc.forgetStreamID(cs.ID) if !hasBody || bodyWritten { cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) } else { + bodyWriter.cancel() cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) } return nil, errRequestCanceled @@ -724,7 +803,7 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { // stream from the streams map; no need for // forgetStreamID. return nil, cs.resetErr - case err := <-bodyCopyErrc: + case err := <-bodyWriter.resc: if err != nil { return nil, err } @@ -785,6 +864,7 @@ func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) ( defer cc.putFrameScratchBuffer(buf) defer func() { + traceWroteRequest(cs.trace, err) // TODO: write h12Compare test showing whether // Request.Body is closed by the Transport, // and in multiple cases: server replies <=299 and >299 @@ -881,7 +961,7 @@ func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) if cs.stopReqBody != nil { return 0, cs.stopReqBody } - if err := cs.checkReset(); err != nil { + if err := cs.checkResetOrDone(); err != nil { return 0, err } if a := cs.flow.available(); a > 0 { @@ -908,7 +988,7 @@ type badStringError struct { func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } // requires cc.mu be held. -func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) []byte { +func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { cc.hbuf.Reset() host := req.Host @@ -916,6 +996,20 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail host = req.URL.Host } + // Check for any invalid headers and return an error before we + // potentially pollute our hpack state. (We want to be able to + // continue to reuse the hpack encoder for future requests) + for k, vv := range req.Header { + if !httplex.ValidHeaderFieldName(k) { + return nil, fmt.Errorf("invalid HTTP header name %q", k) + } + for _, v := range vv { + if !httplex.ValidHeaderFieldValue(v) { + return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k) + } + } + } + // 8.1.2.3 Request Pseudo-Header Fields // The :path pseudo-header field includes the path and query parts of the // target URI (the path-absolute production and optionally a '?' character @@ -939,14 +1033,11 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail // Host is :authority, already sent. // Content-Length is automatic, set below. continue - case "connection", "proxy-connection", "transfer-encoding", "upgrade": + case "connection", "proxy-connection", "transfer-encoding", "upgrade", "keep-alive": // Per 8.1.2.2 Connection-Specific Header // Fields, don't send connection-specific - // fields. We deal with these earlier in - // RoundTrip, deciding whether they're - // error-worthy, but we don't want to mutate - // the user's *Request so at this point, just - // skip over them at this point. + // fields. We have already checked if any + // are error-worthy so just ignore the rest. continue case "user-agent": // Match Go's http1 behavior: at most one @@ -975,7 +1066,7 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail if !didUA { cc.writeHeader("user-agent", defaultUserAgent) } - return cc.hbuf.Bytes() + return cc.hbuf.Bytes(), nil } // shouldSendReqContentLength reports whether the http2.Transport should send @@ -1053,8 +1144,10 @@ func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { defer cc.mu.Unlock() cs := cc.streams[id] if andRemove && cs != nil && !cc.closed { + cc.lastActive = time.Now() delete(cc.streams, id) close(cs.done) + cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } return cs } @@ -1064,15 +1157,6 @@ type clientConnReadLoop struct { cc *ClientConn activeRes map[uint32]*clientStream // keyed by streamID closeWhenIdle bool - - hdec *hpack.Decoder - - // Fields reset on each HEADERS: - nextRes *http.Response - sawRegHeader bool // saw non-pseudo header - reqMalformed error // non-nil once known to be malformed - lastHeaderEndsStream bool - headerListSize int64 // actually uint32, but easier math this way } // readLoop runs in its own goroutine and reads and dispatches frames. @@ -1081,7 +1165,6 @@ func (cc *ClientConn) readLoop() { cc: cc, activeRes: make(map[uint32]*clientStream), } - rl.hdec = hpack.NewDecoder(initialHeaderTableSize, rl.onNewHeaderField) defer rl.cleanup() cc.readerErr = rl.run() @@ -1092,6 +1175,19 @@ func (cc *ClientConn) readLoop() { } } +// GoAwayError is returned by the Transport when the server closes the +// TCP connection after sending a GOAWAY frame. +type GoAwayError struct { + LastStreamID uint32 + ErrCode ErrCode + DebugData string +} + +func (e GoAwayError) Error() string { + return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q", + e.LastStreamID, e.ErrCode, e.DebugData) +} + func (rl *clientConnReadLoop) cleanup() { cc := rl.cc defer cc.tconn.Close() @@ -1102,10 +1198,18 @@ func (rl *clientConnReadLoop) cleanup() { // TODO: also do this if we've written the headers but not // gotten a response yet. err := cc.readerErr + cc.mu.Lock() if err == io.EOF { - err = io.ErrUnexpectedEOF + if cc.goAway != nil { + err = GoAwayError{ + LastStreamID: cc.goAway.LastStreamID, + ErrCode: cc.goAway.ErrCode, + DebugData: cc.goAwayDebug, + } + } else { + err = io.ErrUnexpectedEOF + } } - cc.mu.Lock() for _, cs := range rl.activeRes { cs.bufPipe.CloseWithError(err) } @@ -1123,7 +1227,7 @@ func (rl *clientConnReadLoop) cleanup() { func (rl *clientConnReadLoop) run() error { cc := rl.cc - rl.closeWhenIdle = cc.t.disableKeepAlives() + rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse gotReply := false // ever saw a reply for { f, err := cc.fr.ReadFrame() @@ -1131,8 +1235,10 @@ func (rl *clientConnReadLoop) run() error { cc.vlogf("Transport readFrame error: (%T) %v", err, err) } if se, ok := err.(StreamError); ok { - // TODO: deal with stream errors from the framer. - return se + if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil { + rl.endStreamError(cs, cc.fr.errDetail) + } + continue } else if err != nil { return err } @@ -1142,13 +1248,10 @@ func (rl *clientConnReadLoop) run() error { maybeIdle := false // whether frame might transition us to idle switch f := f.(type) { - case *HeadersFrame: + case *MetaHeadersFrame: err = rl.processHeaders(f) maybeIdle = true gotReply = true - case *ContinuationFrame: - err = rl.processContinuation(f) - maybeIdle = true case *DataFrame: err = rl.processData(f) maybeIdle = true @@ -1178,92 +1281,110 @@ func (rl *clientConnReadLoop) run() error { } } -func (rl *clientConnReadLoop) processHeaders(f *HeadersFrame) error { - rl.sawRegHeader = false - rl.reqMalformed = nil - rl.lastHeaderEndsStream = f.StreamEnded() - rl.headerListSize = 0 - rl.nextRes = &http.Response{ - Proto: "HTTP/2.0", - ProtoMajor: 2, - Header: make(http.Header), - } - rl.hdec.SetEmitEnabled(true) - return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded()) -} - -func (rl *clientConnReadLoop) processContinuation(f *ContinuationFrame) error { - return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded()) -} - -func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID uint32, finalFrag bool) error { +func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { cc := rl.cc - streamEnded := rl.lastHeaderEndsStream - cs := cc.streamByID(streamID, streamEnded && finalFrag) + cs := cc.streamByID(f.StreamID, f.StreamEnded()) if cs == nil { // We'd get here if we canceled a request while the - // server was mid-way through replying with its - // headers. (The case of a CONTINUATION arriving - // without HEADERS would be rejected earlier by the - // Framer). So if this was just something we canceled, - // ignore it. + // server had its response still in flight. So if this + // was just something we canceled, ignore it. return nil } - if cs.pastHeaders { - rl.hdec.SetEmitFunc(func(f hpack.HeaderField) { rl.onNewTrailerField(cs, f) }) - } else { - rl.hdec.SetEmitFunc(rl.onNewHeaderField) - } - _, err := rl.hdec.Write(frag) - if err != nil { - return ConnectionError(ErrCodeCompression) - } - if finalFrag { - if err := rl.hdec.Close(); err != nil { - return ConnectionError(ErrCodeCompression) + if !cs.firstByte { + if cs.trace != nil { + // TODO(bradfitz): move first response byte earlier, + // when we first read the 9 byte header, not waiting + // until all the HEADERS+CONTINUATION frames have been + // merged. This works for now. + traceFirstResponseByte(cs.trace) } + cs.firstByte = true } - - if !finalFrag { - return nil - } - if !cs.pastHeaders { cs.pastHeaders = true } else { - // We're dealing with trailers. (and specifically the - // final frame of headers) - if cs.pastTrailers { - // Too many HEADERS frames for this stream. - return ConnectionError(ErrCodeProtocol) - } - cs.pastTrailers = true - if !streamEnded { - // We expect that any header block fragment - // frame for trailers with END_HEADERS also - // has END_STREAM. - return ConnectionError(ErrCodeProtocol) + return rl.processTrailers(cs, f) + } + + res, err := rl.handleResponse(cs, f) + if err != nil { + if _, ok := err.(ConnectionError); ok { + return err } - rl.endStream(cs) + // Any other error type is a stream error. + cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err) + cs.resc <- resAndError{err: err} + return nil // return nil from process* funcs to keep conn alive + } + if res == nil { + // (nil, nil) special case. See handleResponse docs. return nil } + if res.Body != noBody { + rl.activeRes[cs.ID] = cs + } + cs.resTrailer = &res.Trailer + cs.resc <- resAndError{res: res} + return nil +} - if rl.reqMalformed != nil { - cs.resc <- resAndError{err: rl.reqMalformed} - rl.cc.writeStreamReset(cs.ID, ErrCodeProtocol, rl.reqMalformed) - return nil +// may return error types nil, or ConnectionError. Any other error value +// is a StreamError of type ErrCodeProtocol. The returned error in that case +// is the detail. +// +// As a special case, handleResponse may return (nil, nil) to skip the +// frame (currently only used for 100 expect continue). This special +// case is going away after Issue 13851 is fixed. +func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) { + if f.Truncated { + return nil, errResponseHeaderListSize } - res := rl.nextRes + status := f.PseudoValue("status") + if status == "" { + return nil, errors.New("missing status pseudo header") + } + statusCode, err := strconv.Atoi(status) + if err != nil { + return nil, errors.New("malformed non-numeric status pseudo header") + } - if res.StatusCode == 100 { - // Just skip 100-continue response headers for now. - // TODO: golang.org/issue/13851 for doing it properly. + if statusCode == 100 { + traceGot100Continue(cs.trace) + if cs.on100 != nil { + cs.on100() // forces any write delay timer to fire + } cs.pastHeaders = false // do it all again - return nil + return nil, nil + } + + header := make(http.Header) + res := &http.Response{ + Proto: "HTTP/2.0", + ProtoMajor: 2, + Header: header, + StatusCode: statusCode, + Status: status + " " + http.StatusText(statusCode), + } + for _, hf := range f.RegularFields() { + key := http.CanonicalHeaderKey(hf.Name) + if key == "Trailer" { + t := res.Trailer + if t == nil { + t = make(http.Header) + res.Trailer = t + } + foreachHeaderElement(hf.Value, func(v string) { + t[http.CanonicalHeaderKey(v)] = nil + }) + } else { + header[key] = append(header[key], hf.Value) + } } - if !streamEnded || cs.req.Method == "HEAD" { + streamEnded := f.StreamEnded() + isHead := cs.req.Method == "HEAD" + if !streamEnded || isHead { res.ContentLength = -1 if clens := res.Header["Content-Length"]; len(clens) == 1 { if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil { @@ -1278,27 +1399,52 @@ func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID u } } - if streamEnded { + if streamEnded || isHead { res.Body = noBody - } else { - buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage - cs.bufPipe = pipe{b: buf} - cs.bytesRemain = res.ContentLength - res.Body = transportResponseBody{cs} - go cs.awaitRequestCancel(requestCancel(cs.req)) - - if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" { - res.Header.Del("Content-Encoding") - res.Header.Del("Content-Length") - res.ContentLength = -1 - res.Body = &gzipReader{body: res.Body} - } - rl.activeRes[cs.ID] = cs + return res, nil } - cs.resTrailer = &res.Trailer - cs.resc <- resAndError{res: res} - rl.nextRes = nil // unused now; will be reset next HEADERS frame + buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage + cs.bufPipe = pipe{b: buf} + cs.bytesRemain = res.ContentLength + res.Body = transportResponseBody{cs} + go cs.awaitRequestCancel(cs.req) + + if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" { + res.Header.Del("Content-Encoding") + res.Header.Del("Content-Length") + res.ContentLength = -1 + res.Body = &gzipReader{body: res.Body} + setResponseUncompressed(res) + } + return res, nil +} + +func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error { + if cs.pastTrailers { + // Too many HEADERS frames for this stream. + return ConnectionError(ErrCodeProtocol) + } + cs.pastTrailers = true + if !f.StreamEnded() { + // We expect that any headers for trailers also + // has END_STREAM. + return ConnectionError(ErrCodeProtocol) + } + if len(f.PseudoFields()) > 0 { + // No pseudo header fields are defined for trailers. + // TODO: ConnectionError might be overly harsh? Check. + return ConnectionError(ErrCodeProtocol) + } + + trailer := make(http.Header) + for _, hf := range f.RegularFields() { + key := http.CanonicalHeaderKey(hf.Name) + trailer[key] = append(trailer[key], hf.Value) + } + cs.trailer = trailer + + rl.endStream(cs) return nil } @@ -1349,8 +1495,12 @@ func (b transportResponseBody) Read(p []byte) (n int, err error) { cc.inflow.add(connAdd) } if err == nil { // No need to refresh if the stream is over or failed. - if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh { - streamAdd = transportDefaultStreamFlow - v + // Consider any buffered body data (read from the conn but not + // consumed by the client) when computing flow control for this + // stream. + v := int(cs.inflow.available()) + cs.bufPipe.Len() + if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh { + streamAdd = int32(transportDefaultStreamFlow - v) cs.inflow.add(streamAdd) } } @@ -1416,6 +1566,7 @@ func (rl *clientConnReadLoop) processData(f *DataFrame) error { cc.mu.Unlock() if _, err := cs.bufPipe.Write(data); err != nil { + rl.endStreamError(cs, err) return err } } @@ -1431,11 +1582,14 @@ var errInvalidTrailers = errors.New("http2: invalid trailers") func (rl *clientConnReadLoop) endStream(cs *clientStream) { // TODO: check that any declared content-length matches, like // server.go's (*stream).endStream method. - err := io.EOF - code := cs.copyTrailers - if rl.reqMalformed != nil { - err = rl.reqMalformed - code = nil + rl.endStreamError(cs, nil) +} + +func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { + var code func() + if err == nil { + err = io.EOF + code = cs.copyTrailers } cs.bufPipe.closeWithErrorAndCode(err, code) delete(rl.activeRes, cs.ID) @@ -1528,7 +1682,7 @@ func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { cs.resetErr = err close(cs.peerReset) cs.bufPipe.CloseWithError(err) - cs.cc.cond.Broadcast() // wake up checkReset via clientStream.awaitFlowControl + cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } delete(rl.activeRes, cs.ID) return nil @@ -1574,118 +1728,6 @@ var ( errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers") ) -func (rl *clientConnReadLoop) checkHeaderField(f hpack.HeaderField) bool { - if rl.reqMalformed != nil { - return false - } - - const headerFieldOverhead = 32 // per spec - rl.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead - if max := rl.cc.t.maxHeaderListSize(); max != 0 && rl.headerListSize > int64(max) { - rl.hdec.SetEmitEnabled(false) - rl.reqMalformed = errResponseHeaderListSize - return false - } - - if !validHeaderFieldValue(f.Value) { - rl.reqMalformed = errInvalidHeaderFieldValue - return false - } - - isPseudo := strings.HasPrefix(f.Name, ":") - if isPseudo { - if rl.sawRegHeader { - rl.reqMalformed = errors.New("http2: invalid pseudo header after regular header") - return false - } - } else { - if !validHeaderFieldName(f.Name) { - rl.reqMalformed = errInvalidHeaderFieldName - return false - } - rl.sawRegHeader = true - } - - return true -} - -// onNewHeaderField runs on the readLoop goroutine whenever a new -// hpack header field is decoded. -func (rl *clientConnReadLoop) onNewHeaderField(f hpack.HeaderField) { - cc := rl.cc - if VerboseLogs { - cc.logf("http2: Transport decoded %v", f) - } - - if !rl.checkHeaderField(f) { - return - } - - isPseudo := strings.HasPrefix(f.Name, ":") - if isPseudo { - switch f.Name { - case ":status": - code, err := strconv.Atoi(f.Value) - if err != nil { - rl.reqMalformed = errors.New("http2: invalid :status") - return - } - rl.nextRes.Status = f.Value + " " + http.StatusText(code) - rl.nextRes.StatusCode = code - default: - // "Endpoints MUST NOT generate pseudo-header - // fields other than those defined in this - // document." - rl.reqMalformed = fmt.Errorf("http2: unknown response pseudo header %q", f.Name) - } - return - } - - key := http.CanonicalHeaderKey(f.Name) - if key == "Trailer" { - t := rl.nextRes.Trailer - if t == nil { - t = make(http.Header) - rl.nextRes.Trailer = t - } - foreachHeaderElement(f.Value, func(v string) { - t[http.CanonicalHeaderKey(v)] = nil - }) - } else { - rl.nextRes.Header.Add(key, f.Value) - } -} - -func (rl *clientConnReadLoop) onNewTrailerField(cs *clientStream, f hpack.HeaderField) { - if VerboseLogs { - rl.cc.logf("http2: Transport decoded trailer %v", f) - } - if !rl.checkHeaderField(f) { - return - } - if strings.HasPrefix(f.Name, ":") { - // Pseudo-header fields MUST NOT appear in - // trailers. Endpoints MUST treat a request or - // response that contains undefined or invalid - // pseudo-header fields as malformed. - rl.reqMalformed = errPseudoTrailers - return - } - - key := http.CanonicalHeaderKey(f.Name) - - // The spec says one must predeclare their trailers but in practice - // popular users (which is to say the only user we found) do not so we - // violate the spec and accept all of them. - const acceptAllTrailers = true - if _, ok := (*cs.resTrailer)[key]; ok || acceptAllTrailers { - if cs.trailer == nil { - cs.trailer = make(http.Header) - } - cs.trailer[key] = append(cs.trailer[key], f.Value) - } -} - func (cc *ClientConn) logf(format string, args ...interface{}) { cc.t.logf(format, args...) } @@ -1748,3 +1790,79 @@ func (gz *gzipReader) Close() error { type errorReader struct{ err error } func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } + +// bodyWriterState encapsulates various state around the Transport's writing +// of the request body, particularly regarding doing delayed writes of the body +// when the request contains "Expect: 100-continue". +type bodyWriterState struct { + cs *clientStream + timer *time.Timer // if non-nil, we're doing a delayed write + fnonce *sync.Once // to call fn with + fn func() // the code to run in the goroutine, writing the body + resc chan error // result of fn's execution + delay time.Duration // how long we should delay a delayed write for +} + +func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) { + s.cs = cs + if body == nil { + return + } + resc := make(chan error, 1) + s.resc = resc + s.fn = func() { + resc <- cs.writeRequestBody(body, cs.req.Body) + } + s.delay = t.expectContinueTimeout() + if s.delay == 0 || + !httplex.HeaderValuesContainsToken( + cs.req.Header["Expect"], + "100-continue") { + return + } + s.fnonce = new(sync.Once) + + // Arm the timer with a very large duration, which we'll + // intentionally lower later. It has to be large now because + // we need a handle to it before writing the headers, but the + // s.delay value is defined to not start until after the + // request headers were written. + const hugeDuration = 365 * 24 * time.Hour + s.timer = time.AfterFunc(hugeDuration, func() { + s.fnonce.Do(s.fn) + }) + return +} + +func (s bodyWriterState) cancel() { + if s.timer != nil { + s.timer.Stop() + } +} + +func (s bodyWriterState) on100() { + if s.timer == nil { + // If we didn't do a delayed write, ignore the server's + // bogus 100 continue response. + return + } + s.timer.Stop() + go func() { s.fnonce.Do(s.fn) }() +} + +// scheduleBodyWrite starts writing the body, either immediately (in +// the common case) or after the delay timeout. It should not be +// called until after the headers have been written. +func (s bodyWriterState) scheduleBodyWrite() { + if s.timer == nil { + // We're not doing a delayed write (see + // getBodyWriterState), so just start the writing + // goroutine immediately. + go s.fn() + return + } + traceWait100Continue(s.cs.trace) + if s.timer.Stop() { + s.timer.Reset(s.delay) + } +} diff --git a/vendor/golang.org/x/net/http2/write.go b/vendor/golang.org/x/net/http2/write.go index 5297a4bfe3d0..27ef0dd4d728 100644 --- a/vendor/golang.org/x/net/http2/write.go +++ b/vendor/golang.org/x/net/http2/write.go @@ -9,10 +9,10 @@ import ( "fmt" "log" "net/http" - "sort" "time" "golang.org/x/net/http2/hpack" + "golang.org/x/net/lex/httplex" ) // writeFramer is implemented by any type that is used to write frames. @@ -230,25 +230,26 @@ func (wu writeWindowUpdate) writeFrame(ctx writeContext) error { } func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) { - // TODO: garbage. pool sorters like http1? hot path for 1 key? if keys == nil { - keys = make([]string, 0, len(h)) - for k := range h { - keys = append(keys, k) - } - sort.Strings(keys) + sorter := sorterPool.Get().(*sorter) + // Using defer here, since the returned keys from the + // sorter.Keys method is only valid until the sorter + // is returned: + defer sorterPool.Put(sorter) + keys = sorter.Keys(h) } for _, k := range keys { vv := h[k] k = lowerHeader(k) - if !validHeaderFieldName(k) { - // TODO: return an error? golang.org/issue/14048 - // For now just omit it. + if !validWireHeaderFieldName(k) { + // Skip it as backup paranoia. Per + // golang.org/issue/14048, these should + // already be rejected at a higher level. continue } isTE := k == "transfer-encoding" for _, v := range vv { - if !validHeaderFieldValue(v) { + if !httplex.ValidHeaderFieldValue(v) { // TODO: return an error? golang.org/issue/14048 // For now just omit it. continue diff --git a/vendor/golang.org/x/net/lex/httplex/httplex.go b/vendor/golang.org/x/net/lex/httplex/httplex.go new file mode 100644 index 000000000000..bd0ec24f4443 --- /dev/null +++ b/vendor/golang.org/x/net/lex/httplex/httplex.go @@ -0,0 +1,312 @@ +// Copyright 2016 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 httplex contains rules around lexical matters of various +// HTTP-related specifications. +// +// This package is shared by the standard library (which vendors it) +// and x/net/http2. It comes with no API stability promise. +package httplex + +import ( + "strings" + "unicode/utf8" +) + +var isTokenTable = [127]bool{ + '!': true, + '#': true, + '$': true, + '%': true, + '&': true, + '\'': true, + '*': true, + '+': true, + '-': true, + '.': true, + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + 'A': true, + 'B': true, + 'C': true, + 'D': true, + 'E': true, + 'F': true, + 'G': true, + 'H': true, + 'I': true, + 'J': true, + 'K': true, + 'L': true, + 'M': true, + 'N': true, + 'O': true, + 'P': true, + 'Q': true, + 'R': true, + 'S': true, + 'T': true, + 'U': true, + 'W': true, + 'V': true, + 'X': true, + 'Y': true, + 'Z': true, + '^': true, + '_': true, + '`': true, + 'a': true, + 'b': true, + 'c': true, + 'd': true, + 'e': true, + 'f': true, + 'g': true, + 'h': true, + 'i': true, + 'j': true, + 'k': true, + 'l': true, + 'm': true, + 'n': true, + 'o': true, + 'p': true, + 'q': true, + 'r': true, + 's': true, + 't': true, + 'u': true, + 'v': true, + 'w': true, + 'x': true, + 'y': true, + 'z': true, + '|': true, + '~': true, +} + +func IsTokenRune(r rune) bool { + i := int(r) + return i < len(isTokenTable) && isTokenTable[i] +} + +func isNotToken(r rune) bool { + return !IsTokenRune(r) +} + +// HeaderValuesContainsToken reports whether any string in values +// contains the provided token, ASCII case-insensitively. +func HeaderValuesContainsToken(values []string, token string) bool { + for _, v := range values { + if headerValueContainsToken(v, token) { + return true + } + } + return false +} + +// isOWS reports whether b is an optional whitespace byte, as defined +// by RFC 7230 section 3.2.3. +func isOWS(b byte) bool { return b == ' ' || b == '\t' } + +// trimOWS returns x with all optional whitespace removes from the +// beginning and end. +func trimOWS(x string) string { + // TODO: consider using strings.Trim(x, " \t") instead, + // if and when it's fast enough. See issue 10292. + // But this ASCII-only code will probably always beat UTF-8 + // aware code. + for len(x) > 0 && isOWS(x[0]) { + x = x[1:] + } + for len(x) > 0 && isOWS(x[len(x)-1]) { + x = x[:len(x)-1] + } + return x +} + +// headerValueContainsToken reports whether v (assumed to be a +// 0#element, in the ABNF extension described in RFC 7230 section 7) +// contains token amongst its comma-separated tokens, ASCII +// case-insensitively. +func headerValueContainsToken(v string, token string) bool { + v = trimOWS(v) + if comma := strings.IndexByte(v, ','); comma != -1 { + return tokenEqual(trimOWS(v[:comma]), token) || headerValueContainsToken(v[comma+1:], token) + } + return tokenEqual(v, token) +} + +// lowerASCII returns the ASCII lowercase version of b. +func lowerASCII(b byte) byte { + if 'A' <= b && b <= 'Z' { + return b + ('a' - 'A') + } + return b +} + +// tokenEqual reports whether t1 and t2 are equal, ASCII case-insensitively. +func tokenEqual(t1, t2 string) bool { + if len(t1) != len(t2) { + return false + } + for i, b := range t1 { + if b >= utf8.RuneSelf { + // No UTF-8 or non-ASCII allowed in tokens. + return false + } + if lowerASCII(byte(b)) != lowerASCII(t2[i]) { + return false + } + } + return true +} + +// isLWS reports whether b is linear white space, according +// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 +// LWS = [CRLF] 1*( SP | HT ) +func isLWS(b byte) bool { return b == ' ' || b == '\t' } + +// isCTL reports whether b is a control byte, according +// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 +// CTL = +func isCTL(b byte) bool { + const del = 0x7f // a CTL + return b < ' ' || b == del +} + +// ValidHeaderFieldName reports whether v is a valid HTTP/1.x header name. +// HTTP/2 imposes the additional restriction that uppercase ASCII +// letters are not allowed. +// +// RFC 7230 says: +// header-field = field-name ":" OWS field-value OWS +// field-name = token +// token = 1*tchar +// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / +// "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +func ValidHeaderFieldName(v string) bool { + if len(v) == 0 { + return false + } + for _, r := range v { + if !IsTokenRune(r) { + return false + } + } + return true +} + +// ValidHostHeader reports whether h is a valid host header. +func ValidHostHeader(h string) bool { + // The latest spec is actually this: + // + // http://tools.ietf.org/html/rfc7230#section-5.4 + // Host = uri-host [ ":" port ] + // + // Where uri-host is: + // http://tools.ietf.org/html/rfc3986#section-3.2.2 + // + // But we're going to be much more lenient for now and just + // search for any byte that's not a valid byte in any of those + // expressions. + for i := 0; i < len(h); i++ { + if !validHostByte[h[i]] { + return false + } + } + return true +} + +// See the validHostHeader comment. +var validHostByte = [256]bool{ + '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, + '8': true, '9': true, + + 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, + 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, + 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, + 'y': true, 'z': true, + + 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, + 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, + 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, + 'Y': true, 'Z': true, + + '!': true, // sub-delims + '$': true, // sub-delims + '%': true, // pct-encoded (and used in IPv6 zones) + '&': true, // sub-delims + '(': true, // sub-delims + ')': true, // sub-delims + '*': true, // sub-delims + '+': true, // sub-delims + ',': true, // sub-delims + '-': true, // unreserved + '.': true, // unreserved + ':': true, // IPv6address + Host expression's optional port + ';': true, // sub-delims + '=': true, // sub-delims + '[': true, + '\'': true, // sub-delims + ']': true, + '_': true, // unreserved + '~': true, // unreserved +} + +// ValidHeaderFieldValue reports whether v is a valid "field-value" according to +// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 : +// +// message-header = field-name ":" [ field-value ] +// field-value = *( field-content | LWS ) +// field-content = +// +// http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 : +// +// TEXT = +// LWS = [CRLF] 1*( SP | HT ) +// CTL = +// +// RFC 7230 says: +// field-value = *( field-content / obs-fold ) +// obj-fold = N/A to http2, and deprecated +// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] +// field-vchar = VCHAR / obs-text +// obs-text = %x80-FF +// VCHAR = "any visible [USASCII] character" +// +// http2 further says: "Similarly, HTTP/2 allows header field values +// that are not valid. While most of the values that can be encoded +// will not alter header field parsing, carriage return (CR, ASCII +// 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII +// 0x0) might be exploited by an attacker if they are translated +// verbatim. Any request or response that contains a character not +// permitted in a header field value MUST be treated as malformed +// (Section 8.1.2.6). Valid characters are defined by the +// field-content ABNF rule in Section 3.2 of [RFC7230]." +// +// This function does not (yet?) properly handle the rejection of +// strings that begin or end with SP or HTAB. +func ValidHeaderFieldValue(v string) bool { + for i := 0; i < len(v); i++ { + b := v[i] + if isCTL(b) && !isLWS(b) { + return false + } + } + return true +} diff --git a/vendor/golang.org/x/net/trace/trace.go b/vendor/golang.org/x/net/trace/trace.go index 197402e038f6..877dfb32b6be 100644 --- a/vendor/golang.org/x/net/trace/trace.go +++ b/vendor/golang.org/x/net/trace/trace.go @@ -93,13 +93,17 @@ var DebugUseAfterFinish = false // // AuthRequest may be replaced by a program to customise its authorisation requirements. // -// The default AuthRequest function returns (true, true) iff the request comes from localhost/127.0.0.1/[::1]. +// The default AuthRequest function returns (true, true) if and only if the request +// comes from localhost/127.0.0.1/[::1]. var AuthRequest = func(req *http.Request) (any, sensitive bool) { + // RemoteAddr is commonly in the form "IP" or "IP:port". + // If it is in the form "IP:port", split off the port. host, _, err := net.SplitHostPort(req.RemoteAddr) - switch { - case err != nil: // Badly formed address; fail closed. - return false, false - case host == "localhost" || host == "127.0.0.1" || host == "::1": + if err != nil { + host = req.RemoteAddr + } + switch host { + case "localhost", "127.0.0.1", "::1": return true, true default: return false, false diff --git a/vendor/golang.org/x/net/websocket/hybi.go b/vendor/golang.org/x/net/websocket/hybi.go index 60bbc8418900..8cffdd16c91d 100644 --- a/vendor/golang.org/x/net/websocket/hybi.go +++ b/vendor/golang.org/x/net/websocket/hybi.go @@ -81,9 +81,6 @@ type hybiFrameReader struct { func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { n, err = frame.reader.Read(msg) - if err != nil { - return 0, err - } if frame.header.MaskingKey != nil { for i := 0; i < n; i++ { msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4] diff --git a/vendor/golang.org/x/net/websocket/websocket.go b/vendor/golang.org/x/net/websocket/websocket.go index da0dd964c371..9f9b9a52dafb 100644 --- a/vendor/golang.org/x/net/websocket/websocket.go +++ b/vendor/golang.org/x/net/websocket/websocket.go @@ -144,6 +144,8 @@ type frameHandler interface { } // Conn represents a WebSocket connection. +// +// Multiple goroutines may invoke methods on a Conn simultaneously. type Conn struct { config *Config request *http.Request @@ -207,9 +209,6 @@ func (ws *Conn) Write(msg []byte) (n int, err error) { } n, err = w.Write(msg) w.Close() - if err != nil { - return n, err - } return n, err } diff --git a/vendor/k8s.io/kubernetes/LICENSE b/vendor/k8s.io/kubernetes/LICENSE index 6b4d837a44b0..00b2401109fd 100644 --- a/vendor/k8s.io/kubernetes/LICENSE +++ b/vendor/k8s.io/kubernetes/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2014 The Kubernetes Authors All rights reserved. + Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/options/options.go b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/options/options.go index 4cf8e0555cc3..91fac22b180f 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/options/options.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -65,24 +65,64 @@ func (s *APIServer) AddFlags(fs *pflag.FlagSet) { s.ServerRunOptions.AddFlags(fs) // Note: the weird ""+ in below lines seems to be the only way to get gofmt to // arrange these text blocks sensibly. Grrr. - fs.DurationVar(&s.EventTTL, "event-ttl", s.EventTTL, "Amount of time to retain events. Default 1 hour.") - fs.StringVar(&s.ServiceAccountKeyFile, "service-account-key-file", s.ServiceAccountKeyFile, "File containing PEM-encoded x509 RSA private or public key, used to verify ServiceAccount tokens. If unspecified, --tls-private-key-file is used.") - fs.BoolVar(&s.ServiceAccountLookup, "service-account-lookup", s.ServiceAccountLookup, "If true, validate ServiceAccount tokens exist in etcd as part of authentication.") - fs.StringVar(&s.WebhookTokenAuthnConfigFile, "authentication-token-webhook-config-file", s.WebhookTokenAuthnConfigFile, "File with webhook configuration for token authentication in kubeconfig format. The API server will query the remote service to determine authentication for bearer tokens.") - fs.DurationVar(&s.WebhookTokenAuthnCacheTTL, "authentication-token-webhook-cache-ttl", s.WebhookTokenAuthnCacheTTL, "The duration to cache responses from the webhook token authenticator. Default is 2m") - fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, "If true, allow privileged containers.") - fs.StringVar(&s.SSHUser, "ssh-user", s.SSHUser, "If non-empty, use secure SSH proxy to the nodes, using this user name") - fs.StringVar(&s.SSHKeyfile, "ssh-keyfile", s.SSHKeyfile, "If non-empty, use secure SSH proxy to the nodes, using this user keyfile") - fs.Int64Var(&s.MaxConnectionBytesPerSec, "max-connection-bytes-per-sec", s.MaxConnectionBytesPerSec, "If non-zero, throttle each user connection to this number of bytes/sec. Currently only applies to long-running requests") + + fs.DurationVar(&s.EventTTL, "event-ttl", s.EventTTL, + "Amount of time to retain events. Default is 1h.") + + fs.StringVar(&s.ServiceAccountKeyFile, "service-account-key-file", s.ServiceAccountKeyFile, ""+ + "File containing PEM-encoded x509 RSA private or public key, used to verify "+ + "ServiceAccount tokens. If unspecified, --tls-private-key-file is used.") + + fs.BoolVar(&s.ServiceAccountLookup, "service-account-lookup", s.ServiceAccountLookup, + "If true, validate ServiceAccount tokens exist in etcd as part of authentication.") + + fs.StringVar(&s.WebhookTokenAuthnConfigFile, "authentication-token-webhook-config-file", s.WebhookTokenAuthnConfigFile, ""+ + "File with webhook configuration for token authentication in kubeconfig format. "+ + "The API server will query the remote service to determine authentication for bearer tokens.") + + fs.DurationVar(&s.WebhookTokenAuthnCacheTTL, "authentication-token-webhook-cache-ttl", s.WebhookTokenAuthnCacheTTL, + "The duration to cache responses from the webhook token authenticator. Default is 2m.") + + fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, + "If true, allow privileged containers.") + + fs.StringVar(&s.SSHUser, "ssh-user", s.SSHUser, + "If non-empty, use secure SSH proxy to the nodes, using this user name") + + fs.StringVar(&s.SSHKeyfile, "ssh-keyfile", s.SSHKeyfile, + "If non-empty, use secure SSH proxy to the nodes, using this user keyfile") + + fs.Int64Var(&s.MaxConnectionBytesPerSec, "max-connection-bytes-per-sec", s.MaxConnectionBytesPerSec, ""+ + "If non-zero, throttle each user connection to this number of bytes/sec. "+ + "Currently only applies to long-running requests.") + // Kubelet related flags: - fs.BoolVar(&s.KubeletConfig.EnableHttps, "kubelet-https", s.KubeletConfig.EnableHttps, "Use https for kubelet connections") - fs.UintVar(&s.KubeletConfig.Port, "kubelet-port", s.KubeletConfig.Port, "Kubelet port") - fs.MarkDeprecated("kubelet-port", "kubelet-port is deprecated and will be removed") - fs.DurationVar(&s.KubeletConfig.HTTPTimeout, "kubelet-timeout", s.KubeletConfig.HTTPTimeout, "Timeout for kubelet operations") - fs.StringVar(&s.KubeletConfig.CertFile, "kubelet-client-certificate", s.KubeletConfig.CertFile, "Path to a client cert file for TLS.") - fs.StringVar(&s.KubeletConfig.KeyFile, "kubelet-client-key", s.KubeletConfig.KeyFile, "Path to a client key file for TLS.") - fs.StringVar(&s.KubeletConfig.CAFile, "kubelet-certificate-authority", s.KubeletConfig.CAFile, "Path to a cert. file for the certificate authority.") + fs.BoolVar(&s.KubeletConfig.EnableHttps, "kubelet-https", s.KubeletConfig.EnableHttps, + "Use https for kubelet connections.") + + fs.UintVar(&s.KubeletConfig.Port, "kubelet-port", s.KubeletConfig.Port, + "DEPRECATED: kubelet port.") + fs.MarkDeprecated("kubelet-port", "kubelet-port is deprecated and will be removed.") + + fs.DurationVar(&s.KubeletConfig.HTTPTimeout, "kubelet-timeout", s.KubeletConfig.HTTPTimeout, + "Timeout for kubelet operations.") + + fs.StringVar(&s.KubeletConfig.CertFile, "kubelet-client-certificate", s.KubeletConfig.CertFile, + "Path to a client cert file for TLS.") + + fs.StringVar(&s.KubeletConfig.KeyFile, "kubelet-client-key", s.KubeletConfig.KeyFile, + "Path to a client key file for TLS.") + + fs.StringVar(&s.KubeletConfig.CAFile, "kubelet-certificate-authority", s.KubeletConfig.CAFile, + "Path to a cert file for the certificate authority.") + // TODO: delete this flag as soon as we identify and fix all clients that send malformed updates, like #14126. - fs.BoolVar(&validation.RepairMalformedUpdates, "repair-malformed-updates", validation.RepairMalformedUpdates, "If true, server will do its best to fix the update request to pass the validation, e.g., setting empty UID in update request to its existing value. This flag can be turned off after we fix all the clients that send malformed updates.") - fs.BoolVar(®istry.EnableGarbageCollector, "enable-garbage-collector", false, "Enables the generic garbage collector. MUST be synced with the corresponding flag of the kube-controller-manager.") + fs.BoolVar(&validation.RepairMalformedUpdates, "repair-malformed-updates", validation.RepairMalformedUpdates, ""+ + "If true, server will do its best to fix the update request to pass the validation, "+ + "e.g., setting empty UID in update request to its existing value. This flag can be turned off "+ + "after we fix all the clients that send malformed updates.") + + fs.BoolVar(®istry.EnableGarbageCollector, "enable-garbage-collector", false, ""+ + "Enables the generic garbage collector. MUST be synced with the corresponding flag "+ + "of the kube-controller-manager.") } diff --git a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/plugins.go b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/plugins.go index e8ccd0efbf9e..ef4dda786aea 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/plugins.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/server.go b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/server.go index e479146be16a..78d424fabab0 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/server.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-apiserver/app/server.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import ( "net/url" "strconv" "strings" + "time" "github.com/golang/glog" "github.com/spf13/cobra" @@ -37,10 +38,12 @@ import ( "k8s.io/kubernetes/pkg/apis/autoscaling" "k8s.io/kubernetes/pkg/apis/batch" "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/apiserver" "k8s.io/kubernetes/pkg/apiserver/authenticator" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/cloudprovider" + "k8s.io/kubernetes/pkg/controller/framework/informers" serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount" "k8s.io/kubernetes/pkg/genericapiserver" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" @@ -56,6 +59,7 @@ import ( "k8s.io/kubernetes/pkg/registry/rolebinding" rolebindingetcd "k8s.io/kubernetes/pkg/registry/rolebinding/etcd" "k8s.io/kubernetes/pkg/serviceaccount" + "k8s.io/kubernetes/pkg/util/wait" ) // NewAPIServerCommand creates a *cobra.Command object with default parameters @@ -129,7 +133,7 @@ func Run(s *options.APIServer) error { kubeletClient, err := kubeletclient.NewStaticKubeletClient(&s.KubeletConfig) if err != nil { - glog.Fatalf("Failure to start kubelet client: %v", err) + glog.Fatalf("Failed to start kubelet client: %v", err) } storageGroupsToEncodingVersion, err := s.StorageGroupsToEncodingVersion() @@ -182,7 +186,7 @@ func Run(s *options.APIServer) error { if err != nil { glog.Fatalf("Unable to get serviceaccounts storage: %v", err) } - serviceAccountGetter = serviceaccountcontroller.NewGetterFromStorageInterface(storage) + serviceAccountGetter = serviceaccountcontroller.NewGetterFromStorageInterface(storage, storageFactory.ResourcePrefix(api.Resource("serviceaccounts")), storageFactory.ResourcePrefix(api.Resource("secrets"))) } authenticator, err := authenticator.New(authenticator.AuthenticatorConfig{ @@ -219,11 +223,11 @@ func Run(s *options.APIServer) error { if modeEnabled(apiserver.ModeRBAC) { mustGetRESTOptions := func(resource string) generic.RESTOptions { - s, err := storageFactory.New(api.Resource(resource)) + s, err := storageFactory.New(rbac.Resource(resource)) if err != nil { glog.Fatalf("Unable to get %s storage: %v", resource, err) } - return generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage} + return generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage, ResourcePrefix: storageFactory.ResourcePrefix(rbac.Resource(resource))} } // For initial bootstrapping go directly to etcd to avoid privillege escalation check. @@ -243,7 +247,13 @@ func Run(s *options.APIServer) error { if err != nil { glog.Errorf("Failed to create clientset: %v", err) } - admissionController := admission.NewFromPlugins(client, admissionControlPluginNames, s.AdmissionControlConfigFile) + sharedInformers := informers.NewSharedInformerFactory(client, 10*time.Minute) + pluginInitializer := admission.NewPluginInitializer(sharedInformers) + + admissionController, err := admission.NewFromPlugins(client, admissionControlPluginNames, s.AdmissionControlConfigFile, pluginInitializer) + if err != nil { + glog.Fatalf("Failed to initialize plugins: %v", err) + } genericConfig := genericapiserver.NewConfig(s.ServerRunOptions) // TODO: Move the following to generic api server as well. @@ -278,6 +288,7 @@ func Run(s *options.APIServer) error { return err } + sharedInformers.Start(wait.NeverStop) m.Run(s.ServerRunOptions) return nil } diff --git a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go index 247db27dd8c1..75d11f7052fc 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/controllermanager.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -46,19 +46,20 @@ import ( "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/controller" + certcontroller "k8s.io/kubernetes/pkg/controller/certificates" "k8s.io/kubernetes/pkg/controller/daemon" "k8s.io/kubernetes/pkg/controller/deployment" endpointcontroller "k8s.io/kubernetes/pkg/controller/endpoint" "k8s.io/kubernetes/pkg/controller/framework" "k8s.io/kubernetes/pkg/controller/framework/informers" "k8s.io/kubernetes/pkg/controller/garbagecollector" - "k8s.io/kubernetes/pkg/controller/gc" "k8s.io/kubernetes/pkg/controller/job" namespacecontroller "k8s.io/kubernetes/pkg/controller/namespace" nodecontroller "k8s.io/kubernetes/pkg/controller/node" petset "k8s.io/kubernetes/pkg/controller/petset" "k8s.io/kubernetes/pkg/controller/podautoscaler" "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics" + "k8s.io/kubernetes/pkg/controller/podgc" replicaset "k8s.io/kubernetes/pkg/controller/replicaset" replicationcontroller "k8s.io/kubernetes/pkg/controller/replication" resourcequotacontroller "k8s.io/kubernetes/pkg/controller/resourcequota" @@ -72,7 +73,6 @@ import ( "k8s.io/kubernetes/pkg/serviceaccount" "k8s.io/kubernetes/pkg/util/configz" "k8s.io/kubernetes/pkg/util/crypto" - "k8s.io/kubernetes/pkg/util/flowcontrol" "k8s.io/kubernetes/pkg/util/wait" "github.com/golang/glog" @@ -144,6 +144,7 @@ func Run(s *options.CMServer) error { mux.HandleFunc("/debug/pprof/profile", pprof.Profile) mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) } + configz.InstallHandler(mux) mux.Handle("/metrics", prometheus.Handler()) server := &http.Server{ @@ -216,11 +217,12 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig ResyncPeriod(s), replicationcontroller.BurstReplicas, int(s.LookupCacheSizeForRC), + s.EnableGarbageCollector, ).Run(int(s.ConcurrentRCSyncs), wait.NeverStop) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) if s.TerminatedPodGCThreshold > 0 { - go gc.New(clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "garbage-collector")), ResyncPeriod(s), int(s.TerminatedPodGCThreshold)). + go podgc.New(clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "pod-garbage-collector")), ResyncPeriod(s), int(s.TerminatedPodGCThreshold)). Run(wait.NeverStop) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) } @@ -239,9 +241,9 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig glog.Warningf("Unsuccessful parsing of service CIDR %v: %v", s.ServiceCIDR, err) } nodeController, err := nodecontroller.NewNodeController(cloud, clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "node-controller")), - s.PodEvictionTimeout.Duration, flowcontrol.NewTokenBucketRateLimiter(s.DeletingPodsQps, int(s.DeletingPodsBurst)), - flowcontrol.NewTokenBucketRateLimiter(s.DeletingPodsQps, int(s.DeletingPodsBurst)), - s.NodeMonitorGracePeriod.Duration, s.NodeStartupGracePeriod.Duration, s.NodeMonitorPeriod.Duration, clusterCIDR, serviceCIDR, int(s.NodeCIDRMaskSize), s.AllocateNodeCIDRs) + s.PodEvictionTimeout.Duration, s.DeletingPodsQps, s.NodeMonitorGracePeriod.Duration, + s.NodeStartupGracePeriod.Duration, s.NodeMonitorPeriod.Duration, clusterCIDR, serviceCIDR, + int(s.NodeCIDRMaskSize), s.AllocateNodeCIDRs) if err != nil { glog.Fatalf("Failed to initialize nodecontroller: %v", err) } @@ -264,10 +266,8 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig routeController.Run(s.NodeSyncPeriod.Duration) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) } - } else if s.ConfigureCloudRoutes && !s.AllocateNodeCIDRs { - glog.Warningf("allocate-node-cidrs set to %v, will not configure cloud provider routes.", s.AllocateNodeCIDRs) - } else if s.AllocateNodeCIDRs && !s.ConfigureCloudRoutes { - glog.Infof("configure-cloud-routes is set to %v, will not configure cloud provider routes.", s.ConfigureCloudRoutes) + } else { + glog.Infof("Will not configure cloud provider routes for allocate-node-cidrs: %v, configure-cloud-routes: %v.", s.AllocateNodeCIDRs, s.ConfigureCloudRoutes) } resourceQuotaControllerClient := clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "resourcequota-controller")) @@ -365,7 +365,7 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig if containsResource(resources, "replicasets") { glog.Infof("Starting ReplicaSet controller") - go replicaset.NewReplicaSetController(clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "replicaset-controller")), ResyncPeriod(s), replicaset.BurstReplicas, int(s.LookupCacheSizeForRS)). + go replicaset.NewReplicaSetController(podInformer, clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "replicaset-controller")), ResyncPeriod(s), replicaset.BurstReplicas, int(s.LookupCacheSizeForRS), s.EnableGarbageCollector). Run(int(s.ConcurrentRSSyncs), wait.NeverStop) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) } @@ -391,7 +391,7 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig provisioner, err := NewVolumeProvisioner(cloud, s.VolumeConfiguration) if err != nil { - glog.Fatal("A Provisioner could not be created, but one was expected. Provisioning will not work. This functionality is considered an early Alpha version.") + glog.Fatalf("A Provisioner could not be created: %v, but one was expected. Provisioning will not work. This functionality is considered an early Alpha version.", err) } volumeController := persistentvolumecontroller.NewPersistentVolumeController( @@ -418,9 +418,31 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig ProbeAttachableVolumePlugins(s.VolumeConfiguration)) if attachDetachControllerErr != nil { glog.Fatalf("Failed to start attach/detach controller: %v", attachDetachControllerErr) - } else { - go attachDetachController.Run(wait.NeverStop) - time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) + } + go attachDetachController.Run(wait.NeverStop) + time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) + + groupVersion = "certificates/v1alpha1" + resources, found = resourceMap[groupVersion] + glog.Infof("Attempting to start certificates, full resource map %+v", resourceMap) + if containsVersion(versions, groupVersion) && found { + glog.Infof("Starting %s apis", groupVersion) + if containsResource(resources, "certificatesigningrequests") { + glog.Infof("Starting certificate request controller") + resyncPeriod := ResyncPeriod(s)() + certController, err := certcontroller.NewCertificateController( + clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "certificate-controller")), + resyncPeriod, + s.ClusterSigningCertFile, + s.ClusterSigningKeyFile, + ) + if err != nil { + glog.Errorf("Failed to start certificate controller: %v", err) + } else { + go certController.Run(1, wait.NeverStop) + } + time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) + } } var rootCA []byte @@ -442,13 +464,13 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig if err != nil { glog.Errorf("Error reading key for service account token controller: %v", err) } else { - serviceaccountcontroller.NewTokensController( + go serviceaccountcontroller.NewTokensController( clientset.NewForConfigOrDie(restclient.AddUserAgent(kubeconfig, "tokens-controller")), serviceaccountcontroller.TokensControllerOptions{ TokenGenerator: serviceaccount.JWTTokenGenerator(privateKey), RootCA: rootCA, }, - ).Run() + ).Run(int(s.ConcurrentSATokenSyncs), wait.NeverStop) time.Sleep(wait.Jitter(s.ControllerStartInterval.Duration, ControllerStartJitter)) } } @@ -468,10 +490,9 @@ func StartControllers(s *options.CMServer, kubeClient *client.Client, kubeconfig clientPool := dynamic.NewClientPool(restclient.AddUserAgent(kubeconfig, "generic-garbage-collector"), dynamic.LegacyAPIPathResolverFunc) garbageCollector, err := garbagecollector.NewGarbageCollector(clientPool, groupVersionResources) if err != nil { - glog.Errorf("Failed to start the generic garbage collector") + glog.Errorf("Failed to start the generic garbage collector: %v", err) } else { - // TODO: make this a flag of kube-controller-manager - workers := 5 + workers := int(s.ConcurrentGCSyncs) go garbageCollector.Run(workers, wait.NeverStop) } } diff --git a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/options/options.go b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/options/options.go index b862ba4db9ce..f6463b966e6d 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/options/options.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -53,6 +53,7 @@ func NewCMServer() *CMServer { ConcurrentResourceQuotaSyncs: 5, ConcurrentDeploymentSyncs: 5, ConcurrentNamespaceSyncs: 2, + ConcurrentSATokenSyncs: 5, LookupCacheSizeForRC: 4096, LookupCacheSizeForRS: 4096, LookupCacheSizeForDaemonSet: 1024, @@ -91,8 +92,12 @@ func NewCMServer() *CMServer { LeaderElection: leaderelection.DefaultLeaderElectionConfiguration(), ControllerStartInterval: unversioned.Duration{Duration: 0 * time.Second}, EnableGarbageCollector: false, + ConcurrentGCSyncs: 5, + ClusterSigningCertFile: "/etc/kubernetes/ca/ca.pem", + ClusterSigningKeyFile: "/etc/kubernetes/ca/ca.key", }, } + s.LeaderElection.LeaderElect = true return &s } @@ -108,6 +113,7 @@ func (s *CMServer) AddFlags(fs *pflag.FlagSet) { fs.Int32Var(&s.ConcurrentResourceQuotaSyncs, "concurrent-resource-quota-syncs", s.ConcurrentResourceQuotaSyncs, "The number of resource quotas that are allowed to sync concurrently. Larger number = more responsive quota management, but more CPU (and network) load") fs.Int32Var(&s.ConcurrentDeploymentSyncs, "concurrent-deployment-syncs", s.ConcurrentDeploymentSyncs, "The number of deployment objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load") fs.Int32Var(&s.ConcurrentNamespaceSyncs, "concurrent-namespace-syncs", s.ConcurrentNamespaceSyncs, "The number of namespace objects that are allowed to sync concurrently. Larger number = more responsive namespace termination, but more CPU (and network) load") + fs.Int32Var(&s.ConcurrentSATokenSyncs, "concurrent-serviceaccount-token-syncs", s.ConcurrentSATokenSyncs, "The number of service account token objects that are allowed to sync concurrently. Larger number = more responsive token generation, but more CPU (and network) load") fs.Int32Var(&s.LookupCacheSizeForRC, "replication-controller-lookup-cache-size", s.LookupCacheSizeForRC, "The the size of lookup cache for replication controllers. Larger number = more responsive replica management, but more MEM load.") fs.Int32Var(&s.LookupCacheSizeForRS, "replicaset-lookup-cache-size", s.LookupCacheSizeForRS, "The the size of lookup cache for replicatsets. Larger number = more responsive replica management, but more MEM load.") fs.Int32Var(&s.LookupCacheSizeForDaemonSet, "daemonset-lookup-cache-size", s.LookupCacheSizeForDaemonSet, "The the size of lookup cache for daemonsets. Larger number = more responsive daemonsets, but more MEM load.") @@ -133,19 +139,22 @@ func (s *CMServer) AddFlags(fs *pflag.FlagSet) { fs.DurationVar(&s.DeploymentControllerSyncPeriod.Duration, "deployment-controller-sync-period", s.DeploymentControllerSyncPeriod.Duration, "Period for syncing the deployments.") fs.DurationVar(&s.PodEvictionTimeout.Duration, "pod-eviction-timeout", s.PodEvictionTimeout.Duration, "The grace period for deleting pods on failed nodes.") fs.Float32Var(&s.DeletingPodsQps, "deleting-pods-qps", 0.1, "Number of nodes per second on which pods are deleted in case of node failure.") - fs.Int32Var(&s.DeletingPodsBurst, "deleting-pods-burst", 1, "Number of nodes on which pods are bursty deleted in case of node failure. For more details look into RateLimiter.") + fs.Int32Var(&s.DeletingPodsBurst, "deleting-pods-burst", 0, "Number of nodes on which pods are bursty deleted in case of node failure. For more details look into RateLimiter.") + fs.MarkDeprecated("deleting-pods-burst", "This flag is currently no-op and will be deleted.") fs.Int32Var(&s.RegisterRetryCount, "register-retry-count", s.RegisterRetryCount, ""+ "The number of retries for initial node registration. Retry interval equals node-sync-period.") fs.MarkDeprecated("register-retry-count", "This flag is currently no-op and will be deleted.") fs.DurationVar(&s.NodeMonitorGracePeriod.Duration, "node-monitor-grace-period", s.NodeMonitorGracePeriod.Duration, - "Amount of time which we allow running Node to be unresponsive before marking it unhealty. "+ + "Amount of time which we allow running Node to be unresponsive before marking it unhealthy. "+ "Must be N times more than kubelet's nodeStatusUpdateFrequency, "+ "where N means number of retries allowed for kubelet to post node status.") fs.DurationVar(&s.NodeStartupGracePeriod.Duration, "node-startup-grace-period", s.NodeStartupGracePeriod.Duration, - "Amount of time which we allow starting Node to be unresponsive before marking it unhealty.") + "Amount of time which we allow starting Node to be unresponsive before marking it unhealthy.") fs.DurationVar(&s.NodeMonitorPeriod.Duration, "node-monitor-period", s.NodeMonitorPeriod.Duration, "The period for syncing NodeStatus in NodeController.") fs.StringVar(&s.ServiceAccountKeyFile, "service-account-private-key-file", s.ServiceAccountKeyFile, "Filename containing a PEM-encoded private RSA key used to sign service account tokens.") + fs.StringVar(&s.ClusterSigningCertFile, "cluster-signing-cert-file", s.ClusterSigningCertFile, "Filename containing a PEM-encoded X509 CA certificate used to issue cluster-scoped certificates") + fs.StringVar(&s.ClusterSigningKeyFile, "cluster-signing-key-file", s.ClusterSigningKeyFile, "Filename containing a PEM-encoded RSA or ECDSA private key used to sign cluster-scoped certificates") fs.BoolVar(&s.EnableProfiling, "profiling", true, "Enable profiling via web interface host:port/debug/pprof/") fs.StringVar(&s.ClusterName, "cluster-name", s.ClusterName, "The instance prefix for the cluster") fs.StringVar(&s.ClusterCIDR, "cluster-cidr", s.ClusterCIDR, "CIDR Range for Pods in cluster.") @@ -161,5 +170,6 @@ func (s *CMServer) AddFlags(fs *pflag.FlagSet) { fs.Int32Var(&s.KubeAPIBurst, "kube-api-burst", s.KubeAPIBurst, "Burst to use while talking with kubernetes apiserver") fs.DurationVar(&s.ControllerStartInterval.Duration, "controller-start-interval", s.ControllerStartInterval.Duration, "Interval between starting controller managers.") fs.BoolVar(&s.EnableGarbageCollector, "enable-garbage-collector", s.EnableGarbageCollector, "Enables the generic garbage collector. MUST be synced with the corresponding flag of the kube-apiserver. WARNING: the generic garbage collector is an alpha feature.") + fs.Int32Var(&s.ConcurrentGCSyncs, "concurrent-gc-syncs", s.ConcurrentGCSyncs, "The number of garbage collector workers that are allowed to sync concurrently.") leaderelection.BindFlags(&s.LeaderElection, fs) } diff --git a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/plugins.go b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/plugins.go index 6b11dd382265..8ea23ecca2ac 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/plugins.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-controller-manager/app/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/conntrack.go b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/conntrack.go index d61656ee2d1d..001d99111932 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/conntrack.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/conntrack.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go index fd9de2d9fdf3..0f492cd9f673 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/server.go b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/server.go index 50b39bb9e3ea..f618c209fd57 100644 --- a/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/server.go +++ b/vendor/k8s.io/kubernetes/cmd/kube-proxy/app/server.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/options/options.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/options/options.go index 8911addcb7c4..808734c6f4dc 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/options/options.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,39 +19,16 @@ package options import ( _ "net/http/pprof" - "path/filepath" - "runtime" - "time" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/componentconfig" - "k8s.io/kubernetes/pkg/kubelet/qos" - "k8s.io/kubernetes/pkg/kubelet/rkt" - kubetypes "k8s.io/kubernetes/pkg/kubelet/types" - "k8s.io/kubernetes/pkg/master/ports" + "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" "k8s.io/kubernetes/pkg/util" - "k8s.io/kubernetes/pkg/util/config" + utilconfig "k8s.io/kubernetes/pkg/util/config" "github.com/spf13/pflag" ) -const ( - defaultRootDir = "/var/lib/kubelet" - experimentalFlannelOverlay = false - - // When these values are updated, also update test/e2e/framework/util.go - defaultPodInfraContainerImageName = "gcr.io/google_containers/pause" - defaultPodInfraContainerImageVersion = "3.0" - // Auto detect cloud provider. - AutoDetectCloudProvider = "auto-detect" -) - -// Returns the arch-specific pause image that kubelet should use as the default -func GetDefaultPodInfraContainerImage() string { - return defaultPodInfraContainerImageName + "-" + runtime.GOARCH + ":" + defaultPodInfraContainerImageVersion -} - // KubeletServer encapsulates all of the parameters necessary for starting up // a kubelet. These can either be set via command line or directly. type KubeletServer struct { @@ -67,93 +44,16 @@ type KubeletServer struct { ChaosChance float64 // Crash immediately, rather than eating panics. ReallyCrashForTesting bool - SystemReserved config.ConfigurationMap - KubeReserved config.ConfigurationMap } // NewKubeletServer will create a new KubeletServer with default values. func NewKubeletServer() *KubeletServer { + config := componentconfig.KubeletConfiguration{} + api.Scheme.Convert(&v1alpha1.KubeletConfiguration{}, &config) return &KubeletServer{ - AuthPath: util.NewStringFlag("/var/lib/kubelet/kubernetes_auth"), // deprecated - KubeConfig: util.NewStringFlag("/var/lib/kubelet/kubeconfig"), - - SystemReserved: make(config.ConfigurationMap), - KubeReserved: make(config.ConfigurationMap), - KubeletConfiguration: componentconfig.KubeletConfiguration{ - Address: "0.0.0.0", - CAdvisorPort: 4194, - VolumeStatsAggPeriod: unversioned.Duration{Duration: time.Minute}, - CertDirectory: "/var/run/kubernetes", - CgroupRoot: "", - CloudProvider: AutoDetectCloudProvider, - ConfigureCBR0: false, - ContainerRuntime: "docker", - RuntimeRequestTimeout: unversioned.Duration{Duration: 2 * time.Minute}, - CPUCFSQuota: true, - DockerExecHandlerName: "native", - EventBurst: 10, - EventRecordQPS: 5.0, - EnableControllerAttachDetach: true, - EnableCustomMetrics: false, - EnableDebuggingHandlers: true, - EnableServer: true, - FileCheckFrequency: unversioned.Duration{Duration: 20 * time.Second}, - HealthzBindAddress: "127.0.0.1", - HealthzPort: 10248, - HostNetworkSources: kubetypes.AllSource, - HostPIDSources: kubetypes.AllSource, - HostIPCSources: kubetypes.AllSource, - HTTPCheckFrequency: unversioned.Duration{Duration: 20 * time.Second}, - ImageMinimumGCAge: unversioned.Duration{Duration: 2 * time.Minute}, - ImageGCHighThresholdPercent: 90, - ImageGCLowThresholdPercent: 80, - LowDiskSpaceThresholdMB: 256, - MasterServiceNamespace: api.NamespaceDefault, - MaxContainerCount: 240, - MaxPerPodContainerCount: 2, - MaxOpenFiles: 1000000, - MaxPods: 110, - NvidiaGPUs: 0, - MinimumGCAge: unversioned.Duration{Duration: 1 * time.Minute}, - NetworkPluginDir: "/usr/libexec/kubernetes/kubelet-plugins/net/exec/", - NetworkPluginName: "", - NonMasqueradeCIDR: "10.0.0.0/8", - VolumePluginDir: "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/", - NodeStatusUpdateFrequency: unversioned.Duration{Duration: 10 * time.Second}, - NodeLabels: make(map[string]string), - OOMScoreAdj: int32(qos.KubeletOOMScoreAdj), - LockFilePath: "", - ExitOnLockContention: false, - PodInfraContainerImage: GetDefaultPodInfraContainerImage(), - Port: ports.KubeletPort, - ReadOnlyPort: ports.KubeletReadOnlyPort, - RegisterNode: true, // will be ignored if no apiserver is configured - RegisterSchedulable: true, - RegistryBurst: 10, - RegistryPullQPS: 5.0, - KubeletCgroups: "", - ResolverConfig: kubetypes.ResolvConfDefault, - RktPath: "", - RktAPIEndpoint: rkt.DefaultRktAPIServiceEndpoint, - RktStage1Image: "", - RootDirectory: defaultRootDir, - RuntimeCgroups: "", - SerializeImagePulls: true, - SeccompProfileRoot: filepath.Join(defaultRootDir, "seccomp"), - StreamingConnectionIdleTimeout: unversioned.Duration{Duration: 4 * time.Hour}, - SyncFrequency: unversioned.Duration{Duration: 1 * time.Minute}, - SystemCgroups: "", - ReconcileCIDR: true, - ContentType: "application/vnd.kubernetes.protobuf", - KubeAPIQPS: 5.0, - KubeAPIBurst: 10, - ExperimentalFlannelOverlay: experimentalFlannelOverlay, - OutOfDiskTransitionFrequency: unversioned.Duration{Duration: 5 * time.Minute}, - HairpinMode: componentconfig.PromiscuousBridge, - BabysitDaemons: false, - EvictionPressureTransitionPeriod: unversioned.Duration{Duration: 5 * time.Minute}, - PodsPerCore: 0, - }, + AuthPath: util.NewStringFlag("/var/lib/kubelet/kubernetes_auth"), // deprecated + KubeConfig: util.NewStringFlag("/var/lib/kubelet/kubeconfig"), + KubeletConfiguration: config, } } @@ -167,8 +67,8 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.ManifestURLHeader, "manifest-url-header", s.ManifestURLHeader, "HTTP header to use when accessing the manifest URL, with the key separated from the value with a ':', as in 'key:value'") fs.BoolVar(&s.EnableServer, "enable-server", s.EnableServer, "Enable the Kubelet's server") fs.Var(componentconfig.IPVar{Val: &s.Address}, "address", "The IP address for the Kubelet to serve on (set to 0.0.0.0 for all interfaces)") - fs.UintVar(&s.Port, "port", s.Port, "The port for the Kubelet to serve on.") - fs.UintVar(&s.ReadOnlyPort, "read-only-port", s.ReadOnlyPort, "The read-only port for the Kubelet to serve on with no authentication/authorization (set to 0 to disable)") + fs.Int32Var(&s.Port, "port", s.Port, "The port for the Kubelet to serve on.") + fs.Int32Var(&s.ReadOnlyPort, "read-only-port", s.ReadOnlyPort, "The read-only port for the Kubelet to serve on with no authentication/authorization (set to 0 to disable)") fs.StringVar(&s.TLSCertFile, "tls-cert-file", s.TLSCertFile, ""+ "File containing x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). "+ "If --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key "+ @@ -178,26 +78,29 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { "If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.") fs.StringVar(&s.HostnameOverride, "hostname-override", s.HostnameOverride, "If non-empty, will use this string as identification instead of the actual hostname.") fs.StringVar(&s.PodInfraContainerImage, "pod-infra-container-image", s.PodInfraContainerImage, "The image whose network/ipc namespaces containers in each pod will use.") - fs.StringVar(&s.DockerEndpoint, "docker-endpoint", s.DockerEndpoint, "If non-empty, use this for the docker endpoint to communicate with") + fs.StringVar(&s.DockerEndpoint, "docker-endpoint", s.DockerEndpoint, "Use this for the docker endpoint to communicate with") fs.StringVar(&s.RootDirectory, "root-dir", s.RootDirectory, "Directory path for managing kubelet files (volume mounts,etc).") fs.StringVar(&s.SeccompProfileRoot, "seccomp-profile-root", s.SeccompProfileRoot, "Directory path for seccomp profiles.") fs.BoolVar(&s.AllowPrivileged, "allow-privileged", s.AllowPrivileged, "If true, allow containers to request privileged mode. [default=false]") - fs.StringVar(&s.HostNetworkSources, "host-network-sources", s.HostNetworkSources, "Comma-separated list of sources from which the Kubelet allows pods to use of host network. [default=\"*\"]") - fs.StringVar(&s.HostPIDSources, "host-pid-sources", s.HostPIDSources, "Comma-separated list of sources from which the Kubelet allows pods to use the host pid namespace. [default=\"*\"]") - fs.StringVar(&s.HostIPCSources, "host-ipc-sources", s.HostIPCSources, "Comma-separated list of sources from which the Kubelet allows pods to use the host ipc namespace. [default=\"*\"]") - fs.Float64Var(&s.RegistryPullQPS, "registry-qps", s.RegistryPullQPS, "If > 0, limit registry pull QPS to this value. If 0, unlimited. [default=5.0]") + fs.StringSliceVar(&s.HostNetworkSources, "host-network-sources", s.HostNetworkSources, "Comma-separated list of sources from which the Kubelet allows pods to use of host network. [default=\"*\"]") + fs.StringSliceVar(&s.HostPIDSources, "host-pid-sources", s.HostPIDSources, "Comma-separated list of sources from which the Kubelet allows pods to use the host pid namespace. [default=\"*\"]") + fs.StringSliceVar(&s.HostIPCSources, "host-ipc-sources", s.HostIPCSources, "Comma-separated list of sources from which the Kubelet allows pods to use the host ipc namespace. [default=\"*\"]") + fs.Int32Var(&s.RegistryPullQPS, "registry-qps", s.RegistryPullQPS, "If > 0, limit registry pull QPS to this value. If 0, unlimited. [default=5.0]") fs.Int32Var(&s.RegistryBurst, "registry-burst", s.RegistryBurst, "Maximum size of a bursty pulls, temporarily allows pulls to burst to this number, while still not exceeding registry-qps. Only used if --registry-qps > 0") - fs.Float32Var(&s.EventRecordQPS, "event-qps", s.EventRecordQPS, "If > 0, limit event creations per second to this value. If 0, unlimited.") + fs.Int32Var(&s.EventRecordQPS, "event-qps", s.EventRecordQPS, "If > 0, limit event creations per second to this value. If 0, unlimited.") fs.Int32Var(&s.EventBurst, "event-burst", s.EventBurst, "Maximum size of a bursty event records, temporarily allows event records to burst to this number, while still not exceeding event-qps. Only used if --event-qps > 0") fs.BoolVar(&s.RunOnce, "runonce", s.RunOnce, "If true, exit after spawning pods from local manifests or remote urls. Exclusive with --api-servers, and --enable-server") fs.BoolVar(&s.EnableDebuggingHandlers, "enable-debugging-handlers", s.EnableDebuggingHandlers, "Enables server endpoints for log collection and local running of containers and commands") fs.DurationVar(&s.MinimumGCAge.Duration, "minimum-container-ttl-duration", s.MinimumGCAge.Duration, "Minimum age for a finished container before it is garbage collected. Examples: '300ms', '10s' or '2h45m'") + fs.MarkDeprecated("minimum-container-ttl-duration", "Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.") fs.Int32Var(&s.MaxPerPodContainerCount, "maximum-dead-containers-per-container", s.MaxPerPodContainerCount, "Maximum number of old instances to retain per container. Each container takes up some disk space. Default: 2.") + fs.MarkDeprecated("maximum-dead-containers-per-container", "Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.") fs.Int32Var(&s.MaxContainerCount, "maximum-dead-containers", s.MaxContainerCount, "Maximum number of old instances of containers to retain globally. Each container takes up some disk space. Default: 100.") + fs.MarkDeprecated("maximum-dead-containers", "Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.") fs.Var(&s.AuthPath, "auth-path", "Path to .kubernetes_auth file, specifying how to authenticate to API server.") fs.MarkDeprecated("auth-path", "will be removed in a future version") fs.Var(&s.KubeConfig, "kubeconfig", "Path to a kubeconfig file, specifying how to authenticate to API server (the master location is set by the api-servers flag).") - fs.UintVar(&s.CAdvisorPort, "cadvisor-port", s.CAdvisorPort, "The port of the localhost cAdvisor endpoint") + fs.Int32Var(&s.CAdvisorPort, "cadvisor-port", s.CAdvisorPort, "The port of the localhost cAdvisor endpoint") fs.Int32Var(&s.HealthzPort, "healthz-port", s.HealthzPort, "The port of the localhost healthz endpoint") fs.Var(componentconfig.IPVar{Val: &s.HealthzBindAddress}, "healthz-bind-address", "The IP address for the healthz server to serve on, defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces)") fs.Int32Var(&s.OOMScoreAdj, "oom-score-adj", s.OOMScoreAdj, "The oom-score-adj value for kubelet process. Values must be within the range [-1000, 1000]") @@ -208,7 +111,8 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.ClusterDNS, "cluster-dns", s.ClusterDNS, "IP address for a cluster DNS server. This value is used for containers' DNS server in case of Pods with \"dnsPolicy=ClusterFirst\"") fs.DurationVar(&s.StreamingConnectionIdleTimeout.Duration, "streaming-connection-idle-timeout", s.StreamingConnectionIdleTimeout.Duration, "Maximum time a streaming connection can be idle before the connection is automatically closed. 0 indicates no timeout. Example: '5m'") fs.DurationVar(&s.NodeStatusUpdateFrequency.Duration, "node-status-update-frequency", s.NodeStatusUpdateFrequency.Duration, "Specifies how often kubelet posts node status to master. Note: be cautious when changing the constant, it must work with nodeMonitorGracePeriod in nodecontroller. Default: 10s") - bindableNodeLabels := config.ConfigurationMap(s.NodeLabels) + s.NodeLabels = make(map[string]string) + bindableNodeLabels := utilconfig.ConfigurationMap(s.NodeLabels) fs.Var(&bindableNodeLabels, "node-labels", " Labels to add when registering the node in the cluster. Labels must be key=value pairs separated by ','.") fs.DurationVar(&s.ImageMinimumGCAge.Duration, "minimum-image-ttl-duration", s.ImageMinimumGCAge.Duration, "Minimum age for a unused image before it is garbage collected. Examples: '300ms', '10s' or '2h45m'. Default: '2m'") fs.Int32Var(&s.ImageGCHighThresholdPercent, "image-gc-high-threshold", s.ImageGCHighThresholdPercent, "The percent of disk usage after which image garbage collection is always run. Default: 90%") @@ -229,6 +133,7 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.MarkDeprecated("system-container", "Use --system-cgroups instead. Will be removed in a future version.") fs.StringVar(&s.SystemCgroups, "system-cgroups", s.SystemCgroups, "Optional absolute name of cgroups in which to place all non-kernel processes that are not already inside a cgroup under `/`. Empty for no container. Rolling back the flag requires a reboot. (Default: \"\").") + fs.BoolVar(&s.CgroupsPerQOS, "cgroups-per-qos", s.CgroupsPerQOS, "Enable creation of QoS cgroup hierarchy, if true top level QoS and pod cgroups are created.") fs.StringVar(&s.CgroupRoot, "cgroup-root", s.CgroupRoot, "Optional root cgroup to use for pods. This is handled by the container runtime on a best effort basis. Default: '', which means use the container runtime default.") fs.StringVar(&s.ContainerRuntime, "container-runtime", s.ContainerRuntime, "The container runtime to use. Possible values: 'docker', 'rkt'. Default: 'docker'.") fs.DurationVar(&s.RuntimeRequestTimeout.Duration, "runtime-request-timeout", s.RuntimeRequestTimeout.Duration, "Timeout of all runtime requests except long running request - pull, logs, exec and attach. When timeout exceeded, kubelet will cancel the request, throw out an error and retry later. Default: 2m0s") @@ -255,13 +160,13 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.BoolVar(&s.ReallyCrashForTesting, "really-crash-for-testing", s.ReallyCrashForTesting, "If true, when panics occur crash. Intended for testing.") fs.Float64Var(&s.ChaosChance, "chaos-chance", s.ChaosChance, "If > 0.0, introduce random client errors and latency. Intended for testing. [default=0.0]") fs.BoolVar(&s.Containerized, "containerized", s.Containerized, "Experimental support for running kubelet in a container. Intended for testing. [default=false]") - fs.Uint64Var(&s.MaxOpenFiles, "max-open-files", s.MaxOpenFiles, "Number of files that can be opened by Kubelet process. [default=1000000]") + fs.Int64Var(&s.MaxOpenFiles, "max-open-files", s.MaxOpenFiles, "Number of files that can be opened by Kubelet process. [default=1000000]") fs.BoolVar(&s.ReconcileCIDR, "reconcile-cidr", s.ReconcileCIDR, "Reconcile node CIDR with the CIDR specified by the API server. No-op if register-node or configure-cbr0 is false. [default=true]") fs.Var(&s.SystemReserved, "system-reserved", "A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs that describe resources reserved for non-kubernetes components. Currently only cpu and memory are supported. See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. [default=none]") fs.Var(&s.KubeReserved, "kube-reserved", "A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs that describe resources reserved for kubernetes system components. Currently only cpu and memory are supported. See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. [default=none]") fs.BoolVar(&s.RegisterSchedulable, "register-schedulable", s.RegisterSchedulable, "Register the node as schedulable. No-op if register-node is false. [default=true]") fs.StringVar(&s.ContentType, "kube-api-content-type", s.ContentType, "Content type of requests sent to apiserver.") - fs.Float32Var(&s.KubeAPIQPS, "kube-api-qps", s.KubeAPIQPS, "QPS to use while talking with kubernetes apiserver") + fs.Int32Var(&s.KubeAPIQPS, "kube-api-qps", s.KubeAPIQPS, "QPS to use while talking with kubernetes apiserver") fs.Int32Var(&s.KubeAPIBurst, "kube-api-burst", s.KubeAPIBurst, "Burst to use while talking with kubernetes apiserver") fs.BoolVar(&s.SerializeImagePulls, "serialize-image-pulls", s.SerializeImagePulls, "Pull images one at a time. We recommend *not* changing the default value on nodes that run docker daemon with version < 1.9 or an Aufs storage backend. Issue #10959 has more details. [default=true]") fs.BoolVar(&s.ExperimentalFlannelOverlay, "experimental-flannel-overlay", s.ExperimentalFlannelOverlay, "Experimental support for starting the kubelet with the default overlay network (flannel). Assumes flanneld is already running in client mode. [default=false]") @@ -274,5 +179,6 @@ func (s *KubeletServer) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.EvictionSoftGracePeriod, "eviction-soft-grace-period", s.EvictionSoftGracePeriod, "A set of eviction grace periods (e.g. memory.available=1m30s) that correspond to how long a soft eviction threshold must hold before triggering a pod eviction.") fs.DurationVar(&s.EvictionPressureTransitionPeriod.Duration, "eviction-pressure-transition-period", s.EvictionPressureTransitionPeriod.Duration, "Duration for which the kubelet has to wait before transitioning out of an eviction pressure condition.") fs.Int32Var(&s.EvictionMaxPodGracePeriod, "eviction-max-pod-grace-period", s.EvictionMaxPodGracePeriod, "Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met. If negative, defer to pod specified value.") + fs.StringVar(&s.EvictionMinimumReclaim, "eviction-minimum-reclaim", s.EvictionMinimumReclaim, "A set of minimum reclaims (e.g. imagefs.available=2Gi) that describes the minimum amount of resource the kubelet will reclaim when performing a pod eviction if that resource is under pressure.") fs.Int32Var(&s.PodsPerCore, "pods-per-core", s.PodsPerCore, "Number of Pods per core that can run on this Kubelet. The total number of Pods on this Kubelet cannot exceed max-pods, so max-pods will be used if this calculation results in a larger number of Pods allowed on the Kubelet. A value of 0 disables this limit.") } diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/plugins.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/plugins.go index 76736350e414..f904ffa582e3 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/plugins.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go index 9ee4a8ea52ff..cece8629744a 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/apis/componentconfig" + kubeExternal "k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1" "k8s.io/kubernetes/pkg/capabilities" "k8s.io/kubernetes/pkg/client/chaosclient" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" @@ -122,17 +123,17 @@ HTTP server: The kubelet can also listen for HTTP and respond to a simple API // UnsecuredKubeletConfig returns a KubeletConfig suitable for being run, or an error if the server setup // is not valid. It will not start any background processes, and does not include authentication/authorization func UnsecuredKubeletConfig(s *options.KubeletServer) (*KubeletConfig, error) { - hostNetworkSources, err := kubetypes.GetValidatedSources(strings.Split(s.HostNetworkSources, ",")) + hostNetworkSources, err := kubetypes.GetValidatedSources(s.HostNetworkSources) if err != nil { return nil, err } - hostPIDSources, err := kubetypes.GetValidatedSources(strings.Split(s.HostPIDSources, ",")) + hostPIDSources, err := kubetypes.GetValidatedSources(s.HostPIDSources) if err != nil { return nil, err } - hostIPCSources, err := kubetypes.GetValidatedSources(strings.Split(s.HostIPCSources, ",")) + hostIPCSources, err := kubetypes.GetValidatedSources(s.HostIPCSources) if err != nil { return nil, err } @@ -186,7 +187,7 @@ func UnsecuredKubeletConfig(s *options.KubeletServer) (*KubeletConfig, error) { return nil, err } - thresholds, err := eviction.ParseThresholdConfig(s.EvictionHard, s.EvictionSoft, s.EvictionSoftGracePeriod) + thresholds, err := eviction.ParseThresholdConfig(s.EvictionHard, s.EvictionSoft, s.EvictionSoftGracePeriod, s.EvictionMinimumReclaim) if err != nil { return nil, err } @@ -219,9 +220,10 @@ func UnsecuredKubeletConfig(s *options.KubeletServer) (*KubeletConfig, error) { EnableControllerAttachDetach: s.EnableControllerAttachDetach, EnableCustomMetrics: s.EnableCustomMetrics, EnableDebuggingHandlers: s.EnableDebuggingHandlers, + CgroupsPerQOS: s.CgroupsPerQOS, EnableServer: s.EnableServer, EventBurst: int(s.EventBurst), - EventRecordQPS: s.EventRecordQPS, + EventRecordQPS: float32(s.EventRecordQPS), FileCheckFrequency: s.FileCheckFrequency.Duration, HostnameOverride: s.HostnameOverride, HostNetworkSources: hostNetworkSources, @@ -234,7 +236,7 @@ func UnsecuredKubeletConfig(s *options.KubeletServer) (*KubeletConfig, error) { ManifestURLHeader: manifestURLHeader, MasterServiceNamespace: s.MasterServiceNamespace, MaxContainerCount: int(s.MaxContainerCount), - MaxOpenFiles: s.MaxOpenFiles, + MaxOpenFiles: uint64(s.MaxOpenFiles), MaxPerPodContainerCount: int(s.MaxPerPodContainerCount), MaxPods: int(s.MaxPods), NvidiaGPUs: int(s.NvidiaGPUs), @@ -250,12 +252,12 @@ func UnsecuredKubeletConfig(s *options.KubeletServer) (*KubeletConfig, error) { PodCIDR: s.PodCIDR, ReconcileCIDR: s.ReconcileCIDR, PodInfraContainerImage: s.PodInfraContainerImage, - Port: s.Port, - ReadOnlyPort: s.ReadOnlyPort, + Port: uint(s.Port), + ReadOnlyPort: uint(s.ReadOnlyPort), RegisterNode: s.RegisterNode, RegisterSchedulable: s.RegisterSchedulable, RegistryBurst: int(s.RegistryBurst), - RegistryPullQPS: s.RegistryPullQPS, + RegistryPullQPS: float64(s.RegistryPullQPS), ResolverConfig: s.ResolverConfig, Reservation: *reservation, KubeletCgroups: s.KubeletCgroups, @@ -331,7 +333,7 @@ func run(s *options.KubeletServer, kcfg *KubeletConfig) (err error) { // make a separate client for events eventClientConfig := *clientConfig - eventClientConfig.QPS = s.EventRecordQPS + eventClientConfig.QPS = float32(s.EventRecordQPS) eventClientConfig.Burst = int(s.EventBurst) kcfg.EventClient, err = clientset.NewForConfig(&eventClientConfig) } @@ -339,20 +341,24 @@ func run(s *options.KubeletServer, kcfg *KubeletConfig) (err error) { glog.Warningf("No API client: %v", err) } - if s.CloudProvider == options.AutoDetectCloudProvider { + if s.CloudProvider == kubeExternal.AutoDetectCloudProvider { kcfg.AutoDetectCloudProvider = true } else { cloud, err := cloudprovider.InitCloudProvider(s.CloudProvider, s.CloudConfigFile) if err != nil { return err } - glog.V(2).Infof("Successfully initialized cloud provider: %q from the config file: %q\n", s.CloudProvider, s.CloudConfigFile) - kcfg.Cloud = cloud + if cloud == nil { + glog.V(2).Infof("No cloud provider specified: %q from the config file: %q\n", s.CloudProvider, s.CloudConfigFile) + } else { + glog.V(2).Infof("Successfully initialized cloud provider: %q from the config file: %q\n", s.CloudProvider, s.CloudConfigFile) + kcfg.Cloud = cloud + } } } if kcfg.CAdvisorInterface == nil { - kcfg.CAdvisorInterface, err = cadvisor.New(s.CAdvisorPort, kcfg.ContainerRuntime) + kcfg.CAdvisorInterface, err = cadvisor.New(uint(s.CAdvisorPort), kcfg.ContainerRuntime) if err != nil { return err } @@ -362,12 +368,13 @@ func run(s *options.KubeletServer, kcfg *KubeletConfig) (err error) { if kcfg.SystemCgroups != "" && kcfg.CgroupRoot == "" { return fmt.Errorf("invalid configuration: system container was specified and cgroup root was not specified") } - kcfg.ContainerManager, err = cm.NewContainerManager(kcfg.Mounter, kcfg.CAdvisorInterface, cm.NodeConfig{ RuntimeCgroupsName: kcfg.RuntimeCgroups, SystemCgroupsName: kcfg.SystemCgroups, KubeletCgroupsName: kcfg.KubeletCgroups, ContainerRuntime: kcfg.ContainerRuntime, + CgroupsPerQOS: kcfg.CgroupsPerQOS, + CgroupRoot: kcfg.CgroupRoot, }) if err != nil { return err @@ -377,10 +384,6 @@ func run(s *options.KubeletServer, kcfg *KubeletConfig) (err error) { runtime.ReallyCrash = s.ReallyCrashForTesting rand.Seed(time.Now().UTC().UnixNano()) - credentialprovider.SetPreferredDockercfgPath(s.RootDirectory) - - glog.V(2).Infof("Using root directory: %v", s.RootDirectory) - // TODO(vmarmol): Do this through container config. oomAdjuster := kcfg.OOMAdjuster if err := oomAdjuster.ApplyOOMScoreAdj(0, int(s.OOMScoreAdj)); err != nil { @@ -510,7 +513,7 @@ func CreateAPIServerClientConfig(s *options.KubeletServer) (*restclient.Config, clientConfig.ContentType = s.ContentType // Override kubeconfig qps/burst settings from flags - clientConfig.QPS = s.KubeAPIQPS + clientConfig.QPS = float32(s.KubeAPIQPS) clientConfig.Burst = int(s.KubeAPIBurst) addChaosToClientConfig(s, clientConfig) @@ -557,6 +560,8 @@ func SimpleKubelet(client *clientset.Clientset, evictionConfig := eviction.Config{ PressureTransitionPeriod: evictionPressureTransitionPeriod, } + + c := componentconfig.KubeletConfiguration{} kcfg := KubeletConfig{ Address: net.ParseIP(address), CAdvisorInterface: cadvisorInterface, @@ -576,6 +581,7 @@ func SimpleKubelet(client *clientset.Clientset, EnableCustomMetrics: false, EnableDebuggingHandlers: true, EnableServer: true, + CgroupsPerQOS: false, FileCheckFrequency: fileCheckFrequency, // Since this kubelet runs with --configure-cbr0=false, it needs to use // hairpin-veth to allow hairpin packets. Note that this deviates from @@ -598,7 +604,7 @@ func SimpleKubelet(client *clientset.Clientset, NodeStatusUpdateFrequency: nodeStatusUpdateFrequency, OOMAdjuster: oom.NewFakeOOMAdjuster(), OSInterface: osInterface, - PodInfraContainerImage: options.GetDefaultPodInfraContainerImage(), + PodInfraContainerImage: c.PodInfraContainerImage, Port: port, ReadOnlyPort: readOnlyPort, RegisterNode: true, @@ -668,6 +674,7 @@ func RunKubelet(kcfg *KubeletConfig) error { capabilities.Setup(kcfg.AllowPrivileged, privilegedSources, 0) credentialprovider.SetPreferredDockercfgPath(kcfg.RootDirectory) + glog.V(2).Infof("Using root directory: %v", kcfg.RootDirectory) builder := kcfg.Builder if builder == nil { @@ -798,6 +805,7 @@ type KubeletConfig struct { EnableControllerAttachDetach bool EnableCustomMetrics bool EnableDebuggingHandlers bool + CgroupsPerQOS bool EnableServer bool EventClient *clientset.Clientset EventBurst int @@ -929,6 +937,7 @@ func CreateAndInitKubelet(kc *KubeletConfig) (k KubeletBootstrap, pc *config.Pod kc.NodeLabels, kc.NodeStatusUpdateFrequency, kc.OSInterface, + kc.CgroupsPerQOS, kc.CgroupRoot, kc.ContainerRuntime, kc.RuntimeRequestTimeout, diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_linux.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_linux.go index a687f6f8daa9..ceab334c0ba7 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_linux.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_linux.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_unsupported.go b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_unsupported.go index 8647b8b68be3..fd42a8ddd7ca 100644 --- a/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_unsupported.go +++ b/vendor/k8s.io/kubernetes/cmd/kubelet/app/server_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/attributes.go b/vendor/k8s.io/kubernetes/pkg/admission/attributes.go index d3b8dd080c00..4075cf9007fc 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/attributes.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/attributes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/chain.go b/vendor/k8s.io/kubernetes/pkg/admission/chain.go index 5301a7b724e4..a43bf8bb5b66 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/chain.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/chain.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ type chainAdmissionHandler []Interface // NewFromPlugins returns an admission.Interface that will enforce admission control decisions of all // the given plugins. -func NewFromPlugins(client clientset.Interface, pluginNames []string, configFilePath string) Interface { +func NewFromPlugins(client clientset.Interface, pluginNames []string, configFilePath string, plugInit PluginInitializer) (Interface, error) { plugins := []Interface{} for _, pluginName := range pluginNames { plugin := InitPlugin(pluginName, client, configFilePath) @@ -31,7 +31,12 @@ func NewFromPlugins(client clientset.Interface, pluginNames []string, configFile plugins = append(plugins, plugin) } } - return chainAdmissionHandler(plugins) + plugInit.Initialize(plugins) + // ensure that plugins have been properly initialized + if err := Validate(plugins); err != nil { + return nil, err + } + return chainAdmissionHandler(plugins), nil } // NewChainHandler creates a new chain handler from an array of handlers. Used for testing. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/errors.go b/vendor/k8s.io/kubernetes/pkg/admission/errors.go index bf5204e42ce9..b6878849b8bf 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/handler.go b/vendor/k8s.io/kubernetes/pkg/admission/handler.go index a0d26c469715..b4f2c577554b 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/handler.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/handler.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/init.go b/vendor/k8s.io/kubernetes/pkg/admission/init.go new file mode 100644 index 000000000000..c4433ffce503 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/admission/init.go @@ -0,0 +1,63 @@ +/* +Copyright 2016 The Kubernetes 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 admission + +import ( + "k8s.io/kubernetes/pkg/controller/framework/informers" +) + +// PluginInitializer is used for initialization of shareable resources between admission plugins. +// After initialization the resources have to be set separately +type PluginInitializer interface { + Initialize(plugins []Interface) +} + +type pluginInitializer struct { + informers informers.SharedInformerFactory +} + +// NewPluginInitializer constructs new instance of PluginInitializer +func NewPluginInitializer(sharedInformers informers.SharedInformerFactory) PluginInitializer { + plugInit := &pluginInitializer{ + informers: sharedInformers, + } + return plugInit +} + +// Initialize checks the initialization interfaces implemented by each plugin +// and provide the appropriate initialization data +func (i *pluginInitializer) Initialize(plugins []Interface) { + for _, plugin := range plugins { + if wantsInformerFactory, ok := plugin.(WantsInformerFactory); ok { + wantsInformerFactory.SetInformerFactory(i.informers) + } + } +} + +// Validate will call the Validate function in each plugin if they implement +// the Validator interface. +func Validate(plugins []Interface) error { + for _, plugin := range plugins { + if validater, ok := plugin.(Validator); ok { + err := validater.Validate() + if err != nil { + return err + } + } + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/admission/interfaces.go b/vendor/k8s.io/kubernetes/pkg/admission/interfaces.go index 6c3ef0976033..a5fa7ef65ac9 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/plugins.go b/vendor/k8s.io/kubernetes/pkg/admission/plugins.go index 17736c4f3206..6d739d99c5ed 100644 --- a/vendor/k8s.io/kubernetes/pkg/admission/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/admission/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/admission/types.go b/vendor/k8s.io/kubernetes/pkg/admission/types.go new file mode 100644 index 000000000000..4de01016eb12 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/admission/types.go @@ -0,0 +1,33 @@ +/* +Copyright 2016 The Kubernetes 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 admission + +import ( + "k8s.io/kubernetes/pkg/controller/framework/informers" +) + +// Validator holds Validate functions, which are responsible for validation of initialized shared resources +// and should be implemented on admission plugins +type Validator interface { + Validate() error +} + +// WantsNamespaceInformer defines a function which sets NamespaceInformer for admission plugins that need it +type WantsInformerFactory interface { + SetInformerFactory(informers.SharedInformerFactory) + Validator +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/annotations/annotations.go b/vendor/k8s.io/kubernetes/pkg/api/annotations/annotations.go index dbdf11cbabcf..2f9a6c442276 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/annotations/annotations.go +++ b/vendor/k8s.io/kubernetes/pkg/api/annotations/annotations.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/annotations/doc.go b/vendor/k8s.io/kubernetes/pkg/api/annotations/doc.go index 6a422ea4f414..0c36c85cc17f 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/annotations/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/annotations/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/context.go b/vendor/k8s.io/kubernetes/pkg/api/context.go index 7e86395712a1..580e6b8a0a6e 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/context.go +++ b/vendor/k8s.io/kubernetes/pkg/api/context.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import ( "golang.org/x/net/context" "k8s.io/kubernetes/pkg/auth/user" + "k8s.io/kubernetes/pkg/types" ) // Context carries values across API boundaries. @@ -49,11 +50,16 @@ type Context interface { // The key type is unexported to prevent collisions type key int -// namespaceKey is the context key for the request namespace. -const namespaceKey key = 0 +const ( + // namespaceKey is the context key for the request namespace. + namespaceKey key = iota -// userKey is the context key for the request user. -const userKey key = 1 + // userKey is the context key for the request user. + userKey + + // uidKey is the context key for the uid to assign to an object on create. + uidKey +) // NewContext instantiates a base context object for request flows. func NewContext() Context { @@ -119,3 +125,14 @@ func UserFrom(ctx Context) (user.Info, bool) { user, ok := ctx.Value(userKey).(user.Info) return user, ok } + +// WithUID returns a copy of parent in which the uid value is set +func WithUID(parent Context, uid types.UID) Context { + return WithValue(parent, uidKey, uid) +} + +// UIDFrom returns the value of the uid key on the ctx +func UIDFrom(ctx Context) (types.UID, bool) { + uid, ok := ctx.Value(uidKey).(types.UID) + return uid, ok +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/conversion.go b/vendor/k8s.io/kubernetes/pkg/api/conversion.go index 7ae1e0184e39..033e755f4cd2 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/api/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,12 +17,16 @@ limitations under the License. package api import ( + "fmt" + "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/intstr" + utillabels "k8s.io/kubernetes/pkg/util/labels" + "k8s.io/kubernetes/pkg/util/validation/field" ) func init() { @@ -38,22 +42,88 @@ func init() { ) Scheme.AddConversionFuncs( Convert_unversioned_TypeMeta_To_unversioned_TypeMeta, + Convert_unversioned_ListMeta_To_unversioned_ListMeta, + Convert_intstr_IntOrString_To_intstr_IntOrString, + Convert_unversioned_Time_To_unversioned_Time, + Convert_Slice_string_To_unversioned_Time, + + Convert_resource_Quantity_To_resource_Quantity, + Convert_string_To_labels_Selector, + Convert_labels_Selector_To_string, + Convert_string_To_fields_Selector, + Convert_fields_Selector_To_string, + Convert_Pointer_bool_To_bool, Convert_bool_To_Pointer_bool, + Convert_Pointer_string_To_string, Convert_string_To_Pointer_string, - Convert_labels_Selector_To_string, - Convert_fields_Selector_To_string, - Convert_resource_Quantity_To_resource_Quantity, + + Convert_Pointer_int64_To_int, + Convert_int_To_Pointer_int64, + + Convert_Pointer_int32_To_int32, + Convert_int32_To_Pointer_int32, + + Convert_Pointer_float64_To_float64, + Convert_float64_To_Pointer_float64, + + Convert_map_to_unversioned_LabelSelector, + Convert_unversioned_LabelSelector_to_map, ) } +func Convert_Pointer_float64_To_float64(in **float64, out *float64, s conversion.Scope) error { + if *in == nil { + *out = 0 + return nil + } + *out = float64(**in) + return nil +} + +func Convert_float64_To_Pointer_float64(in *float64, out **float64, s conversion.Scope) error { + temp := float64(*in) + *out = &temp + return nil +} + +func Convert_Pointer_int32_To_int32(in **int32, out *int32, s conversion.Scope) error { + if *in == nil { + *out = 0 + return nil + } + *out = int32(**in) + return nil +} + +func Convert_int32_To_Pointer_int32(in *int32, out **int32, s conversion.Scope) error { + temp := int32(*in) + *out = &temp + return nil +} + +func Convert_Pointer_int64_To_int(in **int64, out *int, s conversion.Scope) error { + if *in == nil { + *out = 0 + return nil + } + *out = int(**in) + return nil +} + +func Convert_int_To_Pointer_int64(in *int, out **int64, s conversion.Scope) error { + temp := int64(*in) + *out = &temp + return nil +} + func Convert_Pointer_string_To_string(in **string, out *string, s conversion.Scope) error { if *in == nil { *out = "" @@ -100,15 +170,12 @@ func Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(in, out *unversioned.T } func Convert_unversioned_ListMeta_To_unversioned_ListMeta(in, out *unversioned.ListMeta, s conversion.Scope) error { - out.ResourceVersion = in.ResourceVersion - out.SelfLink = in.SelfLink + *out = *in return nil } func Convert_intstr_IntOrString_To_intstr_IntOrString(in, out *intstr.IntOrString, s conversion.Scope) error { - out.Type = in.Type - out.IntVal = in.IntVal - out.StrVal = in.StrVal + *out = *in return nil } @@ -135,6 +202,7 @@ func Convert_string_To_labels_Selector(in *string, out *labels.Selector, s conve *out = selector return nil } + func Convert_string_To_fields_Selector(in *string, out *fields.Selector, s conversion.Scope) error { selector, err := fields.ParseSelector(*in) if err != nil { @@ -143,6 +211,7 @@ func Convert_string_To_fields_Selector(in *string, out *fields.Selector, s conve *out = selector return nil } + func Convert_labels_Selector_To_string(in *labels.Selector, out *string, s conversion.Scope) error { if *in == nil { return nil @@ -150,6 +219,7 @@ func Convert_labels_Selector_To_string(in *labels.Selector, out *string, s conve *out = (*in).String() return nil } + func Convert_fields_Selector_To_string(in *fields.Selector, out *string, s conversion.Scope) error { if *in == nil { return nil @@ -157,7 +227,25 @@ func Convert_fields_Selector_To_string(in *fields.Selector, out *string, s conve *out = (*in).String() return nil } + func Convert_resource_Quantity_To_resource_Quantity(in *resource.Quantity, out *resource.Quantity, s conversion.Scope) error { *out = *in return nil } + +func Convert_map_to_unversioned_LabelSelector(in *map[string]string, out *unversioned.LabelSelector, s conversion.Scope) error { + out = new(unversioned.LabelSelector) + for labelKey, labelValue := range *in { + utillabels.AddLabelToSelector(out, labelKey, labelValue) + } + return nil +} + +func Convert_unversioned_LabelSelector_to_map(in *unversioned.LabelSelector, out *map[string]string, s conversion.Scope) error { + var err error + *out, err = unversioned.LabelSelectorAsMap(in) + if err != nil { + err = field.Invalid(field.NewPath("labelSelector"), *in, fmt.Sprintf("cannot convert to old selector: %v", err)) + } + return err +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/api/deep_copy_generated.go deleted file mode 100644 index f3181b8a730d..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/deep_copy_generated.go +++ /dev/null @@ -1,3300 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package api - -import ( - resource "k8s.io/kubernetes/pkg/api/resource" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" - fields "k8s.io/kubernetes/pkg/fields" - labels "k8s.io/kubernetes/pkg/labels" - runtime "k8s.io/kubernetes/pkg/runtime" - types "k8s.io/kubernetes/pkg/types" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_api_AWSElasticBlockStoreVolumeSource, - DeepCopy_api_Affinity, - DeepCopy_api_AttachedVolume, - DeepCopy_api_AzureFileVolumeSource, - DeepCopy_api_Binding, - DeepCopy_api_Capabilities, - DeepCopy_api_CephFSVolumeSource, - DeepCopy_api_CinderVolumeSource, - DeepCopy_api_ComponentCondition, - DeepCopy_api_ComponentStatus, - DeepCopy_api_ComponentStatusList, - DeepCopy_api_ConfigMap, - DeepCopy_api_ConfigMapKeySelector, - DeepCopy_api_ConfigMapList, - DeepCopy_api_ConfigMapVolumeSource, - DeepCopy_api_Container, - DeepCopy_api_ContainerImage, - DeepCopy_api_ContainerPort, - DeepCopy_api_ContainerState, - DeepCopy_api_ContainerStateRunning, - DeepCopy_api_ContainerStateTerminated, - DeepCopy_api_ContainerStateWaiting, - DeepCopy_api_ContainerStatus, - DeepCopy_api_ConversionError, - DeepCopy_api_DaemonEndpoint, - DeepCopy_api_DeleteOptions, - DeepCopy_api_DownwardAPIVolumeFile, - DeepCopy_api_DownwardAPIVolumeSource, - DeepCopy_api_EmptyDirVolumeSource, - DeepCopy_api_EndpointAddress, - DeepCopy_api_EndpointPort, - DeepCopy_api_EndpointSubset, - DeepCopy_api_Endpoints, - DeepCopy_api_EndpointsList, - DeepCopy_api_EnvVar, - DeepCopy_api_EnvVarSource, - DeepCopy_api_Event, - DeepCopy_api_EventList, - DeepCopy_api_EventSource, - DeepCopy_api_ExecAction, - DeepCopy_api_ExportOptions, - DeepCopy_api_FCVolumeSource, - DeepCopy_api_FlexVolumeSource, - DeepCopy_api_FlockerVolumeSource, - DeepCopy_api_GCEPersistentDiskVolumeSource, - DeepCopy_api_GitRepoVolumeSource, - DeepCopy_api_GlusterfsVolumeSource, - DeepCopy_api_HTTPGetAction, - DeepCopy_api_HTTPHeader, - DeepCopy_api_Handler, - DeepCopy_api_HostPathVolumeSource, - DeepCopy_api_ISCSIVolumeSource, - DeepCopy_api_KeyToPath, - DeepCopy_api_Lifecycle, - DeepCopy_api_LimitRange, - DeepCopy_api_LimitRangeItem, - DeepCopy_api_LimitRangeList, - DeepCopy_api_LimitRangeSpec, - DeepCopy_api_List, - DeepCopy_api_ListOptions, - DeepCopy_api_LoadBalancerIngress, - DeepCopy_api_LoadBalancerStatus, - DeepCopy_api_LocalObjectReference, - DeepCopy_api_NFSVolumeSource, - DeepCopy_api_Namespace, - DeepCopy_api_NamespaceList, - DeepCopy_api_NamespaceSpec, - DeepCopy_api_NamespaceStatus, - DeepCopy_api_Node, - DeepCopy_api_NodeAddress, - DeepCopy_api_NodeAffinity, - DeepCopy_api_NodeCondition, - DeepCopy_api_NodeDaemonEndpoints, - DeepCopy_api_NodeList, - DeepCopy_api_NodeProxyOptions, - DeepCopy_api_NodeResources, - DeepCopy_api_NodeSelector, - DeepCopy_api_NodeSelectorRequirement, - DeepCopy_api_NodeSelectorTerm, - DeepCopy_api_NodeSpec, - DeepCopy_api_NodeStatus, - DeepCopy_api_NodeSystemInfo, - DeepCopy_api_ObjectFieldSelector, - DeepCopy_api_ObjectMeta, - DeepCopy_api_ObjectReference, - DeepCopy_api_OwnerReference, - DeepCopy_api_PersistentVolume, - DeepCopy_api_PersistentVolumeClaim, - DeepCopy_api_PersistentVolumeClaimList, - DeepCopy_api_PersistentVolumeClaimSpec, - DeepCopy_api_PersistentVolumeClaimStatus, - DeepCopy_api_PersistentVolumeClaimVolumeSource, - DeepCopy_api_PersistentVolumeList, - DeepCopy_api_PersistentVolumeSource, - DeepCopy_api_PersistentVolumeSpec, - DeepCopy_api_PersistentVolumeStatus, - DeepCopy_api_Pod, - DeepCopy_api_PodAffinity, - DeepCopy_api_PodAffinityTerm, - DeepCopy_api_PodAntiAffinity, - DeepCopy_api_PodAttachOptions, - DeepCopy_api_PodCondition, - DeepCopy_api_PodExecOptions, - DeepCopy_api_PodList, - DeepCopy_api_PodLogOptions, - DeepCopy_api_PodProxyOptions, - DeepCopy_api_PodSecurityContext, - DeepCopy_api_PodSpec, - DeepCopy_api_PodStatus, - DeepCopy_api_PodStatusResult, - DeepCopy_api_PodTemplate, - DeepCopy_api_PodTemplateList, - DeepCopy_api_PodTemplateSpec, - DeepCopy_api_Preconditions, - DeepCopy_api_PreferredSchedulingTerm, - DeepCopy_api_Probe, - DeepCopy_api_RBDVolumeSource, - DeepCopy_api_RangeAllocation, - DeepCopy_api_ReplicationController, - DeepCopy_api_ReplicationControllerList, - DeepCopy_api_ReplicationControllerSpec, - DeepCopy_api_ReplicationControllerStatus, - DeepCopy_api_ResourceFieldSelector, - DeepCopy_api_ResourceQuota, - DeepCopy_api_ResourceQuotaList, - DeepCopy_api_ResourceQuotaSpec, - DeepCopy_api_ResourceQuotaStatus, - DeepCopy_api_ResourceRequirements, - DeepCopy_api_SELinuxOptions, - DeepCopy_api_Secret, - DeepCopy_api_SecretKeySelector, - DeepCopy_api_SecretList, - DeepCopy_api_SecretVolumeSource, - DeepCopy_api_SecurityContext, - DeepCopy_api_SerializedReference, - DeepCopy_api_Service, - DeepCopy_api_ServiceAccount, - DeepCopy_api_ServiceAccountList, - DeepCopy_api_ServiceList, - DeepCopy_api_ServicePort, - DeepCopy_api_ServiceProxyOptions, - DeepCopy_api_ServiceSpec, - DeepCopy_api_ServiceStatus, - DeepCopy_api_TCPSocketAction, - DeepCopy_api_Taint, - DeepCopy_api_Toleration, - DeepCopy_api_Volume, - DeepCopy_api_VolumeMount, - DeepCopy_api_VolumeSource, - DeepCopy_api_VsphereVirtualDiskVolumeSource, - DeepCopy_api_WeightedPodAffinityTerm, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_api_AWSElasticBlockStoreVolumeSource(in AWSElasticBlockStoreVolumeSource, out *AWSElasticBlockStoreVolumeSource, c *conversion.Cloner) error { - out.VolumeID = in.VolumeID - out.FSType = in.FSType - out.Partition = in.Partition - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_Affinity(in Affinity, out *Affinity, c *conversion.Cloner) error { - if in.NodeAffinity != nil { - in, out := in.NodeAffinity, &out.NodeAffinity - *out = new(NodeAffinity) - if err := DeepCopy_api_NodeAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.NodeAffinity = nil - } - if in.PodAffinity != nil { - in, out := in.PodAffinity, &out.PodAffinity - *out = new(PodAffinity) - if err := DeepCopy_api_PodAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.PodAffinity = nil - } - if in.PodAntiAffinity != nil { - in, out := in.PodAntiAffinity, &out.PodAntiAffinity - *out = new(PodAntiAffinity) - if err := DeepCopy_api_PodAntiAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.PodAntiAffinity = nil - } - return nil -} - -func DeepCopy_api_AttachedVolume(in AttachedVolume, out *AttachedVolume, c *conversion.Cloner) error { - out.Name = in.Name - out.DevicePath = in.DevicePath - return nil -} - -func DeepCopy_api_AzureFileVolumeSource(in AzureFileVolumeSource, out *AzureFileVolumeSource, c *conversion.Cloner) error { - out.SecretName = in.SecretName - out.ShareName = in.ShareName - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_Binding(in Binding, out *Binding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectReference(in.Target, &out.Target, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_Capabilities(in Capabilities, out *Capabilities, c *conversion.Cloner) error { - if in.Add != nil { - in, out := in.Add, &out.Add - *out = make([]Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Add = nil - } - if in.Drop != nil { - in, out := in.Drop, &out.Drop - *out = make([]Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Drop = nil - } - return nil -} - -func DeepCopy_api_CephFSVolumeSource(in CephFSVolumeSource, out *CephFSVolumeSource, c *conversion.Cloner) error { - if in.Monitors != nil { - in, out := in.Monitors, &out.Monitors - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Monitors = nil - } - out.Path = in.Path - out.User = in.User - out.SecretFile = in.SecretFile - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_CinderVolumeSource(in CinderVolumeSource, out *CinderVolumeSource, c *conversion.Cloner) error { - out.VolumeID = in.VolumeID - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_ComponentCondition(in ComponentCondition, out *ComponentCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - out.Message = in.Message - out.Error = in.Error - return nil -} - -func DeepCopy_api_ComponentStatus(in ComponentStatus, out *ComponentStatus, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]ComponentCondition, len(in)) - for i := range in { - if err := DeepCopy_api_ComponentCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - return nil -} - -func DeepCopy_api_ComponentStatusList(in ComponentStatusList, out *ComponentStatusList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ComponentStatus, len(in)) - for i := range in { - if err := DeepCopy_api_ComponentStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ConfigMap(in ConfigMap, out *ConfigMap, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_api_ConfigMapKeySelector(in ConfigMapKeySelector, out *ConfigMapKeySelector, c *conversion.Cloner) error { - if err := DeepCopy_api_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - out.Key = in.Key - return nil -} - -func DeepCopy_api_ConfigMapList(in ConfigMapList, out *ConfigMapList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ConfigMap, len(in)) - for i := range in { - if err := DeepCopy_api_ConfigMap(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ConfigMapVolumeSource(in ConfigMapVolumeSource, out *ConfigMapVolumeSource, c *conversion.Cloner) error { - if err := DeepCopy_api_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]KeyToPath, len(in)) - for i := range in { - if err := DeepCopy_api_KeyToPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_Container(in Container, out *Container, c *conversion.Cloner) error { - out.Name = in.Name - out.Image = in.Image - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - if in.Args != nil { - in, out := in.Args, &out.Args - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Args = nil - } - out.WorkingDir = in.WorkingDir - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]ContainerPort, len(in)) - for i := range in { - if err := DeepCopy_api_ContainerPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.Env != nil { - in, out := in.Env, &out.Env - *out = make([]EnvVar, len(in)) - for i := range in { - if err := DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Env = nil - } - if err := DeepCopy_api_ResourceRequirements(in.Resources, &out.Resources, c); err != nil { - return err - } - if in.VolumeMounts != nil { - in, out := in.VolumeMounts, &out.VolumeMounts - *out = make([]VolumeMount, len(in)) - for i := range in { - if err := DeepCopy_api_VolumeMount(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumeMounts = nil - } - if in.LivenessProbe != nil { - in, out := in.LivenessProbe, &out.LivenessProbe - *out = new(Probe) - if err := DeepCopy_api_Probe(*in, *out, c); err != nil { - return err - } - } else { - out.LivenessProbe = nil - } - if in.ReadinessProbe != nil { - in, out := in.ReadinessProbe, &out.ReadinessProbe - *out = new(Probe) - if err := DeepCopy_api_Probe(*in, *out, c); err != nil { - return err - } - } else { - out.ReadinessProbe = nil - } - if in.Lifecycle != nil { - in, out := in.Lifecycle, &out.Lifecycle - *out = new(Lifecycle) - if err := DeepCopy_api_Lifecycle(*in, *out, c); err != nil { - return err - } - } else { - out.Lifecycle = nil - } - out.TerminationMessagePath = in.TerminationMessagePath - out.ImagePullPolicy = in.ImagePullPolicy - if in.SecurityContext != nil { - in, out := in.SecurityContext, &out.SecurityContext - *out = new(SecurityContext) - if err := DeepCopy_api_SecurityContext(*in, *out, c); err != nil { - return err - } - } else { - out.SecurityContext = nil - } - out.Stdin = in.Stdin - out.StdinOnce = in.StdinOnce - out.TTY = in.TTY - return nil -} - -func DeepCopy_api_ContainerImage(in ContainerImage, out *ContainerImage, c *conversion.Cloner) error { - if in.Names != nil { - in, out := in.Names, &out.Names - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Names = nil - } - out.SizeBytes = in.SizeBytes - return nil -} - -func DeepCopy_api_ContainerPort(in ContainerPort, out *ContainerPort, c *conversion.Cloner) error { - out.Name = in.Name - out.HostPort = in.HostPort - out.ContainerPort = in.ContainerPort - out.Protocol = in.Protocol - out.HostIP = in.HostIP - return nil -} - -func DeepCopy_api_ContainerState(in ContainerState, out *ContainerState, c *conversion.Cloner) error { - if in.Waiting != nil { - in, out := in.Waiting, &out.Waiting - *out = new(ContainerStateWaiting) - if err := DeepCopy_api_ContainerStateWaiting(*in, *out, c); err != nil { - return err - } - } else { - out.Waiting = nil - } - if in.Running != nil { - in, out := in.Running, &out.Running - *out = new(ContainerStateRunning) - if err := DeepCopy_api_ContainerStateRunning(*in, *out, c); err != nil { - return err - } - } else { - out.Running = nil - } - if in.Terminated != nil { - in, out := in.Terminated, &out.Terminated - *out = new(ContainerStateTerminated) - if err := DeepCopy_api_ContainerStateTerminated(*in, *out, c); err != nil { - return err - } - } else { - out.Terminated = nil - } - return nil -} - -func DeepCopy_api_ContainerStateRunning(in ContainerStateRunning, out *ContainerStateRunning, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_Time(in.StartedAt, &out.StartedAt, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_ContainerStateTerminated(in ContainerStateTerminated, out *ContainerStateTerminated, c *conversion.Cloner) error { - out.ExitCode = in.ExitCode - out.Signal = in.Signal - out.Reason = in.Reason - out.Message = in.Message - if err := unversioned.DeepCopy_unversioned_Time(in.StartedAt, &out.StartedAt, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.FinishedAt, &out.FinishedAt, c); err != nil { - return err - } - out.ContainerID = in.ContainerID - return nil -} - -func DeepCopy_api_ContainerStateWaiting(in ContainerStateWaiting, out *ContainerStateWaiting, c *conversion.Cloner) error { - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_api_ContainerStatus(in ContainerStatus, out *ContainerStatus, c *conversion.Cloner) error { - out.Name = in.Name - if err := DeepCopy_api_ContainerState(in.State, &out.State, c); err != nil { - return err - } - if err := DeepCopy_api_ContainerState(in.LastTerminationState, &out.LastTerminationState, c); err != nil { - return err - } - out.Ready = in.Ready - out.RestartCount = in.RestartCount - out.Image = in.Image - out.ImageID = in.ImageID - out.ContainerID = in.ContainerID - return nil -} - -func DeepCopy_api_ConversionError(in ConversionError, out *ConversionError, c *conversion.Cloner) error { - if in.In == nil { - out.In = nil - } else if newVal, err := c.DeepCopy(in.In); err != nil { - return err - } else { - out.In = newVal.(interface{}) - } - if in.Out == nil { - out.Out = nil - } else if newVal, err := c.DeepCopy(in.Out); err != nil { - return err - } else { - out.Out = newVal.(interface{}) - } - out.Message = in.Message - return nil -} - -func DeepCopy_api_DaemonEndpoint(in DaemonEndpoint, out *DaemonEndpoint, c *conversion.Cloner) error { - out.Port = in.Port - return nil -} - -func DeepCopy_api_DeleteOptions(in DeleteOptions, out *DeleteOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.GracePeriodSeconds != nil { - in, out := in.GracePeriodSeconds, &out.GracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.GracePeriodSeconds = nil - } - if in.Preconditions != nil { - in, out := in.Preconditions, &out.Preconditions - *out = new(Preconditions) - if err := DeepCopy_api_Preconditions(*in, *out, c); err != nil { - return err - } - } else { - out.Preconditions = nil - } - if in.OrphanDependents != nil { - in, out := in.OrphanDependents, &out.OrphanDependents - *out = new(bool) - **out = *in - } else { - out.OrphanDependents = nil - } - return nil -} - -func DeepCopy_api_DownwardAPIVolumeFile(in DownwardAPIVolumeFile, out *DownwardAPIVolumeFile, c *conversion.Cloner) error { - out.Path = in.Path - if in.FieldRef != nil { - in, out := in.FieldRef, &out.FieldRef - *out = new(ObjectFieldSelector) - if err := DeepCopy_api_ObjectFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.FieldRef = nil - } - if in.ResourceFieldRef != nil { - in, out := in.ResourceFieldRef, &out.ResourceFieldRef - *out = new(ResourceFieldSelector) - if err := DeepCopy_api_ResourceFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceFieldRef = nil - } - return nil -} - -func DeepCopy_api_DownwardAPIVolumeSource(in DownwardAPIVolumeSource, out *DownwardAPIVolumeSource, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]DownwardAPIVolumeFile, len(in)) - for i := range in { - if err := DeepCopy_api_DownwardAPIVolumeFile(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error { - out.Medium = in.Medium - return nil -} - -func DeepCopy_api_EndpointAddress(in EndpointAddress, out *EndpointAddress, c *conversion.Cloner) error { - out.IP = in.IP - out.Hostname = in.Hostname - if in.TargetRef != nil { - in, out := in.TargetRef, &out.TargetRef - *out = new(ObjectReference) - if err := DeepCopy_api_ObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.TargetRef = nil - } - return nil -} - -func DeepCopy_api_EndpointPort(in EndpointPort, out *EndpointPort, c *conversion.Cloner) error { - out.Name = in.Name - out.Port = in.Port - out.Protocol = in.Protocol - return nil -} - -func DeepCopy_api_EndpointSubset(in EndpointSubset, out *EndpointSubset, c *conversion.Cloner) error { - if in.Addresses != nil { - in, out := in.Addresses, &out.Addresses - *out = make([]EndpointAddress, len(in)) - for i := range in { - if err := DeepCopy_api_EndpointAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Addresses = nil - } - if in.NotReadyAddresses != nil { - in, out := in.NotReadyAddresses, &out.NotReadyAddresses - *out = make([]EndpointAddress, len(in)) - for i := range in { - if err := DeepCopy_api_EndpointAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.NotReadyAddresses = nil - } - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]EndpointPort, len(in)) - for i := range in { - if err := DeepCopy_api_EndpointPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - return nil -} - -func DeepCopy_api_Endpoints(in Endpoints, out *Endpoints, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subsets != nil { - in, out := in.Subsets, &out.Subsets - *out = make([]EndpointSubset, len(in)) - for i := range in { - if err := DeepCopy_api_EndpointSubset(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subsets = nil - } - return nil -} - -func DeepCopy_api_EndpointsList(in EndpointsList, out *EndpointsList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Endpoints, len(in)) - for i := range in { - if err := DeepCopy_api_Endpoints(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_EnvVar(in EnvVar, out *EnvVar, c *conversion.Cloner) error { - out.Name = in.Name - out.Value = in.Value - if in.ValueFrom != nil { - in, out := in.ValueFrom, &out.ValueFrom - *out = new(EnvVarSource) - if err := DeepCopy_api_EnvVarSource(*in, *out, c); err != nil { - return err - } - } else { - out.ValueFrom = nil - } - return nil -} - -func DeepCopy_api_EnvVarSource(in EnvVarSource, out *EnvVarSource, c *conversion.Cloner) error { - if in.FieldRef != nil { - in, out := in.FieldRef, &out.FieldRef - *out = new(ObjectFieldSelector) - if err := DeepCopy_api_ObjectFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.FieldRef = nil - } - if in.ResourceFieldRef != nil { - in, out := in.ResourceFieldRef, &out.ResourceFieldRef - *out = new(ResourceFieldSelector) - if err := DeepCopy_api_ResourceFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceFieldRef = nil - } - if in.ConfigMapKeyRef != nil { - in, out := in.ConfigMapKeyRef, &out.ConfigMapKeyRef - *out = new(ConfigMapKeySelector) - if err := DeepCopy_api_ConfigMapKeySelector(*in, *out, c); err != nil { - return err - } - } else { - out.ConfigMapKeyRef = nil - } - if in.SecretKeyRef != nil { - in, out := in.SecretKeyRef, &out.SecretKeyRef - *out = new(SecretKeySelector) - if err := DeepCopy_api_SecretKeySelector(*in, *out, c); err != nil { - return err - } - } else { - out.SecretKeyRef = nil - } - return nil -} - -func DeepCopy_api_Event(in Event, out *Event, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectReference(in.InvolvedObject, &out.InvolvedObject, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - if err := DeepCopy_api_EventSource(in.Source, &out.Source, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.FirstTimestamp, &out.FirstTimestamp, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTimestamp, &out.LastTimestamp, c); err != nil { - return err - } - out.Count = in.Count - out.Type = in.Type - return nil -} - -func DeepCopy_api_EventList(in EventList, out *EventList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Event, len(in)) - for i := range in { - if err := DeepCopy_api_Event(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_EventSource(in EventSource, out *EventSource, c *conversion.Cloner) error { - out.Component = in.Component - out.Host = in.Host - return nil -} - -func DeepCopy_api_ExecAction(in ExecAction, out *ExecAction, c *conversion.Cloner) error { - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - return nil -} - -func DeepCopy_api_ExportOptions(in ExportOptions, out *ExportOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Export = in.Export - out.Exact = in.Exact - return nil -} - -func DeepCopy_api_FCVolumeSource(in FCVolumeSource, out *FCVolumeSource, c *conversion.Cloner) error { - if in.TargetWWNs != nil { - in, out := in.TargetWWNs, &out.TargetWWNs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.TargetWWNs = nil - } - if in.Lun != nil { - in, out := in.Lun, &out.Lun - *out = new(int32) - **out = *in - } else { - out.Lun = nil - } - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_FlexVolumeSource(in FlexVolumeSource, out *FlexVolumeSource, c *conversion.Cloner) error { - out.Driver = in.Driver - out.FSType = in.FSType - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - if in.Options != nil { - in, out := in.Options, &out.Options - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Options = nil - } - return nil -} - -func DeepCopy_api_FlockerVolumeSource(in FlockerVolumeSource, out *FlockerVolumeSource, c *conversion.Cloner) error { - out.DatasetName = in.DatasetName - return nil -} - -func DeepCopy_api_GCEPersistentDiskVolumeSource(in GCEPersistentDiskVolumeSource, out *GCEPersistentDiskVolumeSource, c *conversion.Cloner) error { - out.PDName = in.PDName - out.FSType = in.FSType - out.Partition = in.Partition - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_GitRepoVolumeSource(in GitRepoVolumeSource, out *GitRepoVolumeSource, c *conversion.Cloner) error { - out.Repository = in.Repository - out.Revision = in.Revision - out.Directory = in.Directory - return nil -} - -func DeepCopy_api_GlusterfsVolumeSource(in GlusterfsVolumeSource, out *GlusterfsVolumeSource, c *conversion.Cloner) error { - out.EndpointsName = in.EndpointsName - out.Path = in.Path - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_HTTPGetAction(in HTTPGetAction, out *HTTPGetAction, c *conversion.Cloner) error { - out.Path = in.Path - if err := intstr.DeepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { - return err - } - out.Host = in.Host - out.Scheme = in.Scheme - if in.HTTPHeaders != nil { - in, out := in.HTTPHeaders, &out.HTTPHeaders - *out = make([]HTTPHeader, len(in)) - for i := range in { - if err := DeepCopy_api_HTTPHeader(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.HTTPHeaders = nil - } - return nil -} - -func DeepCopy_api_HTTPHeader(in HTTPHeader, out *HTTPHeader, c *conversion.Cloner) error { - out.Name = in.Name - out.Value = in.Value - return nil -} - -func DeepCopy_api_Handler(in Handler, out *Handler, c *conversion.Cloner) error { - if in.Exec != nil { - in, out := in.Exec, &out.Exec - *out = new(ExecAction) - if err := DeepCopy_api_ExecAction(*in, *out, c); err != nil { - return err - } - } else { - out.Exec = nil - } - if in.HTTPGet != nil { - in, out := in.HTTPGet, &out.HTTPGet - *out = new(HTTPGetAction) - if err := DeepCopy_api_HTTPGetAction(*in, *out, c); err != nil { - return err - } - } else { - out.HTTPGet = nil - } - if in.TCPSocket != nil { - in, out := in.TCPSocket, &out.TCPSocket - *out = new(TCPSocketAction) - if err := DeepCopy_api_TCPSocketAction(*in, *out, c); err != nil { - return err - } - } else { - out.TCPSocket = nil - } - return nil -} - -func DeepCopy_api_HostPathVolumeSource(in HostPathVolumeSource, out *HostPathVolumeSource, c *conversion.Cloner) error { - out.Path = in.Path - return nil -} - -func DeepCopy_api_ISCSIVolumeSource(in ISCSIVolumeSource, out *ISCSIVolumeSource, c *conversion.Cloner) error { - out.TargetPortal = in.TargetPortal - out.IQN = in.IQN - out.Lun = in.Lun - out.ISCSIInterface = in.ISCSIInterface - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_KeyToPath(in KeyToPath, out *KeyToPath, c *conversion.Cloner) error { - out.Key = in.Key - out.Path = in.Path - return nil -} - -func DeepCopy_api_Lifecycle(in Lifecycle, out *Lifecycle, c *conversion.Cloner) error { - if in.PostStart != nil { - in, out := in.PostStart, &out.PostStart - *out = new(Handler) - if err := DeepCopy_api_Handler(*in, *out, c); err != nil { - return err - } - } else { - out.PostStart = nil - } - if in.PreStop != nil { - in, out := in.PreStop, &out.PreStop - *out = new(Handler) - if err := DeepCopy_api_Handler(*in, *out, c); err != nil { - return err - } - } else { - out.PreStop = nil - } - return nil -} - -func DeepCopy_api_LimitRange(in LimitRange, out *LimitRange, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_LimitRangeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_LimitRangeItem(in LimitRangeItem, out *LimitRangeItem, c *conversion.Cloner) error { - out.Type = in.Type - if in.Max != nil { - in, out := in.Max, &out.Max - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Max = nil - } - if in.Min != nil { - in, out := in.Min, &out.Min - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Min = nil - } - if in.Default != nil { - in, out := in.Default, &out.Default - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Default = nil - } - if in.DefaultRequest != nil { - in, out := in.DefaultRequest, &out.DefaultRequest - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.DefaultRequest = nil - } - if in.MaxLimitRequestRatio != nil { - in, out := in.MaxLimitRequestRatio, &out.MaxLimitRequestRatio - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.MaxLimitRequestRatio = nil - } - return nil -} - -func DeepCopy_api_LimitRangeList(in LimitRangeList, out *LimitRangeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]LimitRange, len(in)) - for i := range in { - if err := DeepCopy_api_LimitRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_LimitRangeSpec(in LimitRangeSpec, out *LimitRangeSpec, c *conversion.Cloner) error { - if in.Limits != nil { - in, out := in.Limits, &out.Limits - *out = make([]LimitRangeItem, len(in)) - for i := range in { - if err := DeepCopy_api_LimitRangeItem(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Limits = nil - } - return nil -} - -func DeepCopy_api_List(in List, out *List, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]runtime.Object, len(in)) - for i := range in { - if newVal, err := c.DeepCopy(in[i]); err != nil { - return err - } else { - (*out)[i] = newVal.(runtime.Object) - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ListOptions(in ListOptions, out *ListOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.LabelSelector == nil { - out.LabelSelector = nil - } else if newVal, err := c.DeepCopy(in.LabelSelector); err != nil { - return err - } else { - out.LabelSelector = newVal.(labels.Selector) - } - if in.FieldSelector == nil { - out.FieldSelector = nil - } else if newVal, err := c.DeepCopy(in.FieldSelector); err != nil { - return err - } else { - out.FieldSelector = newVal.(fields.Selector) - } - out.Watch = in.Watch - out.ResourceVersion = in.ResourceVersion - if in.TimeoutSeconds != nil { - in, out := in.TimeoutSeconds, &out.TimeoutSeconds - *out = new(int64) - **out = *in - } else { - out.TimeoutSeconds = nil - } - return nil -} - -func DeepCopy_api_LoadBalancerIngress(in LoadBalancerIngress, out *LoadBalancerIngress, c *conversion.Cloner) error { - out.IP = in.IP - out.Hostname = in.Hostname - return nil -} - -func DeepCopy_api_LoadBalancerStatus(in LoadBalancerStatus, out *LoadBalancerStatus, c *conversion.Cloner) error { - if in.Ingress != nil { - in, out := in.Ingress, &out.Ingress - *out = make([]LoadBalancerIngress, len(in)) - for i := range in { - if err := DeepCopy_api_LoadBalancerIngress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ingress = nil - } - return nil -} - -func DeepCopy_api_LocalObjectReference(in LocalObjectReference, out *LocalObjectReference, c *conversion.Cloner) error { - out.Name = in.Name - return nil -} - -func DeepCopy_api_NFSVolumeSource(in NFSVolumeSource, out *NFSVolumeSource, c *conversion.Cloner) error { - out.Server = in.Server - out.Path = in.Path - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_Namespace(in Namespace, out *Namespace, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_NamespaceSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_NamespaceStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_NamespaceList(in NamespaceList, out *NamespaceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Namespace, len(in)) - for i := range in { - if err := DeepCopy_api_Namespace(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_NamespaceSpec(in NamespaceSpec, out *NamespaceSpec, c *conversion.Cloner) error { - if in.Finalizers != nil { - in, out := in.Finalizers, &out.Finalizers - *out = make([]FinalizerName, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Finalizers = nil - } - return nil -} - -func DeepCopy_api_NamespaceStatus(in NamespaceStatus, out *NamespaceStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - return nil -} - -func DeepCopy_api_Node(in Node, out *Node, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_NodeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_NodeStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_NodeAddress(in NodeAddress, out *NodeAddress, c *conversion.Cloner) error { - out.Type = in.Type - out.Address = in.Address - return nil -} - -func DeepCopy_api_NodeAffinity(in NodeAffinity, out *NodeAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = new(NodeSelector) - if err := DeepCopy_api_NodeSelector(*in, *out, c); err != nil { - return err - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]PreferredSchedulingTerm, len(in)) - for i := range in { - if err := DeepCopy_api_PreferredSchedulingTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_api_NodeCondition(in NodeCondition, out *NodeCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastHeartbeatTime, &out.LastHeartbeatTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_api_NodeDaemonEndpoints(in NodeDaemonEndpoints, out *NodeDaemonEndpoints, c *conversion.Cloner) error { - if err := DeepCopy_api_DaemonEndpoint(in.KubeletEndpoint, &out.KubeletEndpoint, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_NodeList(in NodeList, out *NodeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Node, len(in)) - for i := range in { - if err := DeepCopy_api_Node(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_NodeProxyOptions(in NodeProxyOptions, out *NodeProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_api_NodeResources(in NodeResources, out *NodeResources, c *conversion.Cloner) error { - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - return nil -} - -func DeepCopy_api_NodeSelector(in NodeSelector, out *NodeSelector, c *conversion.Cloner) error { - if in.NodeSelectorTerms != nil { - in, out := in.NodeSelectorTerms, &out.NodeSelectorTerms - *out = make([]NodeSelectorTerm, len(in)) - for i := range in { - if err := DeepCopy_api_NodeSelectorTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.NodeSelectorTerms = nil - } - return nil -} - -func DeepCopy_api_NodeSelectorRequirement(in NodeSelectorRequirement, out *NodeSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} - -func DeepCopy_api_NodeSelectorTerm(in NodeSelectorTerm, out *NodeSelectorTerm, c *conversion.Cloner) error { - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]NodeSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_api_NodeSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_api_NodeSpec(in NodeSpec, out *NodeSpec, c *conversion.Cloner) error { - out.PodCIDR = in.PodCIDR - out.ExternalID = in.ExternalID - out.ProviderID = in.ProviderID - out.Unschedulable = in.Unschedulable - return nil -} - -func DeepCopy_api_NodeStatus(in NodeStatus, out *NodeStatus, c *conversion.Cloner) error { - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - if in.Allocatable != nil { - in, out := in.Allocatable, &out.Allocatable - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Allocatable = nil - } - out.Phase = in.Phase - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]NodeCondition, len(in)) - for i := range in { - if err := DeepCopy_api_NodeCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.Addresses != nil { - in, out := in.Addresses, &out.Addresses - *out = make([]NodeAddress, len(in)) - for i := range in { - if err := DeepCopy_api_NodeAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Addresses = nil - } - if err := DeepCopy_api_NodeDaemonEndpoints(in.DaemonEndpoints, &out.DaemonEndpoints, c); err != nil { - return err - } - if err := DeepCopy_api_NodeSystemInfo(in.NodeInfo, &out.NodeInfo, c); err != nil { - return err - } - if in.Images != nil { - in, out := in.Images, &out.Images - *out = make([]ContainerImage, len(in)) - for i := range in { - if err := DeepCopy_api_ContainerImage(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Images = nil - } - if in.VolumesInUse != nil { - in, out := in.VolumesInUse, &out.VolumesInUse - *out = make([]UniqueVolumeName, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.VolumesInUse = nil - } - if in.VolumesAttached != nil { - in, out := in.VolumesAttached, &out.VolumesAttached - *out = make([]AttachedVolume, len(in)) - for i := range in { - if err := DeepCopy_api_AttachedVolume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumesAttached = nil - } - return nil -} - -func DeepCopy_api_NodeSystemInfo(in NodeSystemInfo, out *NodeSystemInfo, c *conversion.Cloner) error { - out.MachineID = in.MachineID - out.SystemUUID = in.SystemUUID - out.BootID = in.BootID - out.KernelVersion = in.KernelVersion - out.OSImage = in.OSImage - out.ContainerRuntimeVersion = in.ContainerRuntimeVersion - out.KubeletVersion = in.KubeletVersion - out.KubeProxyVersion = in.KubeProxyVersion - out.OperatingSystem = in.OperatingSystem - out.Architecture = in.Architecture - return nil -} - -func DeepCopy_api_ObjectFieldSelector(in ObjectFieldSelector, out *ObjectFieldSelector, c *conversion.Cloner) error { - out.APIVersion = in.APIVersion - out.FieldPath = in.FieldPath - return nil -} - -func DeepCopy_api_ObjectMeta(in ObjectMeta, out *ObjectMeta, c *conversion.Cloner) error { - out.Name = in.Name - out.GenerateName = in.GenerateName - out.Namespace = in.Namespace - out.SelfLink = in.SelfLink - out.UID = in.UID - out.ResourceVersion = in.ResourceVersion - out.Generation = in.Generation - if err := unversioned.DeepCopy_unversioned_Time(in.CreationTimestamp, &out.CreationTimestamp, c); err != nil { - return err - } - if in.DeletionTimestamp != nil { - in, out := in.DeletionTimestamp, &out.DeletionTimestamp - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.DeletionTimestamp = nil - } - if in.DeletionGracePeriodSeconds != nil { - in, out := in.DeletionGracePeriodSeconds, &out.DeletionGracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.DeletionGracePeriodSeconds = nil - } - if in.Labels != nil { - in, out := in.Labels, &out.Labels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Labels = nil - } - if in.Annotations != nil { - in, out := in.Annotations, &out.Annotations - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Annotations = nil - } - if in.OwnerReferences != nil { - in, out := in.OwnerReferences, &out.OwnerReferences - *out = make([]OwnerReference, len(in)) - for i := range in { - if err := DeepCopy_api_OwnerReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.OwnerReferences = nil - } - if in.Finalizers != nil { - in, out := in.Finalizers, &out.Finalizers - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Finalizers = nil - } - return nil -} - -func DeepCopy_api_ObjectReference(in ObjectReference, out *ObjectReference, c *conversion.Cloner) error { - out.Kind = in.Kind - out.Namespace = in.Namespace - out.Name = in.Name - out.UID = in.UID - out.APIVersion = in.APIVersion - out.ResourceVersion = in.ResourceVersion - out.FieldPath = in.FieldPath - return nil -} - -func DeepCopy_api_OwnerReference(in OwnerReference, out *OwnerReference, c *conversion.Cloner) error { - out.APIVersion = in.APIVersion - out.Kind = in.Kind - out.Name = in.Name - out.UID = in.UID - if in.Controller != nil { - in, out := in.Controller, &out.Controller - *out = new(bool) - **out = *in - } else { - out.Controller = nil - } - return nil -} - -func DeepCopy_api_PersistentVolume(in PersistentVolume, out *PersistentVolume, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PersistentVolumeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_PersistentVolumeStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_PersistentVolumeClaim(in PersistentVolumeClaim, out *PersistentVolumeClaim, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PersistentVolumeClaimSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_PersistentVolumeClaimStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_PersistentVolumeClaimList(in PersistentVolumeClaimList, out *PersistentVolumeClaimList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PersistentVolumeClaim, len(in)) - for i := range in { - if err := DeepCopy_api_PersistentVolumeClaim(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_PersistentVolumeClaimSpec(in PersistentVolumeClaimSpec, out *PersistentVolumeClaimSpec, c *conversion.Cloner) error { - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := DeepCopy_api_ResourceRequirements(in.Resources, &out.Resources, c); err != nil { - return err - } - out.VolumeName = in.VolumeName - return nil -} - -func DeepCopy_api_PersistentVolumeClaimStatus(in PersistentVolumeClaimStatus, out *PersistentVolumeClaimStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - return nil -} - -func DeepCopy_api_PersistentVolumeClaimVolumeSource(in PersistentVolumeClaimVolumeSource, out *PersistentVolumeClaimVolumeSource, c *conversion.Cloner) error { - out.ClaimName = in.ClaimName - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_PersistentVolumeList(in PersistentVolumeList, out *PersistentVolumeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PersistentVolume, len(in)) - for i := range in { - if err := DeepCopy_api_PersistentVolume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_PersistentVolumeSource(in PersistentVolumeSource, out *PersistentVolumeSource, c *conversion.Cloner) error { - if in.GCEPersistentDisk != nil { - in, out := in.GCEPersistentDisk, &out.GCEPersistentDisk - *out = new(GCEPersistentDiskVolumeSource) - if err := DeepCopy_api_GCEPersistentDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GCEPersistentDisk = nil - } - if in.AWSElasticBlockStore != nil { - in, out := in.AWSElasticBlockStore, &out.AWSElasticBlockStore - *out = new(AWSElasticBlockStoreVolumeSource) - if err := DeepCopy_api_AWSElasticBlockStoreVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AWSElasticBlockStore = nil - } - if in.HostPath != nil { - in, out := in.HostPath, &out.HostPath - *out = new(HostPathVolumeSource) - if err := DeepCopy_api_HostPathVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.HostPath = nil - } - if in.Glusterfs != nil { - in, out := in.Glusterfs, &out.Glusterfs - *out = new(GlusterfsVolumeSource) - if err := DeepCopy_api_GlusterfsVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Glusterfs = nil - } - if in.NFS != nil { - in, out := in.NFS, &out.NFS - *out = new(NFSVolumeSource) - if err := DeepCopy_api_NFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.NFS = nil - } - if in.RBD != nil { - in, out := in.RBD, &out.RBD - *out = new(RBDVolumeSource) - if err := DeepCopy_api_RBDVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.RBD = nil - } - if in.ISCSI != nil { - in, out := in.ISCSI, &out.ISCSI - *out = new(ISCSIVolumeSource) - if err := DeepCopy_api_ISCSIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ISCSI = nil - } - if in.FlexVolume != nil { - in, out := in.FlexVolume, &out.FlexVolume - *out = new(FlexVolumeSource) - if err := DeepCopy_api_FlexVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FlexVolume = nil - } - if in.Cinder != nil { - in, out := in.Cinder, &out.Cinder - *out = new(CinderVolumeSource) - if err := DeepCopy_api_CinderVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Cinder = nil - } - if in.CephFS != nil { - in, out := in.CephFS, &out.CephFS - *out = new(CephFSVolumeSource) - if err := DeepCopy_api_CephFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.CephFS = nil - } - if in.FC != nil { - in, out := in.FC, &out.FC - *out = new(FCVolumeSource) - if err := DeepCopy_api_FCVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FC = nil - } - if in.Flocker != nil { - in, out := in.Flocker, &out.Flocker - *out = new(FlockerVolumeSource) - if err := DeepCopy_api_FlockerVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Flocker = nil - } - if in.AzureFile != nil { - in, out := in.AzureFile, &out.AzureFile - *out = new(AzureFileVolumeSource) - if err := DeepCopy_api_AzureFileVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AzureFile = nil - } - if in.VsphereVolume != nil { - in, out := in.VsphereVolume, &out.VsphereVolume - *out = new(VsphereVirtualDiskVolumeSource) - if err := DeepCopy_api_VsphereVirtualDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.VsphereVolume = nil - } - return nil -} - -func DeepCopy_api_PersistentVolumeSpec(in PersistentVolumeSpec, out *PersistentVolumeSpec, c *conversion.Cloner) error { - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - if err := DeepCopy_api_PersistentVolumeSource(in.PersistentVolumeSource, &out.PersistentVolumeSource, c); err != nil { - return err - } - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.ClaimRef != nil { - in, out := in.ClaimRef, &out.ClaimRef - *out = new(ObjectReference) - if err := DeepCopy_api_ObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.ClaimRef = nil - } - out.PersistentVolumeReclaimPolicy = in.PersistentVolumeReclaimPolicy - return nil -} - -func DeepCopy_api_PersistentVolumeStatus(in PersistentVolumeStatus, out *PersistentVolumeStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - out.Message = in.Message - out.Reason = in.Reason - return nil -} - -func DeepCopy_api_Pod(in Pod, out *Pod, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PodSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_PodStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_PodAffinity(in PodAffinity, out *PodAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = make([]PodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_api_PodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]WeightedPodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_api_WeightedPodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_api_PodAffinityTerm(in PodAffinityTerm, out *PodAffinityTerm, c *conversion.Cloner) error { - if in.LabelSelector != nil { - in, out := in.LabelSelector, &out.LabelSelector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.LabelSelector = nil - } - if in.Namespaces != nil { - in, out := in.Namespaces, &out.Namespaces - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Namespaces = nil - } - out.TopologyKey = in.TopologyKey - return nil -} - -func DeepCopy_api_PodAntiAffinity(in PodAntiAffinity, out *PodAntiAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = make([]PodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_api_PodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]WeightedPodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_api_WeightedPodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_api_PodAttachOptions(in PodAttachOptions, out *PodAttachOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Stdin = in.Stdin - out.Stdout = in.Stdout - out.Stderr = in.Stderr - out.TTY = in.TTY - out.Container = in.Container - return nil -} - -func DeepCopy_api_PodCondition(in PodCondition, out *PodCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_api_PodExecOptions(in PodExecOptions, out *PodExecOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Stdin = in.Stdin - out.Stdout = in.Stdout - out.Stderr = in.Stderr - out.TTY = in.TTY - out.Container = in.Container - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - return nil -} - -func DeepCopy_api_PodList(in PodList, out *PodList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Pod, len(in)) - for i := range in { - if err := DeepCopy_api_Pod(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_PodLogOptions(in PodLogOptions, out *PodLogOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Container = in.Container - out.Follow = in.Follow - out.Previous = in.Previous - if in.SinceSeconds != nil { - in, out := in.SinceSeconds, &out.SinceSeconds - *out = new(int64) - **out = *in - } else { - out.SinceSeconds = nil - } - if in.SinceTime != nil { - in, out := in.SinceTime, &out.SinceTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.SinceTime = nil - } - out.Timestamps = in.Timestamps - if in.TailLines != nil { - in, out := in.TailLines, &out.TailLines - *out = new(int64) - **out = *in - } else { - out.TailLines = nil - } - if in.LimitBytes != nil { - in, out := in.LimitBytes, &out.LimitBytes - *out = new(int64) - **out = *in - } else { - out.LimitBytes = nil - } - return nil -} - -func DeepCopy_api_PodProxyOptions(in PodProxyOptions, out *PodProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_api_PodSecurityContext(in PodSecurityContext, out *PodSecurityContext, c *conversion.Cloner) error { - out.HostNetwork = in.HostNetwork - out.HostPID = in.HostPID - out.HostIPC = in.HostIPC - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(SELinuxOptions) - if err := DeepCopy_api_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - if in.RunAsUser != nil { - in, out := in.RunAsUser, &out.RunAsUser - *out = new(int64) - **out = *in - } else { - out.RunAsUser = nil - } - if in.RunAsNonRoot != nil { - in, out := in.RunAsNonRoot, &out.RunAsNonRoot - *out = new(bool) - **out = *in - } else { - out.RunAsNonRoot = nil - } - if in.SupplementalGroups != nil { - in, out := in.SupplementalGroups, &out.SupplementalGroups - *out = make([]int64, len(in)) - copy(*out, in) - } else { - out.SupplementalGroups = nil - } - if in.FSGroup != nil { - in, out := in.FSGroup, &out.FSGroup - *out = new(int64) - **out = *in - } else { - out.FSGroup = nil - } - return nil -} - -func DeepCopy_api_PodSpec(in PodSpec, out *PodSpec, c *conversion.Cloner) error { - if in.Volumes != nil { - in, out := in.Volumes, &out.Volumes - *out = make([]Volume, len(in)) - for i := range in { - if err := DeepCopy_api_Volume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Volumes = nil - } - if in.InitContainers != nil { - in, out := in.InitContainers, &out.InitContainers - *out = make([]Container, len(in)) - for i := range in { - if err := DeepCopy_api_Container(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.InitContainers = nil - } - if in.Containers != nil { - in, out := in.Containers, &out.Containers - *out = make([]Container, len(in)) - for i := range in { - if err := DeepCopy_api_Container(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Containers = nil - } - out.RestartPolicy = in.RestartPolicy - if in.TerminationGracePeriodSeconds != nil { - in, out := in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.TerminationGracePeriodSeconds = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - out.DNSPolicy = in.DNSPolicy - if in.NodeSelector != nil { - in, out := in.NodeSelector, &out.NodeSelector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.NodeSelector = nil - } - out.ServiceAccountName = in.ServiceAccountName - out.NodeName = in.NodeName - if in.SecurityContext != nil { - in, out := in.SecurityContext, &out.SecurityContext - *out = new(PodSecurityContext) - if err := DeepCopy_api_PodSecurityContext(*in, *out, c); err != nil { - return err - } - } else { - out.SecurityContext = nil - } - if in.ImagePullSecrets != nil { - in, out := in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]LocalObjectReference, len(in)) - for i := range in { - if err := DeepCopy_api_LocalObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - out.Hostname = in.Hostname - out.Subdomain = in.Subdomain - return nil -} - -func DeepCopy_api_PodStatus(in PodStatus, out *PodStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]PodCondition, len(in)) - for i := range in { - if err := DeepCopy_api_PodCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - out.Message = in.Message - out.Reason = in.Reason - out.HostIP = in.HostIP - out.PodIP = in.PodIP - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.InitContainerStatuses != nil { - in, out := in.InitContainerStatuses, &out.InitContainerStatuses - *out = make([]ContainerStatus, len(in)) - for i := range in { - if err := DeepCopy_api_ContainerStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.InitContainerStatuses = nil - } - if in.ContainerStatuses != nil { - in, out := in.ContainerStatuses, &out.ContainerStatuses - *out = make([]ContainerStatus, len(in)) - for i := range in { - if err := DeepCopy_api_ContainerStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ContainerStatuses = nil - } - return nil -} - -func DeepCopy_api_PodStatusResult(in PodStatusResult, out *PodStatusResult, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PodStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_PodTemplate(in PodTemplate, out *PodTemplate, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_PodTemplateList(in PodTemplateList, out *PodTemplateList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodTemplate, len(in)) - for i := range in { - if err := DeepCopy_api_PodTemplate(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_PodTemplateSpec(in PodTemplateSpec, out *PodTemplateSpec, c *conversion.Cloner) error { - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_PodSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_Preconditions(in Preconditions, out *Preconditions, c *conversion.Cloner) error { - if in.UID != nil { - in, out := in.UID, &out.UID - *out = new(types.UID) - **out = *in - } else { - out.UID = nil - } - return nil -} - -func DeepCopy_api_PreferredSchedulingTerm(in PreferredSchedulingTerm, out *PreferredSchedulingTerm, c *conversion.Cloner) error { - out.Weight = in.Weight - if err := DeepCopy_api_NodeSelectorTerm(in.Preference, &out.Preference, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_Probe(in Probe, out *Probe, c *conversion.Cloner) error { - if err := DeepCopy_api_Handler(in.Handler, &out.Handler, c); err != nil { - return err - } - out.InitialDelaySeconds = in.InitialDelaySeconds - out.TimeoutSeconds = in.TimeoutSeconds - out.PeriodSeconds = in.PeriodSeconds - out.SuccessThreshold = in.SuccessThreshold - out.FailureThreshold = in.FailureThreshold - return nil -} - -func DeepCopy_api_RBDVolumeSource(in RBDVolumeSource, out *RBDVolumeSource, c *conversion.Cloner) error { - if in.CephMonitors != nil { - in, out := in.CephMonitors, &out.CephMonitors - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.CephMonitors = nil - } - out.RBDImage = in.RBDImage - out.FSType = in.FSType - out.RBDPool = in.RBDPool - out.RadosUser = in.RadosUser - out.Keyring = in.Keyring - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_api_RangeAllocation(in RangeAllocation, out *RangeAllocation, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - out.Range = in.Range - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_api_ReplicationController(in ReplicationController, out *ReplicationController, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ReplicationControllerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_ReplicationControllerStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_ReplicationControllerList(in ReplicationControllerList, out *ReplicationControllerList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ReplicationController, len(in)) - for i := range in { - if err := DeepCopy_api_ReplicationController(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ReplicationControllerSpec(in ReplicationControllerSpec, out *ReplicationControllerSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Selector = nil - } - if in.Template != nil { - in, out := in.Template, &out.Template - *out = new(PodTemplateSpec) - if err := DeepCopy_api_PodTemplateSpec(*in, *out, c); err != nil { - return err - } - } else { - out.Template = nil - } - return nil -} - -func DeepCopy_api_ReplicationControllerStatus(in ReplicationControllerStatus, out *ReplicationControllerStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.FullyLabeledReplicas = in.FullyLabeledReplicas - out.ObservedGeneration = in.ObservedGeneration - return nil -} - -func DeepCopy_api_ResourceFieldSelector(in ResourceFieldSelector, out *ResourceFieldSelector, c *conversion.Cloner) error { - out.ContainerName = in.ContainerName - out.Resource = in.Resource - if err := resource.DeepCopy_resource_Quantity(in.Divisor, &out.Divisor, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_ResourceQuota(in ResourceQuota, out *ResourceQuota, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ResourceQuotaSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_ResourceQuotaStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_ResourceQuotaList(in ResourceQuotaList, out *ResourceQuotaList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ResourceQuota, len(in)) - for i := range in { - if err := DeepCopy_api_ResourceQuota(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ResourceQuotaSpec(in ResourceQuotaSpec, out *ResourceQuotaSpec, c *conversion.Cloner) error { - if in.Hard != nil { - in, out := in.Hard, &out.Hard - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Hard = nil - } - if in.Scopes != nil { - in, out := in.Scopes, &out.Scopes - *out = make([]ResourceQuotaScope, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Scopes = nil - } - return nil -} - -func DeepCopy_api_ResourceQuotaStatus(in ResourceQuotaStatus, out *ResourceQuotaStatus, c *conversion.Cloner) error { - if in.Hard != nil { - in, out := in.Hard, &out.Hard - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Hard = nil - } - if in.Used != nil { - in, out := in.Used, &out.Used - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Used = nil - } - return nil -} - -func DeepCopy_api_ResourceRequirements(in ResourceRequirements, out *ResourceRequirements, c *conversion.Cloner) error { - if in.Limits != nil { - in, out := in.Limits, &out.Limits - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Limits = nil - } - if in.Requests != nil { - in, out := in.Requests, &out.Requests - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Requests = nil - } - return nil -} - -func DeepCopy_api_SELinuxOptions(in SELinuxOptions, out *SELinuxOptions, c *conversion.Cloner) error { - out.User = in.User - out.Role = in.Role - out.Type = in.Type - out.Level = in.Level - return nil -} - -func DeepCopy_api_Secret(in Secret, out *Secret, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make(map[string][]byte) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]byte) - } - } - } else { - out.Data = nil - } - out.Type = in.Type - return nil -} - -func DeepCopy_api_SecretKeySelector(in SecretKeySelector, out *SecretKeySelector, c *conversion.Cloner) error { - if err := DeepCopy_api_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - out.Key = in.Key - return nil -} - -func DeepCopy_api_SecretList(in SecretList, out *SecretList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Secret, len(in)) - for i := range in { - if err := DeepCopy_api_Secret(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_SecretVolumeSource(in SecretVolumeSource, out *SecretVolumeSource, c *conversion.Cloner) error { - out.SecretName = in.SecretName - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]KeyToPath, len(in)) - for i := range in { - if err := DeepCopy_api_KeyToPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_SecurityContext(in SecurityContext, out *SecurityContext, c *conversion.Cloner) error { - if in.Capabilities != nil { - in, out := in.Capabilities, &out.Capabilities - *out = new(Capabilities) - if err := DeepCopy_api_Capabilities(*in, *out, c); err != nil { - return err - } - } else { - out.Capabilities = nil - } - if in.Privileged != nil { - in, out := in.Privileged, &out.Privileged - *out = new(bool) - **out = *in - } else { - out.Privileged = nil - } - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(SELinuxOptions) - if err := DeepCopy_api_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - if in.RunAsUser != nil { - in, out := in.RunAsUser, &out.RunAsUser - *out = new(int64) - **out = *in - } else { - out.RunAsUser = nil - } - if in.RunAsNonRoot != nil { - in, out := in.RunAsNonRoot, &out.RunAsNonRoot - *out = new(bool) - **out = *in - } else { - out.RunAsNonRoot = nil - } - if in.ReadOnlyRootFilesystem != nil { - in, out := in.ReadOnlyRootFilesystem, &out.ReadOnlyRootFilesystem - *out = new(bool) - **out = *in - } else { - out.ReadOnlyRootFilesystem = nil - } - return nil -} - -func DeepCopy_api_SerializedReference(in SerializedReference, out *SerializedReference, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectReference(in.Reference, &out.Reference, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_Service(in Service, out *Service, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ServiceSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_api_ServiceStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_ServiceAccount(in ServiceAccount, out *ServiceAccount, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Secrets != nil { - in, out := in.Secrets, &out.Secrets - *out = make([]ObjectReference, len(in)) - for i := range in { - if err := DeepCopy_api_ObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Secrets = nil - } - if in.ImagePullSecrets != nil { - in, out := in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]LocalObjectReference, len(in)) - for i := range in { - if err := DeepCopy_api_LocalObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - return nil -} - -func DeepCopy_api_ServiceAccountList(in ServiceAccountList, out *ServiceAccountList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ServiceAccount, len(in)) - for i := range in { - if err := DeepCopy_api_ServiceAccount(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ServiceList(in ServiceList, out *ServiceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Service, len(in)) - for i := range in { - if err := DeepCopy_api_Service(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_api_ServicePort(in ServicePort, out *ServicePort, c *conversion.Cloner) error { - out.Name = in.Name - out.Protocol = in.Protocol - out.Port = in.Port - if err := intstr.DeepCopy_intstr_IntOrString(in.TargetPort, &out.TargetPort, c); err != nil { - return err - } - out.NodePort = in.NodePort - return nil -} - -func DeepCopy_api_ServiceProxyOptions(in ServiceProxyOptions, out *ServiceProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_api_ServiceSpec(in ServiceSpec, out *ServiceSpec, c *conversion.Cloner) error { - out.Type = in.Type - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]ServicePort, len(in)) - for i := range in { - if err := DeepCopy_api_ServicePort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Selector = nil - } - out.ClusterIP = in.ClusterIP - if in.ExternalIPs != nil { - in, out := in.ExternalIPs, &out.ExternalIPs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.ExternalIPs = nil - } - out.LoadBalancerIP = in.LoadBalancerIP - out.SessionAffinity = in.SessionAffinity - if in.LoadBalancerSourceRanges != nil { - in, out := in.LoadBalancerSourceRanges, &out.LoadBalancerSourceRanges - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.LoadBalancerSourceRanges = nil - } - return nil -} - -func DeepCopy_api_ServiceStatus(in ServiceStatus, out *ServiceStatus, c *conversion.Cloner) error { - if err := DeepCopy_api_LoadBalancerStatus(in.LoadBalancer, &out.LoadBalancer, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_TCPSocketAction(in TCPSocketAction, out *TCPSocketAction, c *conversion.Cloner) error { - if err := intstr.DeepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_Taint(in Taint, out *Taint, c *conversion.Cloner) error { - out.Key = in.Key - out.Value = in.Value - out.Effect = in.Effect - return nil -} - -func DeepCopy_api_Toleration(in Toleration, out *Toleration, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - out.Value = in.Value - out.Effect = in.Effect - return nil -} - -func DeepCopy_api_Volume(in Volume, out *Volume, c *conversion.Cloner) error { - out.Name = in.Name - if err := DeepCopy_api_VolumeSource(in.VolumeSource, &out.VolumeSource, c); err != nil { - return err - } - return nil -} - -func DeepCopy_api_VolumeMount(in VolumeMount, out *VolumeMount, c *conversion.Cloner) error { - out.Name = in.Name - out.ReadOnly = in.ReadOnly - out.MountPath = in.MountPath - out.SubPath = in.SubPath - return nil -} - -func DeepCopy_api_VolumeSource(in VolumeSource, out *VolumeSource, c *conversion.Cloner) error { - if in.HostPath != nil { - in, out := in.HostPath, &out.HostPath - *out = new(HostPathVolumeSource) - if err := DeepCopy_api_HostPathVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.HostPath = nil - } - if in.EmptyDir != nil { - in, out := in.EmptyDir, &out.EmptyDir - *out = new(EmptyDirVolumeSource) - if err := DeepCopy_api_EmptyDirVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.EmptyDir = nil - } - if in.GCEPersistentDisk != nil { - in, out := in.GCEPersistentDisk, &out.GCEPersistentDisk - *out = new(GCEPersistentDiskVolumeSource) - if err := DeepCopy_api_GCEPersistentDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GCEPersistentDisk = nil - } - if in.AWSElasticBlockStore != nil { - in, out := in.AWSElasticBlockStore, &out.AWSElasticBlockStore - *out = new(AWSElasticBlockStoreVolumeSource) - if err := DeepCopy_api_AWSElasticBlockStoreVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AWSElasticBlockStore = nil - } - if in.GitRepo != nil { - in, out := in.GitRepo, &out.GitRepo - *out = new(GitRepoVolumeSource) - if err := DeepCopy_api_GitRepoVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GitRepo = nil - } - if in.Secret != nil { - in, out := in.Secret, &out.Secret - *out = new(SecretVolumeSource) - if err := DeepCopy_api_SecretVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Secret = nil - } - if in.NFS != nil { - in, out := in.NFS, &out.NFS - *out = new(NFSVolumeSource) - if err := DeepCopy_api_NFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.NFS = nil - } - if in.ISCSI != nil { - in, out := in.ISCSI, &out.ISCSI - *out = new(ISCSIVolumeSource) - if err := DeepCopy_api_ISCSIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ISCSI = nil - } - if in.Glusterfs != nil { - in, out := in.Glusterfs, &out.Glusterfs - *out = new(GlusterfsVolumeSource) - if err := DeepCopy_api_GlusterfsVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Glusterfs = nil - } - if in.PersistentVolumeClaim != nil { - in, out := in.PersistentVolumeClaim, &out.PersistentVolumeClaim - *out = new(PersistentVolumeClaimVolumeSource) - if err := DeepCopy_api_PersistentVolumeClaimVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.PersistentVolumeClaim = nil - } - if in.RBD != nil { - in, out := in.RBD, &out.RBD - *out = new(RBDVolumeSource) - if err := DeepCopy_api_RBDVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.RBD = nil - } - if in.FlexVolume != nil { - in, out := in.FlexVolume, &out.FlexVolume - *out = new(FlexVolumeSource) - if err := DeepCopy_api_FlexVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FlexVolume = nil - } - if in.Cinder != nil { - in, out := in.Cinder, &out.Cinder - *out = new(CinderVolumeSource) - if err := DeepCopy_api_CinderVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Cinder = nil - } - if in.CephFS != nil { - in, out := in.CephFS, &out.CephFS - *out = new(CephFSVolumeSource) - if err := DeepCopy_api_CephFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.CephFS = nil - } - if in.Flocker != nil { - in, out := in.Flocker, &out.Flocker - *out = new(FlockerVolumeSource) - if err := DeepCopy_api_FlockerVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Flocker = nil - } - if in.DownwardAPI != nil { - in, out := in.DownwardAPI, &out.DownwardAPI - *out = new(DownwardAPIVolumeSource) - if err := DeepCopy_api_DownwardAPIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.DownwardAPI = nil - } - if in.FC != nil { - in, out := in.FC, &out.FC - *out = new(FCVolumeSource) - if err := DeepCopy_api_FCVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FC = nil - } - if in.AzureFile != nil { - in, out := in.AzureFile, &out.AzureFile - *out = new(AzureFileVolumeSource) - if err := DeepCopy_api_AzureFileVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AzureFile = nil - } - if in.ConfigMap != nil { - in, out := in.ConfigMap, &out.ConfigMap - *out = new(ConfigMapVolumeSource) - if err := DeepCopy_api_ConfigMapVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ConfigMap = nil - } - if in.VsphereVolume != nil { - in, out := in.VsphereVolume, &out.VsphereVolume - *out = new(VsphereVirtualDiskVolumeSource) - if err := DeepCopy_api_VsphereVirtualDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.VsphereVolume = nil - } - return nil -} - -func DeepCopy_api_VsphereVirtualDiskVolumeSource(in VsphereVirtualDiskVolumeSource, out *VsphereVirtualDiskVolumeSource, c *conversion.Cloner) error { - out.VolumePath = in.VolumePath - out.FSType = in.FSType - return nil -} - -func DeepCopy_api_WeightedPodAffinityTerm(in WeightedPodAffinityTerm, out *WeightedPodAffinityTerm, c *conversion.Cloner) error { - out.Weight = in.Weight - if err := DeepCopy_api_PodAffinityTerm(in.PodAffinityTerm, &out.PodAffinityTerm, c); err != nil { - return err - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/doc.go b/vendor/k8s.io/kubernetes/pkg/api/doc.go index 8a54f7acc69c..1507a8823b4c 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// +k8s:deepcopy-gen=package,register + // Package api contains the latest (or "internal") version of the // Kubernetes API objects. This is the API objects as represented in memory. // The contract presented to clients is located in the versioned packages, diff --git a/vendor/k8s.io/kubernetes/pkg/api/endpoints/util.go b/vendor/k8s.io/kubernetes/pkg/api/endpoints/util.go index 501d58f28538..792a2536fef9 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/endpoints/util.go +++ b/vendor/k8s.io/kubernetes/pkg/api/endpoints/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/errors/doc.go b/vendor/k8s.io/kubernetes/pkg/api/errors/doc.go index 3a2eb2a0a735..58751ed0ec87 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/errors/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/errors/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/errors/errors.go b/vendor/k8s.io/kubernetes/pkg/api/errors/errors.go index 89e83c2e3a6c..a51fe9414693 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/errors/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/api/errors/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/errors/storage/doc.go b/vendor/k8s.io/kubernetes/pkg/api/errors/storage/doc.go index a2a550526c97..4c2601195466 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/errors/storage/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/errors/storage/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/errors/storage/storage.go b/vendor/k8s.io/kubernetes/pkg/api/errors/storage/storage.go index 2a22b4f1716b..7f84cfcbc497 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/errors/storage/storage.go +++ b/vendor/k8s.io/kubernetes/pkg/api/errors/storage/storage.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ func InterpretCreateError(err error, qualifiedResource unversioned.GroupResource // operation into the appropriate API error. func InterpretUpdateError(err error, qualifiedResource unversioned.GroupResource, name string) error { switch { - case storage.IsTestFailed(err), storage.IsNodeExist(err): + case storage.IsTestFailed(err), storage.IsNodeExist(err), storage.IsInvalidObj(err): return errors.NewConflict(qualifiedResource, name, err) case storage.IsUnreachable(err): return errors.NewServerTimeout(qualifiedResource, "update", 2) // TODO: make configurable or handled at a higher level @@ -86,7 +86,7 @@ func InterpretDeleteError(err error, qualifiedResource unversioned.GroupResource return errors.NewNotFound(qualifiedResource, name) case storage.IsUnreachable(err): return errors.NewServerTimeout(qualifiedResource, "delete", 2) // TODO: make configurable or handled at a higher level - case storage.IsTestFailed(err), storage.IsNodeExist(err): + case storage.IsTestFailed(err), storage.IsNodeExist(err), storage.IsInvalidObj(err): return errors.NewConflict(qualifiedResource, name, err) case storage.IsInternalError(err): return errors.NewInternalError(err) diff --git a/vendor/k8s.io/kubernetes/pkg/api/field_constants.go b/vendor/k8s.io/kubernetes/pkg/api/field_constants.go index 94a825caf288..5ead0f13feb8 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/field_constants.go +++ b/vendor/k8s.io/kubernetes/pkg/api/field_constants.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/generate.go b/vendor/k8s.io/kubernetes/pkg/api/generate.go index 2cca5e52fcbe..19379d301e2a 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/generate.go +++ b/vendor/k8s.io/kubernetes/pkg/api/generate.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/helpers.go b/vendor/k8s.io/kubernetes/pkg/api/helpers.go index 1349ef62b0bb..08245e500690 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/api/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -424,19 +424,28 @@ const ( // SeccompContainerAnnotationKeyPrefix represents the key of a seccomp profile applied // to one container of a pod. SeccompContainerAnnotationKeyPrefix string = "container.seccomp.security.alpha.kubernetes.io/" + + // CreatedByAnnotation represents the key used to store the spec(json) + // used to create the resource. + CreatedByAnnotation = "kubernetes.io/created-by" + + // PreferAvoidPodsAnnotationKey represents the key of preferAvoidPods data (json serialized) + // in the Annotations of a Node. + PreferAvoidPodsAnnotationKey string = "scheduler.alpha.kubernetes.io/preferAvoidPods" ) // GetAffinityFromPod gets the json serialized affinity data from Pod.Annotations // and converts it to the Affinity type in api. -func GetAffinityFromPodAnnotations(annotations map[string]string) (Affinity, error) { - var affinity Affinity +func GetAffinityFromPodAnnotations(annotations map[string]string) (*Affinity, error) { if len(annotations) > 0 && annotations[AffinityAnnotationKey] != "" { + var affinity Affinity err := json.Unmarshal([]byte(annotations[AffinityAnnotationKey]), &affinity) if err != nil { - return affinity, err + return nil, err } + return &affinity, nil } - return affinity, nil + return nil, nil } // GetTolerationsFromPodAnnotations gets the json serialized tolerations data from Pod.Annotations @@ -466,7 +475,7 @@ func GetTaintsFromNodeAnnotations(annotations map[string]string) ([]Taint, error } // TolerationToleratesTaint checks if the toleration tolerates the taint. -func TolerationToleratesTaint(toleration Toleration, taint Taint) bool { +func TolerationToleratesTaint(toleration *Toleration, taint *Taint) bool { if len(toleration.Effect) != 0 && toleration.Effect != taint.Effect { return false } @@ -486,13 +495,24 @@ func TolerationToleratesTaint(toleration Toleration, taint Taint) bool { } // TaintToleratedByTolerations checks if taint is tolerated by any of the tolerations. -func TaintToleratedByTolerations(taint Taint, tolerations []Toleration) bool { +func TaintToleratedByTolerations(taint *Taint, tolerations []Toleration) bool { tolerated := false - for _, toleration := range tolerations { - if TolerationToleratesTaint(toleration, taint) { + for i := range tolerations { + if TolerationToleratesTaint(&tolerations[i], taint) { tolerated = true break } } return tolerated } + +func GetAvoidPodsFromNodeAnnotations(annotations map[string]string) (AvoidPods, error) { + var avoidPods AvoidPods + if len(annotations) > 0 && annotations[PreferAvoidPodsAnnotationKey] != "" { + err := json.Unmarshal([]byte(annotations[PreferAvoidPodsAnnotationKey]), &avoidPods) + if err != nil { + return avoidPods, err + } + } + return avoidPods, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/install/install.go b/vendor/k8s.io/kubernetes/pkg/api/install/install.go index bed5f0791abf..937920d28a85 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/api/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/mapper.go b/vendor/k8s.io/kubernetes/pkg/api/mapper.go index 0216771eec87..60addca7f245 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/mapper.go +++ b/vendor/k8s.io/kubernetes/pkg/api/mapper.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta.go b/vendor/k8s.io/kubernetes/pkg/api/meta.go index 9d5dae2c5951..4f02e934d83c 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,7 +29,13 @@ import ( // FillObjectMetaSystemFields populates fields that are managed by the system on ObjectMeta. func FillObjectMetaSystemFields(ctx Context, meta *ObjectMeta) { meta.CreationTimestamp = unversioned.Now() - meta.UID = util.NewUUID() + // allows admission controllers to assign a UID earlier in the request processing + // to support tracking resources pending creation. + uid, found := UIDFrom(ctx) + if !found { + uid = util.NewUUID() + } + meta.UID = uid meta.SelfLink = "" } @@ -67,8 +73,6 @@ func ListMetaFor(obj runtime.Object) (*unversioned.ListMeta, error) { func (obj *ObjectMeta) GetObjectMeta() meta.Object { return obj } -func (obj *ObjectReference) GetObjectKind() unversioned.ObjectKind { return obj } - // Namespace implements meta.Object for any object with an ObjectMeta typed field. Allows // fast, direct access to metadata fields for API objects. func (meta *ObjectMeta) GetNamespace() string { return meta.Namespace } diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/doc.go b/vendor/k8s.io/kubernetes/pkg/api/meta/doc.go index 4a132184f66c..a3b18a5c9aa1 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/errors.go b/vendor/k8s.io/kubernetes/pkg/api/meta/errors.go index 2b89bcb8ac38..70452965e584 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,19 +38,40 @@ func (e *AmbiguousResourceError) Error() string { return fmt.Sprintf("%v matches multiple kinds %v", e.PartialResource, e.MatchingKinds) case len(e.MatchingResources) > 0: return fmt.Sprintf("%v matches multiple resources %v", e.PartialResource, e.MatchingResources) - } - return fmt.Sprintf("%v matches multiple resources or kinds", e.PartialResource) } -func IsAmbiguousResourceError(err error) bool { +// AmbiguousKindError is returned if the RESTMapper finds multiple matches for a kind +type AmbiguousKindError struct { + PartialKind unversioned.GroupVersionKind + + MatchingResources []unversioned.GroupVersionResource + MatchingKinds []unversioned.GroupVersionKind +} + +func (e *AmbiguousKindError) Error() string { + switch { + case len(e.MatchingKinds) > 0 && len(e.MatchingResources) > 0: + return fmt.Sprintf("%v matches multiple resources %v and kinds %v", e.PartialKind, e.MatchingResources, e.MatchingKinds) + case len(e.MatchingKinds) > 0: + return fmt.Sprintf("%v matches multiple kinds %v", e.PartialKind, e.MatchingKinds) + case len(e.MatchingResources) > 0: + return fmt.Sprintf("%v matches multiple resources %v", e.PartialKind, e.MatchingResources) + } + return fmt.Sprintf("%v matches multiple resources or kinds", e.PartialKind) +} + +func IsAmbiguousError(err error) bool { if err == nil { return false } - - _, ok := err.(*AmbiguousResourceError) - return ok + switch err.(type) { + case *AmbiguousResourceError, *AmbiguousKindError: + return true + default: + return false + } } // NoResourceMatchError is returned if the RESTMapper can't find any match for a resource @@ -62,11 +83,23 @@ func (e *NoResourceMatchError) Error() string { return fmt.Sprintf("no matches for %v", e.PartialResource) } -func IsNoResourceMatchError(err error) bool { +// NoKindMatchError is returned if the RESTMapper can't find any match for a kind +type NoKindMatchError struct { + PartialKind unversioned.GroupVersionKind +} + +func (e *NoKindMatchError) Error() string { + return fmt.Sprintf("no matches for %v", e.PartialKind) +} + +func IsNoMatchError(err error) bool { if err == nil { return false } - - _, ok := err.(*NoResourceMatchError) - return ok + switch err.(type) { + case *NoResourceMatchError, *NoKindMatchError: + return true + default: + return false + } } diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/help.go b/vendor/k8s.io/kubernetes/pkg/api/meta/help.go index cdc07930fe83..0d733a58a099 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/help.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/help.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/interfaces.go b/vendor/k8s.io/kubernetes/pkg/api/meta/interfaces.go index 286bdc0dd732..f8179869d889 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -173,7 +173,10 @@ type RESTMapper interface { // ResourcesFor takes a partial resource and returns back the list of potential resource in priority order ResourcesFor(input unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) + // RESTMapping identifies a preferred resource mapping for the provided group kind. RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) + // RESTMappings returns all resource mappings for the provided group kind. + RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) AliasesForResource(resource string) ([]string, bool) ResourceSingularizer(resource string) (singular string, err error) diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/meta.go b/vendor/k8s.io/kubernetes/pkg/api/meta/meta.go index 5f185f39f395..876aa4faafbb 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/meta.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/meta.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,104 +29,66 @@ import ( "github.com/golang/glog" ) +// errNotList is returned when an object implements the Object style interfaces but not the List style +// interfaces. +var errNotList = fmt.Errorf("object does not implement the List interfaces") + +// ListAccessor returns a List interface for the provided object or an error if the object does +// not provide List. +// IMPORTANT: Objects are a superset of lists, so all Objects return List metadata. Do not use this +// check to determine whether an object *is* a List. +// TODO: return bool instead of error func ListAccessor(obj interface{}) (List, error) { - if listMetaAccessor, ok := obj.(ListMetaAccessor); ok { - if om := listMetaAccessor.GetListMeta(); om != nil { - return om, nil + switch t := obj.(type) { + case List: + return t, nil + case unversioned.List: + return t, nil + case ListMetaAccessor: + if m := t.GetListMeta(); m != nil { + return m, nil } - } - if listMetaAccessor, ok := obj.(unversioned.ListMetaAccessor); ok { - if om := listMetaAccessor.GetListMeta(); om != nil { - return om, nil + return nil, errNotList + case unversioned.ListMetaAccessor: + if m := t.GetListMeta(); m != nil { + return m, nil } - } - // we may get passed an object that is directly portable to List - if list, ok := obj.(List); ok { - return list, nil - } - glog.V(4).Infof("Calling ListAccessor on non-internal object: %v", reflect.TypeOf(obj)) - // legacy path for objects that do not implement List and ListMetaAccessor via - // reflection - very slow code path. - v, err := conversion.EnforcePtr(obj) - if err != nil { - return nil, err - } - t := v.Type() - if v.Kind() != reflect.Struct { - return nil, fmt.Errorf("expected struct, but got %v: %v (%#v)", v.Kind(), t, v.Interface()) - } - a := &genericAccessor{} - listMeta := v.FieldByName("ListMeta") - if listMeta.IsValid() { - // look for the ListMeta fields - if err := extractFromListMeta(listMeta, a); err != nil { - return nil, fmt.Errorf("unable to find list fields on %#v: %v", listMeta, err) + return nil, errNotList + case Object: + return t, nil + case ObjectMetaAccessor: + if m := t.GetObjectMeta(); m != nil { + return m, nil } - } else { - return nil, fmt.Errorf("unable to find listMeta on %#v", v) + return nil, errNotList + default: + return nil, errNotList } - return a, nil } +// errNotObject is returned when an object implements the List style interfaces but not the Object style +// interfaces. +var errNotObject = fmt.Errorf("object does not implement the Object interfaces") + // Accessor takes an arbitrary object pointer and returns meta.Interface. // obj must be a pointer to an API type. An error is returned if the minimum // required fields are missing. Fields that are not required return the default // value and are a no-op if set. +// TODO: return bool instead of error func Accessor(obj interface{}) (Object, error) { - if objectMetaAccessor, ok := obj.(ObjectMetaAccessor); ok { - if om := objectMetaAccessor.GetObjectMeta(); om != nil { - return om, nil + switch t := obj.(type) { + case Object: + return t, nil + case ObjectMetaAccessor: + if m := t.GetObjectMeta(); m != nil { + return m, nil } + return nil, errNotObject + case List, unversioned.List, ListMetaAccessor, unversioned.ListMetaAccessor: + return nil, errNotObject + default: + return nil, errNotObject } - // we may get passed an object that is directly portable to Object - if object, ok := obj.(Object); ok { - return object, nil - } - - glog.V(4).Infof("Calling Accessor on non-internal object: %v", reflect.TypeOf(obj)) - // legacy path for objects that do not implement Object and ObjectMetaAccessor via - // reflection - very slow code path. - v, err := conversion.EnforcePtr(obj) - if err != nil { - return nil, err - } - t := v.Type() - if v.Kind() != reflect.Struct { - return nil, fmt.Errorf("expected struct, but got %v: %v (%#v)", v.Kind(), t, v.Interface()) - } - - typeMeta := v.FieldByName("TypeMeta") - if !typeMeta.IsValid() { - return nil, fmt.Errorf("struct %v lacks embedded TypeMeta type", t) - } - - a := &genericAccessor{} - if err := extractFromTypeMeta(typeMeta, a); err != nil { - return nil, fmt.Errorf("unable to find type fields on %#v: %v", typeMeta, err) - } - - objectMeta := v.FieldByName("ObjectMeta") - if objectMeta.IsValid() { - // look for the ObjectMeta fields - if err := extractFromObjectMeta(objectMeta, a); err != nil { - return nil, fmt.Errorf("unable to find object fields on %#v: %v", objectMeta, err) - } - } else { - listMeta := v.FieldByName("ListMeta") - if listMeta.IsValid() { - // look for the ListMeta fields - if err := extractFromListMeta(listMeta, a); err != nil { - return nil, fmt.Errorf("unable to find list fields on %#v: %v", listMeta, err) - } - } else { - // look for the older TypeMeta with all metadata - if err := extractFromObjectMeta(typeMeta, a); err != nil { - return nil, fmt.Errorf("unable to find object fields on %#v: %v", typeMeta, err) - } - } - } - - return a, nil } // TypeAccessor returns an interface that allows retrieving and modifying the APIVersion @@ -283,7 +245,7 @@ func (resourceAccessor) SetUID(obj runtime.Object, uid types.UID) error { } func (resourceAccessor) SelfLink(obj runtime.Object) (string, error) { - accessor, err := Accessor(obj) + accessor, err := ListAccessor(obj) if err != nil { return "", err } @@ -291,7 +253,7 @@ func (resourceAccessor) SelfLink(obj runtime.Object) (string, error) { } func (resourceAccessor) SetSelfLink(obj runtime.Object, selfLink string) error { - accessor, err := Accessor(obj) + accessor, err := ListAccessor(obj) if err != nil { return err } @@ -334,7 +296,7 @@ func (resourceAccessor) SetAnnotations(obj runtime.Object, annotations map[strin } func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error) { - accessor, err := Accessor(obj) + accessor, err := ListAccessor(obj) if err != nil { return "", err } @@ -342,7 +304,7 @@ func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error) { } func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) error { - accessor, err := Accessor(obj) + accessor, err := ListAccessor(obj) if err != nil { return err } @@ -603,54 +565,3 @@ func extractFromTypeMeta(v reflect.Value, a *genericAccessor) error { } return nil } - -// extractFromObjectMeta extracts pointers to metadata fields from an object -func extractFromObjectMeta(v reflect.Value, a *genericAccessor) error { - if err := runtime.FieldPtr(v, "Namespace", &a.namespace); err != nil { - return err - } - if err := runtime.FieldPtr(v, "Name", &a.name); err != nil { - return err - } - if err := runtime.FieldPtr(v, "GenerateName", &a.generateName); err != nil { - return err - } - if err := runtime.FieldPtr(v, "UID", &a.uid); err != nil { - return err - } - if err := runtime.FieldPtr(v, "ResourceVersion", &a.resourceVersion); err != nil { - return err - } - if err := runtime.FieldPtr(v, "SelfLink", &a.selfLink); err != nil { - return err - } - if err := runtime.FieldPtr(v, "Labels", &a.labels); err != nil { - return err - } - if err := runtime.FieldPtr(v, "Annotations", &a.annotations); err != nil { - return err - } - if err := runtime.FieldPtr(v, "Finalizers", &a.finalizers); err != nil { - return err - } - ownerReferences := v.FieldByName("OwnerReferences") - if !ownerReferences.IsValid() { - return fmt.Errorf("struct %#v lacks OwnerReferences type", v) - } - if ownerReferences.Kind() != reflect.Slice { - return fmt.Errorf("expect %v to be a slice", ownerReferences.Kind()) - } - a.ownerReferences = ownerReferences.Addr() - return nil -} - -// extractFromObjectMeta extracts pointers to metadata fields from a list object -func extractFromListMeta(v reflect.Value, a *genericAccessor) error { - if err := runtime.FieldPtr(v, "ResourceVersion", &a.resourceVersion); err != nil { - return err - } - if err := runtime.FieldPtr(v, "SelfLink", &a.selfLink); err != nil { - return err - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/metatypes/types.go b/vendor/k8s.io/kubernetes/pkg/api/meta/metatypes/types.go index e7ac3e08d7fd..41e6596d7713 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/metatypes/types.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/metatypes/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go b/vendor/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go index b720f8fa2ef3..7b239e0340f9 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/multirestmapper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ func (m MultiRESTMapper) ResourcesFor(resource unversioned.GroupVersionResource) for _, t := range m { gvrs, err := t.ResourcesFor(resource) // ignore "no match" errors, but any other error percolates back up - if IsNoResourceMatchError(err) { + if IsNoMatchError(err) { continue } if err != nil { @@ -91,7 +91,7 @@ func (m MultiRESTMapper) KindsFor(resource unversioned.GroupVersionResource) (gv for _, t := range m { gvks, err := t.KindsFor(resource) // ignore "no match" errors, but any other error percolates back up - if IsNoResourceMatchError(err) { + if IsNoMatchError(err) { continue } if err != nil { @@ -155,7 +155,7 @@ func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...strin for _, t := range m { currMapping, err := t.RESTMapping(gk, versions...) // ignore "no match" errors, but any other error percolates back up - if IsNoResourceMatchError(err) { + if IsNoMatchError(err) { continue } if err != nil { @@ -171,12 +171,43 @@ func (m MultiRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...strin return allMappings[0], nil } if len(allMappings) > 1 { - return nil, fmt.Errorf("multiple matches found for %v in %v", gk, versions) + var kinds []unversioned.GroupVersionKind + for _, m := range allMappings { + kinds = append(kinds, m.GroupVersionKind) + } + return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds} } if len(errors) > 0 { return nil, utilerrors.NewAggregate(errors) } - return nil, fmt.Errorf("no match found for %v in %v", gk, versions) + return nil, &NoKindMatchError{PartialKind: gk.WithVersion("")} +} + +// RESTMappings returns all possible RESTMappings for the provided group kind, or an error +// if the type is not recognized. +func (m MultiRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) { + var allMappings []*RESTMapping + var errors []error + + for _, t := range m { + currMappings, err := t.RESTMappings(gk) + // ignore "no match" errors, but any other error percolates back up + if IsNoMatchError(err) { + continue + } + if err != nil { + errors = append(errors, err) + continue + } + allMappings = append(allMappings, currMappings...) + } + if len(errors) > 0 { + return nil, utilerrors.NewAggregate(errors) + } + if len(allMappings) == 0 { + return nil, &NoKindMatchError{PartialKind: gk.WithVersion("")} + } + return allMappings, nil } // AliasesForResource finds the first alias response for the provided mappers. diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/priority.go b/vendor/k8s.io/kubernetes/pkg/api/meta/priority.go index 24f38f78fd34..2e460609d102 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/priority.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/priority.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -153,7 +153,60 @@ func kindMatches(pattern unversioned.GroupVersionKind, kind unversioned.GroupVer } func (m PriorityRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (mapping *RESTMapping, err error) { - return m.Delegate.RESTMapping(gk, versions...) + mappings, err := m.Delegate.RESTMappings(gk) + if err != nil { + return nil, err + } + + // any versions the user provides take priority + priorities := m.KindPriority + if len(versions) > 0 { + priorities = make([]unversioned.GroupVersionKind, 0, len(m.KindPriority)+len(versions)) + for _, version := range versions { + gv, err := unversioned.ParseGroupVersion(version) + if err != nil { + return nil, err + } + priorities = append(priorities, gv.WithKind(AnyKind)) + } + priorities = append(priorities, m.KindPriority...) + } + + remaining := append([]*RESTMapping{}, mappings...) + for _, pattern := range priorities { + var matching []*RESTMapping + for _, m := range remaining { + if kindMatches(pattern, m.GroupVersionKind) { + matching = append(matching, m) + } + } + + switch len(matching) { + case 0: + // if you have no matches, then nothing matched this pattern just move to the next + continue + case 1: + // one match, return + return matching[0], nil + default: + // more than one match, use the matched hits as the list moving to the next pattern. + // this way you can have a series of selection criteria + remaining = matching + } + } + if len(remaining) == 1 { + return remaining[0], nil + } + + var kinds []unversioned.GroupVersionKind + for _, m := range mappings { + kinds = append(kinds, m.GroupVersionKind) + } + return nil, &AmbiguousKindError{PartialKind: gk.WithVersion(""), MatchingKinds: kinds} +} + +func (m PriorityRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) { + return m.Delegate.RESTMappings(gk) } func (m PriorityRESTMapper) AliasesForResource(alias string) (aliases []string, ok bool) { diff --git a/vendor/k8s.io/kubernetes/pkg/api/meta/restmapper.go b/vendor/k8s.io/kubernetes/pkg/api/meta/restmapper.go index 4e07ab7414e1..3ec959259828 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/meta/restmapper.go +++ b/vendor/k8s.io/kubernetes/pkg/api/meta/restmapper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -431,6 +431,7 @@ func (o resourceByPreferredGroupVersion) Less(i, j int) bool { // RESTClient should use to operate on the provided group/kind in order of versions. If a version search // order is not provided, the search order provided to DefaultRESTMapper will be used to resolve which // version should be used to access the named group/kind. +// TODO: consider refactoring to use RESTMappings in a way that preserves version ordering and preference func (m *DefaultRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*RESTMapping, error) { // Pick an appropriate version var gvk *unversioned.GroupVersionKind @@ -462,7 +463,7 @@ func (m *DefaultRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...st } } if gvk == nil { - return nil, fmt.Errorf("no kind named %q is registered in versions %q", gk, versions) + return nil, &NoKindMatchError{PartialKind: gk.WithVersion("")} } // Ensure we have a REST mapping @@ -503,6 +504,49 @@ func (m *DefaultRESTMapper) RESTMapping(gk unversioned.GroupKind, versions ...st return retVal, nil } +// RESTMappings returns the RESTMappings for the provided group kind in a rough internal preferred order. If no +// kind is found it will return a NoResourceMatchError. +func (m *DefaultRESTMapper) RESTMappings(gk unversioned.GroupKind) ([]*RESTMapping, error) { + // Use the default preferred versions + var mappings []*RESTMapping + for _, gv := range m.defaultGroupVersions { + if gv.Group != gk.Group { + continue + } + + gvk := gk.WithVersion(gv.Version) + gvr, ok := m.kindToPluralResource[gvk] + if !ok { + continue + } + + // Ensure we have a REST scope + scope, ok := m.kindToScope[gvk] + if !ok { + return nil, fmt.Errorf("the provided version %q and kind %q cannot be mapped to a supported scope", gvk.GroupVersion(), gvk.Kind) + } + + interfaces, err := m.interfacesFunc(gvk.GroupVersion()) + if err != nil { + return nil, fmt.Errorf("the provided version %q has no relevant versions", gvk.GroupVersion().String()) + } + + mappings = append(mappings, &RESTMapping{ + Resource: gvr.Resource, + GroupVersionKind: gvk, + Scope: scope, + + ObjectConvertor: interfaces.ObjectConvertor, + MetadataAccessor: interfaces.MetadataAccessor, + }) + } + + if len(mappings) == 0 { + return nil, &NoResourceMatchError{PartialResource: unversioned.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}} + } + return mappings, nil +} + // AddResourceAlias maps aliases to resources func (m *DefaultRESTMapper) AddResourceAlias(alias string, resources ...string) { if len(resources) == 0 { diff --git a/vendor/k8s.io/kubernetes/pkg/api/pod/util.go b/vendor/k8s.io/kubernetes/pkg/api/pod/util.go index 1bdacfe20d68..cd6f9fb675ff 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/pod/util.go +++ b/vendor/k8s.io/kubernetes/pkg/api/pod/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/pod_example.json b/vendor/k8s.io/kubernetes/pkg/api/pod_example.json deleted file mode 100644 index 8284240a22cb..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/pod_example.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "kind": "Pod", - "apiVersion": "v1", - "metadata": { - "name": "etcd-server-e2e-test-wojtekt-master", - "namespace": "default", - "selfLink": "/api/v1/namespaces/default/pods/etcd-server-e2e-test-wojtekt-master", - "uid": "a671734a-e8e5-11e4-8fde-42010af09327", - "resourceVersion": "22", - "creationTimestamp": "2015-04-22T11:49:36Z", - "annotations": { - "kubernetes.io/config.mirror": "mirror", - "kubernetes.io/config.source": "file" - } - }, - "spec": { - "volumes": [ - { - "name": "varetcd", - "hostPath": { - "path": "/mnt/master-pd/var/etcd" - }, - "emptyDir": null, - "gcePersistentDisk": null, - "awsElasticBlockStore": null, - "gitRepo": null, - "secret": null, - "nfs": null, - "iscsi": null, - "glusterfs": null - } - ], - "containers": [ - { - "name": "etcd-container", - "image": "gcr.io/google_containers/etcd:2.0.9", - "command": [ - "/usr/local/bin/etcd", - "--addr", - "127.0.0.1:4001", - "--bind-addr", - "127.0.0.1:4001", - "--data-dir", - "/var/etcd/data" - ], - "ports": [ - { - "name": "serverport", - "hostPort": 2380, - "containerPort": 2380, - "protocol": "TCP" - }, - { - "name": "clientport", - "hostPort": 4001, - "containerPort": 4001, - "protocol": "TCP" - } - ], - "resources": {}, - "volumeMounts": [ - { - "name": "varetcd", - "mountPath": "/var/etcd" - } - ], - "terminationMessagePath": "/dev/termination-log", - "imagePullPolicy": "IfNotPresent", - "capabilities": {} - } - ], - "restartPolicy": "Always", - "dnsPolicy": "ClusterFirst", - "nodeName": "e2e-test-wojtekt-master", - "hostNetwork": true - }, - "status": { - "phase": "Running", - "conditions": [ - { - "type": "Ready", - "status": "True" - } - ], - "containerStatuses": [ - { - "name": "etcd-container", - "state": { - "running": { - "startedAt": "2015-04-22T11:49:32Z" - } - }, - "lastState": {}, - "ready": true, - "restartCount": 0, - "image": "gcr.io/google_containers/etcd:2.0.9", - "imageID": "docker://b6b9a86dc06aa1361357ca1b105feba961f6a4145adca6c54e142c0be0fe87b0", - "containerID": "docker://3cbbf818f1addfc252957b4504f56ef2907a313fe6afc47fc75373674255d46d" - } - ] - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/ref.go b/vendor/k8s.io/kubernetes/pkg/api/ref.go index 08dede0711f8..443343a97c26 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/ref.go +++ b/vendor/k8s.io/kubernetes/pkg/api/ref.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -45,10 +45,6 @@ func GetReference(obj runtime.Object) (*ObjectReference, error) { // Don't make a reference to a reference. return ref, nil } - meta, err := meta.Accessor(obj) - if err != nil { - return nil, err - } gvk := obj.GetObjectKind().GroupVersionKind() @@ -64,10 +60,22 @@ func GetReference(obj runtime.Object) (*ObjectReference, error) { kind = gvks[0].Kind } + // An object that implements only List has enough metadata to build a reference + var listMeta meta.List + objectMeta, err := meta.Accessor(obj) + if err != nil { + listMeta, err = meta.ListAccessor(obj) + if err != nil { + return nil, err + } + } else { + listMeta = objectMeta + } + // if the object referenced is actually persisted, we can also get version from meta version := gvk.GroupVersion().String() if len(version) == 0 { - selfLink := meta.GetSelfLink() + selfLink := listMeta.GetSelfLink() if len(selfLink) == 0 { return nil, ErrNoSelfLink } @@ -83,13 +91,22 @@ func GetReference(obj runtime.Object) (*ObjectReference, error) { version = parts[2] } + // only has list metadata + if objectMeta == nil { + return &ObjectReference{ + Kind: kind, + APIVersion: version, + ResourceVersion: listMeta.GetResourceVersion(), + }, nil + } + return &ObjectReference{ Kind: kind, APIVersion: version, - Name: meta.GetName(), - Namespace: meta.GetNamespace(), - UID: meta.GetUID(), - ResourceVersion: meta.GetResourceVersion(), + Name: objectMeta.GetName(), + Namespace: objectMeta.GetNamespace(), + UID: objectMeta.GetUID(), + ResourceVersion: objectMeta.GetResourceVersion(), }, nil } @@ -111,3 +128,5 @@ func (obj *ObjectReference) SetGroupVersionKind(gvk unversioned.GroupVersionKind func (obj *ObjectReference) GroupVersionKind() unversioned.GroupVersionKind { return unversioned.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) } + +func (obj *ObjectReference) GetObjectKind() unversioned.ObjectKind { return obj } diff --git a/vendor/k8s.io/kubernetes/pkg/api/register.go b/vendor/k8s.io/kubernetes/pkg/api/register.go index 631a7f958820..213c36113e42 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/register.go +++ b/vendor/k8s.io/kubernetes/pkg/api/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ const GroupName = "" // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal} -// Unversiond is group version for unversioned API objects +// Unversioned is group version for unversioned API objects // TODO: this should be v1 probably var Unversioned = unversioned.GroupVersion{Group: "", Version: "v1"} diff --git a/vendor/k8s.io/kubernetes/pkg/api/requestcontext.go b/vendor/k8s.io/kubernetes/pkg/api/requestcontext.go index 2c27d6862baf..14983b2d41fe 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/requestcontext.go +++ b/vendor/k8s.io/kubernetes/pkg/api/requestcontext.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/amount.go b/vendor/k8s.io/kubernetes/pkg/api/resource/amount.go index 6ae823a0229e..2d3012c875e4 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/amount.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/amount.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/api/resource/generated.pb.go index cf9447a321f4..f091cdeef1c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/generated.proto b/vendor/k8s.io/kubernetes/pkg/api/resource/generated.proto index e1c2a3d60800..bdc091d98d4b 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -83,7 +83,6 @@ option go_package = "resource"; // writing some sort of special handling code in the hopes that that will // cause implementors to also use a fixed point implementation. // -// +gencopy=false // +protobuf=true // +protobuf.embed=string // +protobuf.options.marshal=false diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/math.go b/vendor/k8s.io/kubernetes/pkg/api/resource/math.go index 163aafa5db6a..887ac74c9840 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/math.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/math.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/quantity.go b/vendor/k8s.io/kubernetes/pkg/api/resource/quantity.go index 96877b4c946f..823dd5ef70ed 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/quantity.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/quantity.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -87,7 +87,6 @@ import ( // writing some sort of special handling code in the hopes that that will // cause implementors to also use a fixed point implementation. // -// +gencopy=false // +protobuf=true // +protobuf.embed=string // +protobuf.options.marshal=false @@ -386,6 +385,16 @@ func ParseQuantity(str string) (Quantity, error) { return Quantity{d: infDecAmount{amount}, Format: format}, nil } +// DeepCopy returns a deep-copy of the Quantity value. Note that the method +// receiver is a value, so we can mutate it in-place and return it. +func (q Quantity) DeepCopy() Quantity { + if q.d.Dec != nil { + tmp := &inf.Dec{} + q.d.Dec = tmp.Set(q.d.Dec) + } + return q +} + // CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity). // // Note about BinarySI: diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/quantity_proto.go b/vendor/k8s.io/kubernetes/pkg/api/resource/quantity_proto.go index 240294682cff..74dfb4e4b7c9 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/quantity_proto.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/quantity_proto.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/scale_int.go b/vendor/k8s.io/kubernetes/pkg/api/resource/scale_int.go index 173de1a2171d..55e177b0e9b0 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/scale_int.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/scale_int.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/suffix.go b/vendor/k8s.io/kubernetes/pkg/api/resource/suffix.go index 0aa2ce2bf60e..5ed7abe66510 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/suffix.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource/suffix.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource_helpers.go b/vendor/k8s.io/kubernetes/pkg/api/resource_helpers.go index 4c55b120e144..2c683daa1ed0 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource_helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/api/resource_helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/create.go b/vendor/k8s.io/kubernetes/pkg/api/rest/create.go index fa95b7f93f23..e7a521cb2dbb 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/create.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/create.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/delete.go b/vendor/k8s.io/kubernetes/pkg/api/rest/delete.go index 34965d52fe8e..6967acbd1049 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/delete.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/delete.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -44,7 +44,8 @@ type RESTGracefulDeleteStrategy interface { // should be gracefully deleted, if gracefulPending is set the object has already been gracefully deleted // (and the provided grace period is longer than the time to deletion), and an error is returned if the // condition cannot be checked or the gracePeriodSeconds is invalid. The options argument may be updated with -// default values if graceful is true. +// default values if graceful is true. Second place where we set deletionTimestamp is pkg/registry/generic/registry/store.go +// this function is responsible for setting deletionTimestamp during gracefulDeletion, other one for cascading deletions. func BeforeDelete(strategy RESTDeleteStrategy, ctx api.Context, obj runtime.Object, options *api.DeleteOptions) (graceful, gracefulPending bool, err error) { objectMeta, gvk, kerr := objectMetaAndKind(strategy, obj) if kerr != nil { @@ -56,9 +57,11 @@ func BeforeDelete(strategy RESTDeleteStrategy, ctx api.Context, obj runtime.Obje } gracefulStrategy, ok := strategy.(RESTGracefulDeleteStrategy) if !ok { + // If we're not deleting gracefully there's no point in updating Generation, as we won't update + // the obcject before deleting it. return false, false, nil } - // if the object is already being deleted + // if the object is already being deleted, no need to update generation. if objectMeta.DeletionTimestamp != nil { // if we are already being deleted, we may only shorten the deletion grace period // this means the object was gracefully deleted previously but deletionGracePeriodSeconds was not set, @@ -69,13 +72,14 @@ func BeforeDelete(strategy RESTDeleteStrategy, ctx api.Context, obj runtime.Obje // only a shorter grace period may be provided by a user if options.GracePeriodSeconds != nil { period := int64(*options.GracePeriodSeconds) - if period > *objectMeta.DeletionGracePeriodSeconds { + if period >= *objectMeta.DeletionGracePeriodSeconds { return false, true, nil } - now := unversioned.NewTime(unversioned.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) - objectMeta.DeletionTimestamp = &now + newDeletionTimestamp := unversioned.NewTime( + objectMeta.DeletionTimestamp.Add(-time.Second * time.Duration(*objectMeta.DeletionGracePeriodSeconds)). + Add(time.Second * time.Duration(*options.GracePeriodSeconds))) + objectMeta.DeletionTimestamp = &newDeletionTimestamp objectMeta.DeletionGracePeriodSeconds = &period - options.GracePeriodSeconds = &period return true, false, nil } // graceful deletion is pending, do nothing @@ -89,5 +93,12 @@ func BeforeDelete(strategy RESTDeleteStrategy, ctx api.Context, obj runtime.Obje now := unversioned.NewTime(unversioned.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds))) objectMeta.DeletionTimestamp = &now objectMeta.DeletionGracePeriodSeconds = options.GracePeriodSeconds + // If it's the first graceful deletion we are going to set the DeletionTimestamp to non-nil. + // Controllers of the object that's being deleted shouldn't take any nontrivial actions, hence its behavior changes. + // Thus we need to bump object's Generation (if set). This handles generation bump during graceful deletion. + // The bump for objects that don't support graceful deletion is handled in pkg/registry/generic/registry/store.go. + if objectMeta.Generation > 0 { + objectMeta.Generation++ + } return true, false, nil } diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/doc.go b/vendor/k8s.io/kubernetes/pkg/api/rest/doc.go index 8fed0e9f486a..ee7c4145f4d2 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/export.go b/vendor/k8s.io/kubernetes/pkg/api/rest/export.go index e12f65de3c76..4407da79ab52 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/export.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/export.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/rest.go b/vendor/k8s.io/kubernetes/pkg/api/rest/rest.go index 4d5b5ba977c2..2d90c2f53f8d 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/rest.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/rest.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/types.go b/vendor/k8s.io/kubernetes/pkg/api/rest/types.go index 0e7f048ba516..85e786465a02 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/types.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/rest/update.go b/vendor/k8s.io/kubernetes/pkg/api/rest/update.go index bc5ed0c5f866..68cccb213d5f 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/rest/update.go +++ b/vendor/k8s.io/kubernetes/pkg/api/rest/update.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -86,6 +86,12 @@ func BeforeUpdate(strategy RESTUpdateStrategy, ctx api.Context, obj, old runtime } else { objectMeta.Namespace = api.NamespaceNone } + // Ensure requests cannot update generation + oldMeta, err := api.ObjectMetaFor(old) + if err != nil { + return err + } + objectMeta.Generation = oldMeta.Generation strategy.PrepareForUpdate(obj, old) @@ -173,3 +179,44 @@ func (i *defaultUpdatedObjectInfo) UpdatedObject(ctx api.Context, oldObj runtime return newObj, nil } + +// wrappedUpdatedObjectInfo allows wrapping an existing objInfo and +// chaining additional transformations/checks on the result of UpdatedObject() +type wrappedUpdatedObjectInfo struct { + // obj is the updated object + objInfo UpdatedObjectInfo + + // transformers is an optional list of transforming functions that modify or + // replace obj using information from the context, old object, or other sources. + transformers []TransformFunc +} + +// WrapUpdatedObjectInfo returns an UpdatedObjectInfo impl that delegates to +// the specified objInfo, then calls the passed transformers +func WrapUpdatedObjectInfo(objInfo UpdatedObjectInfo, transformers ...TransformFunc) UpdatedObjectInfo { + return &wrappedUpdatedObjectInfo{objInfo, transformers} +} + +// Preconditions satisfies the UpdatedObjectInfo interface. +func (i *wrappedUpdatedObjectInfo) Preconditions() *api.Preconditions { + return i.objInfo.Preconditions() +} + +// UpdatedObject satisfies the UpdatedObjectInfo interface. +// It delegates to the wrapped objInfo and passes the result through any configured transformers. +func (i *wrappedUpdatedObjectInfo) UpdatedObject(ctx api.Context, oldObj runtime.Object) (runtime.Object, error) { + newObj, err := i.objInfo.UpdatedObject(ctx, oldObj) + if err != nil { + return newObj, err + } + + // Allow any configured transformers to update the new object or error + for _, transformer := range i.transformers { + newObj, err = transformer(ctx, newObj, oldObj) + if err != nil { + return nil, err + } + } + + return newObj, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/service/annotations.go b/vendor/k8s.io/kubernetes/pkg/api/service/annotations.go index 9d57fa4c2082..ee275d3c1e33 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/service/annotations.go +++ b/vendor/k8s.io/kubernetes/pkg/api/service/annotations.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/service/util.go b/vendor/k8s.io/kubernetes/pkg/api/service/util.go index b6611d2370d1..6f0e14e2bde5 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/service/util.go +++ b/vendor/k8s.io/kubernetes/pkg/api/service/util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/types.generated.go b/vendor/k8s.io/kubernetes/pkg/api/types.generated.go index b2dcd4afb738..5cc82f5793cb 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/api/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37409,6 +37409,706 @@ func (x *AttachedVolume) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x *AvoidPods) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = len(x.PreferAvoidPods) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.PreferAvoidPods == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSlicePreferAvoidPodsEntry(([]PreferAvoidPodsEntry)(x.PreferAvoidPods), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("preferAvoidPods")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.PreferAvoidPods == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSlicePreferAvoidPodsEntry(([]PreferAvoidPodsEntry)(x.PreferAvoidPods), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *AvoidPods) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *AvoidPods) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "preferAvoidPods": + if r.TryDecodeAsNil() { + x.PreferAvoidPods = nil + } else { + yyv4 := &x.PreferAvoidPods + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSlicePreferAvoidPodsEntry((*[]PreferAvoidPodsEntry)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *AvoidPods) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PreferAvoidPods = nil + } else { + yyv7 := &x.PreferAvoidPods + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSlicePreferAvoidPodsEntry((*[]PreferAvoidPodsEntry)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *PreferAvoidPodsEntry) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = true + yyq2[2] = x.Reason != "" + yyq2[3] = x.Message != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy4 := &x.PodSignature + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("podSignature")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.PodSignature + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yy9 := &x.EvictionTime + yym10 := z.EncBinary() + _ = yym10 + if false { + } else if z.HasExtensions() && z.EncExt(yy9) { + } else if yym10 { + z.EncBinaryMarshal(yy9) + } else if !yym10 && z.IsJSONHandle() { + z.EncJSONMarshal(yy9) + } else { + z.EncFallback(yy9) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("evictionTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy11 := &x.EvictionTime + yym12 := z.EncBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.EncExt(yy11) { + } else if yym12 { + z.EncBinaryMarshal(yy11) + } else if !yym12 && z.IsJSONHandle() { + z.EncJSONMarshal(yy11) + } else { + z.EncFallback(yy11) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("reason")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("message")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym18 := z.EncBinary() + _ = yym18 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *PreferAvoidPodsEntry) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *PreferAvoidPodsEntry) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "podSignature": + if r.TryDecodeAsNil() { + x.PodSignature = PodSignature{} + } else { + yyv4 := &x.PodSignature + yyv4.CodecDecodeSelf(d) + } + case "evictionTime": + if r.TryDecodeAsNil() { + x.EvictionTime = pkg2_unversioned.Time{} + } else { + yyv5 := &x.EvictionTime + yym6 := z.DecBinary() + _ = yym6 + if false { + } else if z.HasExtensions() && z.DecExt(yyv5) { + } else if yym6 { + z.DecBinaryUnmarshal(yyv5) + } else if !yym6 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv5) + } else { + z.DecFallback(yyv5, false) + } + } + case "reason": + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + case "message": + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *PreferAvoidPodsEntry) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PodSignature = PodSignature{} + } else { + yyv10 := &x.PodSignature + yyv10.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.EvictionTime = pkg2_unversioned.Time{} + } else { + yyv11 := &x.EvictionTime + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else if yym12 { + z.DecBinaryUnmarshal(yyv11) + } else if !yym12 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv11) + } else { + z.DecFallback(yyv11, false) + } + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *PodSignature) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = x.PodController != nil + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.PodController == nil { + r.EncodeNil() + } else { + x.PodController.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("podController")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.PodController == nil { + r.EncodeNil() + } else { + x.PodController.CodecEncodeSelf(e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *PodSignature) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *PodSignature) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "podController": + if r.TryDecodeAsNil() { + if x.PodController != nil { + x.PodController = nil + } + } else { + if x.PodController == nil { + x.PodController = new(OwnerReference) + } + x.PodController.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *PodSignature) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj5 int + var yyb5 bool + var yyhl5 bool = l >= 0 + yyj5++ + if yyhl5 { + yyb5 = yyj5 > l + } else { + yyb5 = r.CheckBreak() + } + if yyb5 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.PodController != nil { + x.PodController = nil + } + } else { + if x.PodController == nil { + x.PodController = new(OwnerReference) + } + x.PodController.CodecDecodeSelf(d) + } + for { + yyj5++ + if yyhl5 { + yyb5 = yyj5 > l + } else { + yyb5 = r.CheckBreak() + } + if yyb5 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj5-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + func (x *ContainerImage) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -57857,6 +58557,125 @@ func (x codecSelfer1234) decSliceAttachedVolume(v *[]AttachedVolume, d *codec197 } } +func (x codecSelfer1234) encSlicePreferAvoidPodsEntry(v []PreferAvoidPodsEntry, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSlicePreferAvoidPodsEntry(v *[]PreferAvoidPodsEntry, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []PreferAvoidPodsEntry{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 64) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]PreferAvoidPodsEntry, yyrl1) + } + } else { + yyv1 = make([]PreferAvoidPodsEntry, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, PreferAvoidPodsEntry{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, PreferAvoidPodsEntry{}) // var yyz1 PreferAvoidPodsEntry + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []PreferAvoidPodsEntry{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + func (x codecSelfer1234) encResourceList(v ResourceList, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) diff --git a/vendor/k8s.io/kubernetes/pkg/api/types.go b/vendor/k8s.io/kubernetes/pkg/api/types.go index 6d11c183baea..37d5152c96fb 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/types.go +++ b/vendor/k8s.io/kubernetes/pkg/api/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -283,7 +283,8 @@ type PersistentVolumeClaimVolumeSource struct { ReadOnly bool `json:"readOnly,omitempty"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true type PersistentVolume struct { unversioned.TypeMeta `json:",inline"` @@ -440,7 +441,7 @@ type HostPathVolumeSource struct { type EmptyDirVolumeSource struct { // TODO: Longer term we want to represent the selection of underlying // media more like a scheduling problem - user says what traits they - // need, we give them a backing store that satisifies that. For now + // need, we give them a backing store that satisfies that. For now // this will cover the most common needs. // Optional: what type of storage medium should back this directory. // The default is "" which means to use the node's default medium. @@ -1478,12 +1479,15 @@ type PodSecurityContext struct { // Use the host's network namespace. If this option is set, the ports that will be // used must be specified. // Optional: Default to false + // +k8s:conversion-gen=false HostNetwork bool `json:"hostNetwork,omitempty"` // Use the host's pid namespace. // Optional: Default to false. + // +k8s:conversion-gen=false HostPID bool `json:"hostPID,omitempty"` // Use the host's ipc namespace. // Optional: Default to false. + // +k8s:conversion-gen=false HostIPC bool `json:"hostIPC,omitempty"` // The SELinux context to be applied to all containers. // If unspecified, the container runtime will allocate a random SELinux context for each @@ -2000,10 +2004,38 @@ type AttachedVolume struct { // Name of the attached volume Name UniqueVolumeName `json:"name"` - // DevicePath represents the device path where the volume should be avilable + // DevicePath represents the device path where the volume should be available DevicePath string `json:"devicePath"` } +// AvoidPods describes pods that should avoid this node. This is the value for a +// Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and +// will eventually become a field of NodeStatus. +type AvoidPods struct { + // Bounded-sized list of signatures of pods that should avoid this node, sorted + // in timestamp order from oldest to newest. Size of the slice is unspecified. + PreferAvoidPods []PreferAvoidPodsEntry `json:"preferAvoidPods,omitempty"` +} + +// Describes a class of pods that should avoid this node. +type PreferAvoidPodsEntry struct { + // The class of pods. + PodSignature PodSignature `json:"podSignature"` + // Time at which this entry was added to the list. + EvictionTime unversioned.Time `json:"evictionTime,omitempty"` + // (brief) reason why this entry was added to the list. + Reason string `json:"reason,omitempty"` + // Human readable message indicating why this entry was added to the list. + Message string `json:"message,omitempty"` +} + +// Describes the class of pods that should avoid this node. +// Exactly one field should be set. +type PodSignature struct { + // Reference to controller whose pods should avoid this node. + PodController *OwnerReference `json:"podController,omitempty"` +} + // Describe a container image type ContainerImage struct { // Names by which this image is known. @@ -2037,6 +2069,8 @@ const ( NodeOutOfDisk NodeConditionType = "OutOfDisk" // NodeMemoryPressure means the kubelet is under pressure due to insufficient available memory. NodeMemoryPressure NodeConditionType = "MemoryPressure" + // NodeDiskPressure means the kubelet is under pressure due to insufficient available disk. + NodeDiskPressure NodeConditionType = "DiskPressure" // NodeNetworkUnavailable means that network for the node is not correctly configured. NodeNetworkUnavailable NodeConditionType = "NetworkUnavailable" ) @@ -2096,7 +2130,8 @@ const ( // ResourceList is a set of (resource name, quantity) pairs. type ResourceList map[ResourceName]resource.Quantity -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // Node is a worker node in Kubernetes // The name of the node according to etcd is in ObjectMeta.Name. @@ -2149,7 +2184,8 @@ const ( NamespaceTerminating NamespacePhase = "Terminating" ) -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // A namespace provides a scope for Names. // Use of multiple namespaces is optional @@ -2226,7 +2262,11 @@ type ListOptions struct { FieldSelector fields.Selector // If true, watch for changes to this list Watch bool - // The resource version to watch (no effect on list yet) + // For watch, it's the resource version to watch. + // For list, + // - if unset, then the result is returned from remote storage based on quorum-read flag; + // - if it's 0, then we simply return what we currently have in cache, no guarantee; + // - if set to non zero, then the result is as fresh as given rv. ResourceVersion string // Timeout for the list/watch call. TimeoutSeconds *int64 @@ -2686,7 +2726,7 @@ const ( // TODO: Consider supporting different formats, specifying CA/destinationCA. SecretTypeTLS SecretType = "kubernetes.io/tls" - // TLSCertKey is the key for tls certificates in a TLS secert. + // TLSCertKey is the key for tls certificates in a TLS secret. TLSCertKey = "tls.crt" // TLSPrivateKeyKey is the key for the private key field in a TLS secret. TLSPrivateKeyKey = "tls.key" @@ -2751,6 +2791,8 @@ const ( StreamTypeData = "data" // Value for streamType header for error stream StreamTypeError = "error" + // Value for streamType header for terminal resize stream + StreamTypeResize = "resize" // Name of header that specifies the port being forwarded PortHeader = "port" @@ -2785,7 +2827,8 @@ type ComponentCondition struct { Error string `json:"error,omitempty"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ComponentStatus (and ComponentStatusList) holds the cluster validation info. type ComponentStatus struct { diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/deep_copy_generated.go deleted file mode 100644 index ff8f1f0d66fe..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/deep_copy_generated.go +++ /dev/null @@ -1,314 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package unversioned - -import ( - conversion "k8s.io/kubernetes/pkg/conversion" - time "time" -) - -func DeepCopy_unversioned_APIGroup(in APIGroup, out *APIGroup, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Name = in.Name - if in.Versions != nil { - in, out := in.Versions, &out.Versions - *out = make([]GroupVersionForDiscovery, len(in)) - for i := range in { - if err := DeepCopy_unversioned_GroupVersionForDiscovery(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Versions = nil - } - if err := DeepCopy_unversioned_GroupVersionForDiscovery(in.PreferredVersion, &out.PreferredVersion, c); err != nil { - return err - } - if in.ServerAddressByClientCIDRs != nil { - in, out := in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs - *out = make([]ServerAddressByClientCIDR, len(in)) - for i := range in { - if err := DeepCopy_unversioned_ServerAddressByClientCIDR(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ServerAddressByClientCIDRs = nil - } - return nil -} - -func DeepCopy_unversioned_APIGroupList(in APIGroupList, out *APIGroupList, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.Groups != nil { - in, out := in.Groups, &out.Groups - *out = make([]APIGroup, len(in)) - for i := range in { - if err := DeepCopy_unversioned_APIGroup(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Groups = nil - } - return nil -} - -func DeepCopy_unversioned_APIResource(in APIResource, out *APIResource, c *conversion.Cloner) error { - out.Name = in.Name - out.Namespaced = in.Namespaced - out.Kind = in.Kind - return nil -} - -func DeepCopy_unversioned_APIResourceList(in APIResourceList, out *APIResourceList, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.GroupVersion = in.GroupVersion - if in.APIResources != nil { - in, out := in.APIResources, &out.APIResources - *out = make([]APIResource, len(in)) - for i := range in { - if err := DeepCopy_unversioned_APIResource(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.APIResources = nil - } - return nil -} - -func DeepCopy_unversioned_APIVersions(in APIVersions, out *APIVersions, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.Versions != nil { - in, out := in.Versions, &out.Versions - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Versions = nil - } - if in.ServerAddressByClientCIDRs != nil { - in, out := in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs - *out = make([]ServerAddressByClientCIDR, len(in)) - for i := range in { - if err := DeepCopy_unversioned_ServerAddressByClientCIDR(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ServerAddressByClientCIDRs = nil - } - return nil -} - -func DeepCopy_unversioned_Duration(in Duration, out *Duration, c *conversion.Cloner) error { - out.Duration = in.Duration - return nil -} - -func DeepCopy_unversioned_ExportOptions(in ExportOptions, out *ExportOptions, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Export = in.Export - out.Exact = in.Exact - return nil -} - -func DeepCopy_unversioned_GroupKind(in GroupKind, out *GroupKind, c *conversion.Cloner) error { - out.Group = in.Group - out.Kind = in.Kind - return nil -} - -func DeepCopy_unversioned_GroupResource(in GroupResource, out *GroupResource, c *conversion.Cloner) error { - out.Group = in.Group - out.Resource = in.Resource - return nil -} - -func DeepCopy_unversioned_GroupVersion(in GroupVersion, out *GroupVersion, c *conversion.Cloner) error { - out.Group = in.Group - out.Version = in.Version - return nil -} - -func DeepCopy_unversioned_GroupVersionForDiscovery(in GroupVersionForDiscovery, out *GroupVersionForDiscovery, c *conversion.Cloner) error { - out.GroupVersion = in.GroupVersion - out.Version = in.Version - return nil -} - -func DeepCopy_unversioned_GroupVersionKind(in GroupVersionKind, out *GroupVersionKind, c *conversion.Cloner) error { - out.Group = in.Group - out.Version = in.Version - out.Kind = in.Kind - return nil -} - -func DeepCopy_unversioned_GroupVersionResource(in GroupVersionResource, out *GroupVersionResource, c *conversion.Cloner) error { - out.Group = in.Group - out.Version = in.Version - out.Resource = in.Resource - return nil -} - -func DeepCopy_unversioned_LabelSelector(in LabelSelector, out *LabelSelector, c *conversion.Cloner) error { - if in.MatchLabels != nil { - in, out := in.MatchLabels, &out.MatchLabels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.MatchLabels = nil - } - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]LabelSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_unversioned_LabelSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_unversioned_LabelSelectorRequirement(in LabelSelectorRequirement, out *LabelSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} - -func DeepCopy_unversioned_ListMeta(in ListMeta, out *ListMeta, c *conversion.Cloner) error { - out.SelfLink = in.SelfLink - out.ResourceVersion = in.ResourceVersion - return nil -} - -func DeepCopy_unversioned_Patch(in Patch, out *Patch, c *conversion.Cloner) error { - return nil -} - -func DeepCopy_unversioned_RootPaths(in RootPaths, out *RootPaths, c *conversion.Cloner) error { - if in.Paths != nil { - in, out := in.Paths, &out.Paths - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Paths = nil - } - return nil -} - -func DeepCopy_unversioned_ServerAddressByClientCIDR(in ServerAddressByClientCIDR, out *ServerAddressByClientCIDR, c *conversion.Cloner) error { - out.ClientCIDR = in.ClientCIDR - out.ServerAddress = in.ServerAddress - return nil -} - -func DeepCopy_unversioned_Status(in Status, out *Status, c *conversion.Cloner) error { - if err := DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - out.Status = in.Status - out.Message = in.Message - out.Reason = in.Reason - if in.Details != nil { - in, out := in.Details, &out.Details - *out = new(StatusDetails) - if err := DeepCopy_unversioned_StatusDetails(*in, *out, c); err != nil { - return err - } - } else { - out.Details = nil - } - out.Code = in.Code - return nil -} - -func DeepCopy_unversioned_StatusCause(in StatusCause, out *StatusCause, c *conversion.Cloner) error { - out.Type = in.Type - out.Message = in.Message - out.Field = in.Field - return nil -} - -func DeepCopy_unversioned_StatusDetails(in StatusDetails, out *StatusDetails, c *conversion.Cloner) error { - out.Name = in.Name - out.Group = in.Group - out.Kind = in.Kind - if in.Causes != nil { - in, out := in.Causes, &out.Causes - *out = make([]StatusCause, len(in)) - for i := range in { - if err := DeepCopy_unversioned_StatusCause(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Causes = nil - } - out.RetryAfterSeconds = in.RetryAfterSeconds - return nil -} - -func DeepCopy_unversioned_Time(in Time, out *Time, c *conversion.Cloner) error { - if newVal, err := c.DeepCopy(in.Time); err != nil { - return err - } else { - out.Time = newVal.(time.Time) - } - return nil -} - -func DeepCopy_unversioned_Timestamp(in Timestamp, out *Timestamp, c *conversion.Cloner) error { - out.Seconds = in.Seconds - out.Nanos = in.Nanos - return nil -} - -func DeepCopy_unversioned_TypeMeta(in TypeMeta, out *TypeMeta, c *conversion.Cloner) error { - out.Kind = in.Kind - out.APIVersion = in.APIVersion - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/doc.go new file mode 100644 index 000000000000..d0ffc33275ff --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package + +package unversioned diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/duration.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/duration.go index cdaf257300b4..ed54e515daec 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/duration.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/duration.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.pb.go index cb9803552ed7..1687b899f6bb 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -58,6 +58,10 @@ import math "math" import time "time" +import strings "strings" +import reflect "reflect" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -65,32 +69,26 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *APIGroup) Reset() { *m = APIGroup{} } -func (m *APIGroup) String() string { return proto.CompactTextString(m) } -func (*APIGroup) ProtoMessage() {} +func (m *APIGroup) Reset() { *m = APIGroup{} } +func (*APIGroup) ProtoMessage() {} -func (m *APIGroupList) Reset() { *m = APIGroupList{} } -func (m *APIGroupList) String() string { return proto.CompactTextString(m) } -func (*APIGroupList) ProtoMessage() {} +func (m *APIGroupList) Reset() { *m = APIGroupList{} } +func (*APIGroupList) ProtoMessage() {} -func (m *APIResource) Reset() { *m = APIResource{} } -func (m *APIResource) String() string { return proto.CompactTextString(m) } -func (*APIResource) ProtoMessage() {} +func (m *APIResource) Reset() { *m = APIResource{} } +func (*APIResource) ProtoMessage() {} -func (m *APIResourceList) Reset() { *m = APIResourceList{} } -func (m *APIResourceList) String() string { return proto.CompactTextString(m) } -func (*APIResourceList) ProtoMessage() {} +func (m *APIResourceList) Reset() { *m = APIResourceList{} } +func (*APIResourceList) ProtoMessage() {} func (m *APIVersions) Reset() { *m = APIVersions{} } func (*APIVersions) ProtoMessage() {} -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} +func (m *Duration) Reset() { *m = Duration{} } +func (*Duration) ProtoMessage() {} -func (m *ExportOptions) Reset() { *m = ExportOptions{} } -func (m *ExportOptions) String() string { return proto.CompactTextString(m) } -func (*ExportOptions) ProtoMessage() {} +func (m *ExportOptions) Reset() { *m = ExportOptions{} } +func (*ExportOptions) ProtoMessage() {} func (m *GroupKind) Reset() { *m = GroupKind{} } func (*GroupKind) ProtoMessage() {} @@ -101,9 +99,8 @@ func (*GroupResource) ProtoMessage() {} func (m *GroupVersion) Reset() { *m = GroupVersion{} } func (*GroupVersion) ProtoMessage() {} -func (m *GroupVersionForDiscovery) Reset() { *m = GroupVersionForDiscovery{} } -func (m *GroupVersionForDiscovery) String() string { return proto.CompactTextString(m) } -func (*GroupVersionForDiscovery) ProtoMessage() {} +func (m *GroupVersionForDiscovery) Reset() { *m = GroupVersionForDiscovery{} } +func (*GroupVersionForDiscovery) ProtoMessage() {} func (m *GroupVersionKind) Reset() { *m = GroupVersionKind{} } func (*GroupVersionKind) ProtoMessage() {} @@ -111,49 +108,38 @@ func (*GroupVersionKind) ProtoMessage() {} func (m *GroupVersionResource) Reset() { *m = GroupVersionResource{} } func (*GroupVersionResource) ProtoMessage() {} -func (m *LabelSelector) Reset() { *m = LabelSelector{} } -func (m *LabelSelector) String() string { return proto.CompactTextString(m) } -func (*LabelSelector) ProtoMessage() {} +func (m *LabelSelector) Reset() { *m = LabelSelector{} } +func (*LabelSelector) ProtoMessage() {} -func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } -func (m *LabelSelectorRequirement) String() string { return proto.CompactTextString(m) } -func (*LabelSelectorRequirement) ProtoMessage() {} +func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } +func (*LabelSelectorRequirement) ProtoMessage() {} -func (m *ListMeta) Reset() { *m = ListMeta{} } -func (m *ListMeta) String() string { return proto.CompactTextString(m) } -func (*ListMeta) ProtoMessage() {} +func (m *ListMeta) Reset() { *m = ListMeta{} } +func (*ListMeta) ProtoMessage() {} -func (m *RootPaths) Reset() { *m = RootPaths{} } -func (m *RootPaths) String() string { return proto.CompactTextString(m) } -func (*RootPaths) ProtoMessage() {} +func (m *RootPaths) Reset() { *m = RootPaths{} } +func (*RootPaths) ProtoMessage() {} -func (m *ServerAddressByClientCIDR) Reset() { *m = ServerAddressByClientCIDR{} } -func (m *ServerAddressByClientCIDR) String() string { return proto.CompactTextString(m) } -func (*ServerAddressByClientCIDR) ProtoMessage() {} +func (m *ServerAddressByClientCIDR) Reset() { *m = ServerAddressByClientCIDR{} } +func (*ServerAddressByClientCIDR) ProtoMessage() {} -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} +func (m *Status) Reset() { *m = Status{} } +func (*Status) ProtoMessage() {} -func (m *StatusCause) Reset() { *m = StatusCause{} } -func (m *StatusCause) String() string { return proto.CompactTextString(m) } -func (*StatusCause) ProtoMessage() {} +func (m *StatusCause) Reset() { *m = StatusCause{} } +func (*StatusCause) ProtoMessage() {} -func (m *StatusDetails) Reset() { *m = StatusDetails{} } -func (m *StatusDetails) String() string { return proto.CompactTextString(m) } -func (*StatusDetails) ProtoMessage() {} +func (m *StatusDetails) Reset() { *m = StatusDetails{} } +func (*StatusDetails) ProtoMessage() {} -func (m *Time) Reset() { *m = Time{} } -func (m *Time) String() string { return proto.CompactTextString(m) } -func (*Time) ProtoMessage() {} +func (m *Time) Reset() { *m = Time{} } +func (*Time) ProtoMessage() {} -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} +func (m *Timestamp) Reset() { *m = Timestamp{} } +func (*Timestamp) ProtoMessage() {} -func (m *TypeMeta) Reset() { *m = TypeMeta{} } -func (m *TypeMeta) String() string { return proto.CompactTextString(m) } -func (*TypeMeta) ProtoMessage() {} +func (m *TypeMeta) Reset() { *m = TypeMeta{} } +func (*TypeMeta) ProtoMessage() {} func init() { proto.RegisterType((*APIGroup)(nil), "k8s.io.kubernetes.pkg.api.unversioned.APIGroup") @@ -1278,6 +1264,220 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *APIGroup) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&APIGroup{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Versions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Versions), "GroupVersionForDiscovery", "GroupVersionForDiscovery", 1), `&`, ``, 1) + `,`, + `PreferredVersion:` + strings.Replace(strings.Replace(this.PreferredVersion.String(), "GroupVersionForDiscovery", "GroupVersionForDiscovery", 1), `&`, ``, 1) + `,`, + `ServerAddressByClientCIDRs:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ServerAddressByClientCIDRs), "ServerAddressByClientCIDR", "ServerAddressByClientCIDR", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *APIGroupList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&APIGroupList{`, + `Groups:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Groups), "APIGroup", "APIGroup", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *APIResource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&APIResource{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Namespaced:` + fmt.Sprintf("%v", this.Namespaced) + `,`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `}`, + }, "") + return s +} +func (this *APIResourceList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&APIResourceList{`, + `GroupVersion:` + fmt.Sprintf("%v", this.GroupVersion) + `,`, + `APIResources:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.APIResources), "APIResource", "APIResource", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Duration) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Duration{`, + `Duration:` + fmt.Sprintf("%v", this.Duration) + `,`, + `}`, + }, "") + return s +} +func (this *ExportOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ExportOptions{`, + `Export:` + fmt.Sprintf("%v", this.Export) + `,`, + `Exact:` + fmt.Sprintf("%v", this.Exact) + `,`, + `}`, + }, "") + return s +} +func (this *GroupVersionForDiscovery) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GroupVersionForDiscovery{`, + `GroupVersion:` + fmt.Sprintf("%v", this.GroupVersion) + `,`, + `Version:` + fmt.Sprintf("%v", this.Version) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelector) String() string { + if this == nil { + return "nil" + } + keysForMatchLabels := make([]string, 0, len(this.MatchLabels)) + for k := range this.MatchLabels { + keysForMatchLabels = append(keysForMatchLabels, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMatchLabels) + mapStringForMatchLabels := "map[string]string{" + for _, k := range keysForMatchLabels { + mapStringForMatchLabels += fmt.Sprintf("%v: %v,", k, this.MatchLabels[k]) + } + mapStringForMatchLabels += "}" + s := strings.Join([]string{`&LabelSelector{`, + `MatchLabels:` + mapStringForMatchLabels + `,`, + `MatchExpressions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.MatchExpressions), "LabelSelectorRequirement", "LabelSelectorRequirement", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelectorRequirement) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LabelSelectorRequirement{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Values:` + fmt.Sprintf("%v", this.Values) + `,`, + `}`, + }, "") + return s +} +func (this *ListMeta) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ListMeta{`, + `SelfLink:` + fmt.Sprintf("%v", this.SelfLink) + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `}`, + }, "") + return s +} +func (this *RootPaths) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RootPaths{`, + `Paths:` + fmt.Sprintf("%v", this.Paths) + `,`, + `}`, + }, "") + return s +} +func (this *ServerAddressByClientCIDR) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServerAddressByClientCIDR{`, + `ClientCIDR:` + fmt.Sprintf("%v", this.ClientCIDR) + `,`, + `ServerAddress:` + fmt.Sprintf("%v", this.ServerAddress) + `,`, + `}`, + }, "") + return s +} +func (this *Status) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Status{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "ListMeta", 1), `&`, ``, 1) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Details:` + strings.Replace(fmt.Sprintf("%v", this.Details), "StatusDetails", "StatusDetails", 1) + `,`, + `Code:` + fmt.Sprintf("%v", this.Code) + `,`, + `}`, + }, "") + return s +} +func (this *StatusCause) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StatusCause{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Field:` + fmt.Sprintf("%v", this.Field) + `,`, + `}`, + }, "") + return s +} +func (this *StatusDetails) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StatusDetails{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Group:` + fmt.Sprintf("%v", this.Group) + `,`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Causes:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Causes), "StatusCause", "StatusCause", 1), `&`, ``, 1) + `,`, + `RetryAfterSeconds:` + fmt.Sprintf("%v", this.RetryAfterSeconds) + `,`, + `}`, + }, "") + return s +} +func (this *Timestamp) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Timestamp{`, + `Seconds:` + fmt.Sprintf("%v", this.Seconds) + `,`, + `Nanos:` + fmt.Sprintf("%v", this.Nanos) + `,`, + `}`, + }, "") + return s +} +func (this *TypeMeta) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TypeMeta{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *APIGroup) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.proto b/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.proto index e26cbd7b3e8b..cab7058aac1b 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -144,7 +144,7 @@ message GroupVersion { } // GroupVersion contains the "group/version" and "version" string of a version. -// It is made a struct to keep extensiblity. +// It is made a struct to keep extensibility. message GroupVersionForDiscovery { // groupVersion specifies the API group and version in the form "group/version" optional string groupVersion = 1; @@ -221,7 +221,7 @@ message ListMeta { // Value must be treated as opaque by clients and passed unmodified back to the server. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency optional string resourceVersion = 2; } @@ -245,12 +245,12 @@ message ServerAddressByClientCIDR { // Status is a return value for calls that don't return other objects. message Status { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional ListMeta metadata = 1; // Status of the operation. // One of: "Success" or "Failure". - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional string status = 2; // A human-readable description of the status of this operation. @@ -311,7 +311,7 @@ message StatusDetails { // The kind attribute of the resource associated with the status StatusReason. // On some operations may differ from the requested resource Kind. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional string kind = 3; // The Causes array includes more details associated with the StatusReason @@ -328,6 +328,7 @@ message StatusDetails { // // +protobuf.options.marshal=false // +protobuf.as=Timestamp +// +protobuf.options.(gogoproto.goproto_stringer)=false message Time { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to @@ -365,13 +366,13 @@ message TypeMeta { // Servers may infer this from the endpoint the client submits requests to. // Cannot be updated. // In CamelCase. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional string kind = 1; // APIVersion defines the versioned schema of this representation of an object. // Servers should convert recognized schemas to the latest internal value, and // may reject unrecognized values. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#resources + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources optional string apiVersion = 2; } diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/group_version.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/group_version.go index 167002c3fc71..8f7478921713 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/group_version.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/group_version.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/helpers.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/helpers.go index b71297ec5fb5..cb2f2c5cfd0c 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -64,6 +64,35 @@ func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) { return selector, nil } +// LabelSelectorAsMap converts the LabelSelector api type into a map of strings, ie. the +// original structure of a label selector. Operators that cannot be converted into plain +// labels (Exists, DoesNotExist, NotIn, and In with more than one value) will result in +// an error. +func LabelSelectorAsMap(ps *LabelSelector) (map[string]string, error) { + if ps == nil { + return nil, nil + } + selector := map[string]string{} + for k, v := range ps.MatchLabels { + selector[k] = v + } + for _, expr := range ps.MatchExpressions { + switch expr.Operator { + case LabelSelectorOpIn: + if len(expr.Values) != 1 { + return selector, fmt.Errorf("operator %q without a single value cannot be converted into the old label selector format", expr.Operator) + } + // Should we do anything in case this will override a previous key-value pair? + selector[expr.Key] = expr.Values[0] + case LabelSelectorOpNotIn, LabelSelectorOpExists, LabelSelectorOpDoesNotExist: + return selector, fmt.Errorf("operator %q cannot be converted into the old label selector format", expr.Operator) + default: + return selector, fmt.Errorf("%q is not a valid selector operator", expr.Operator) + } + } + return selector, nil +} + // ParseToLabelSelector parses a string representing a selector into a LabelSelector object. // Note: This function should be kept in sync with the parser in pkg/labels/selector.go func ParseToLabelSelector(selector string) (*LabelSelector, error) { diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/meta.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/meta.go index b82b1990e1ea..48009da162b5 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/meta.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/meta.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/register.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/register.go index f8dbd83711ce..9af0566931d5 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/register.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/time.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/time.go index df94bbe72c89..7e6281a20522 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/time.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/time.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,10 +29,23 @@ import ( // // +protobuf.options.marshal=false // +protobuf.as=Timestamp +// +protobuf.options.(gogoproto.goproto_stringer)=false type Time struct { time.Time `protobuf:"-"` } +// DeepCopy returns a deep-copy of the Time value. The underlying time.Time +// type is effectively immutable in the time API, so it is safe to +// copy-by-assign, despite the presence of (unexported) Pointer fields. +func (t Time) DeepCopy() Time { + return t +} + +// String returns the representation of the time. +func (t Time) String() string { + return t.Time.String() +} + // NewTime returns a wrapped instance of the provided time func NewTime(time time.Time) Time { return Time{time} diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/time_proto.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/time_proto.go index 496d5d98ce2c..ba25e9164f5b 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/time_proto.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/time_proto.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/types.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/types.go index 11afcc2b783e..7d632b496b14 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/types.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -35,13 +35,13 @@ type TypeMeta struct { // Servers may infer this from the endpoint the client submits requests to. // Cannot be updated. // In CamelCase. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"` // APIVersion defines the versioned schema of this representation of an object. // Servers should convert recognized schemas to the latest internal value, and // may reject unrecognized values. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#resources + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"` } @@ -58,7 +58,7 @@ type ListMeta struct { // Value must be treated as opaque by clients and passed unmodified back to the server. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,2,opt,name=resourceVersion"` } @@ -75,12 +75,12 @@ type ExportOptions struct { type Status struct { TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Status of the operation. // One of: "Success" or "Failure". - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status string `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` // A human-readable description of the status of this operation. Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` @@ -112,7 +112,7 @@ type StatusDetails struct { Group string `json:"group,omitempty" protobuf:"bytes,2,opt,name=group"` // The kind attribute of the resource associated with the status StatusReason. // On some operations may differ from the requested resource Kind. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty" protobuf:"bytes,3,opt,name=kind"` // The Causes array includes more details associated with the StatusReason // failure. Not all StatusReasons may provide detailed causes. @@ -357,7 +357,7 @@ type ServerAddressByClientCIDR struct { } // GroupVersion contains the "group/version" and "version" string of a version. -// It is made a struct to keep extensiblity. +// It is made a struct to keep extensibility. type GroupVersionForDiscovery struct { // groupVersion specifies the API group and version in the form "group/version" GroupVersion string `json:"groupVersion" protobuf:"bytes,1,opt,name=groupVersion"` diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go index 2cad1b535fe7..3f08115a6cf0 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -90,7 +90,7 @@ func (ExportOptions) SwaggerDoc() map[string]string { } var map_GroupVersionForDiscovery = map[string]string{ - "": "GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensiblity.", + "": "GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensibility.", "groupVersion": "groupVersion specifies the API group and version in the form \"group/version\"", "version": "version specifies the version in the form of \"version\". This is to save the clients the trouble of splitting the GroupVersion.", } @@ -123,7 +123,7 @@ func (LabelSelectorRequirement) SwaggerDoc() map[string]string { var map_ListMeta = map[string]string{ "": "ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.", "selfLink": "SelfLink is a URL representing this object. Populated by the system. Read-only.", - "resourceVersion": "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency", + "resourceVersion": "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency", } func (ListMeta) SwaggerDoc() map[string]string { @@ -159,8 +159,8 @@ func (ServerAddressByClientCIDR) SwaggerDoc() map[string]string { var map_Status = map[string]string{ "": "Status is a return value for calls that don't return other objects.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "status": "Status of the operation. One of: \"Success\" or \"Failure\". More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "status": "Status of the operation. One of: \"Success\" or \"Failure\". More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", "message": "A human-readable description of the status of this operation.", "reason": "A machine-readable description of why this operation is in the \"Failure\" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it.", "details": "Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type.", @@ -186,7 +186,7 @@ var map_StatusDetails = map[string]string{ "": "StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.", "name": "The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).", "group": "The group attribute of the resource associated with the status StatusReason.", - "kind": "The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "kind": "The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "causes": "The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.", "retryAfterSeconds": "If specified, the time in seconds before the operation should be retried.", } @@ -197,8 +197,8 @@ func (StatusDetails) SwaggerDoc() map[string]string { var map_TypeMeta = map[string]string{ "": "TypeMeta describes an individual object in an API response or request with strings representing the type of the object and its API schema version. Structures that are versioned or persisted should inline TypeMeta.", - "kind": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "apiVersion": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#resources", + "kind": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "apiVersion": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources", } func (TypeMeta) SwaggerDoc() map[string]string { diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go index 47852e3e29f2..ecb968bdcb10 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/well_known_labels.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/well_known_labels.go index 08e4f68892b7..318c6eebf1f0 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/unversioned/well_known_labels.go +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/well_known_labels.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/unversioned/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/api/unversioned/zz_generated.deepcopy.go new file mode 100644 index 000000000000..627bb817ecbf --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/api/unversioned/zz_generated.deepcopy.go @@ -0,0 +1,390 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package unversioned + +import ( + conversion "k8s.io/kubernetes/pkg/conversion" + time "time" +) + +func DeepCopy_unversioned_APIGroup(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIGroup) + out := out.(*APIGroup) + out.TypeMeta = in.TypeMeta + out.Name = in.Name + if in.Versions != nil { + in, out := &in.Versions, &out.Versions + *out = make([]GroupVersionForDiscovery, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Versions = nil + } + out.PreferredVersion = in.PreferredVersion + if in.ServerAddressByClientCIDRs != nil { + in, out := &in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs + *out = make([]ServerAddressByClientCIDR, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ServerAddressByClientCIDRs = nil + } + return nil + } +} + +func DeepCopy_unversioned_APIGroupList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIGroupList) + out := out.(*APIGroupList) + out.TypeMeta = in.TypeMeta + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]APIGroup, len(*in)) + for i := range *in { + if err := DeepCopy_unversioned_APIGroup(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Groups = nil + } + return nil + } +} + +func DeepCopy_unversioned_APIResource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIResource) + out := out.(*APIResource) + out.Name = in.Name + out.Namespaced = in.Namespaced + out.Kind = in.Kind + return nil + } +} + +func DeepCopy_unversioned_APIResourceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIResourceList) + out := out.(*APIResourceList) + out.TypeMeta = in.TypeMeta + out.GroupVersion = in.GroupVersion + if in.APIResources != nil { + in, out := &in.APIResources, &out.APIResources + *out = make([]APIResource, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.APIResources = nil + } + return nil + } +} + +func DeepCopy_unversioned_APIVersions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIVersions) + out := out.(*APIVersions) + out.TypeMeta = in.TypeMeta + if in.Versions != nil { + in, out := &in.Versions, &out.Versions + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Versions = nil + } + if in.ServerAddressByClientCIDRs != nil { + in, out := &in.ServerAddressByClientCIDRs, &out.ServerAddressByClientCIDRs + *out = make([]ServerAddressByClientCIDR, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ServerAddressByClientCIDRs = nil + } + return nil + } +} + +func DeepCopy_unversioned_Duration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Duration) + out := out.(*Duration) + out.Duration = in.Duration + return nil + } +} + +func DeepCopy_unversioned_ExportOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExportOptions) + out := out.(*ExportOptions) + out.TypeMeta = in.TypeMeta + out.Export = in.Export + out.Exact = in.Exact + return nil + } +} + +func DeepCopy_unversioned_GroupKind(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupKind) + out := out.(*GroupKind) + out.Group = in.Group + out.Kind = in.Kind + return nil + } +} + +func DeepCopy_unversioned_GroupResource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupResource) + out := out.(*GroupResource) + out.Group = in.Group + out.Resource = in.Resource + return nil + } +} + +func DeepCopy_unversioned_GroupVersion(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupVersion) + out := out.(*GroupVersion) + out.Group = in.Group + out.Version = in.Version + return nil + } +} + +func DeepCopy_unversioned_GroupVersionForDiscovery(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupVersionForDiscovery) + out := out.(*GroupVersionForDiscovery) + out.GroupVersion = in.GroupVersion + out.Version = in.Version + return nil + } +} + +func DeepCopy_unversioned_GroupVersionKind(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupVersionKind) + out := out.(*GroupVersionKind) + out.Group = in.Group + out.Version = in.Version + out.Kind = in.Kind + return nil + } +} + +func DeepCopy_unversioned_GroupVersionResource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GroupVersionResource) + out := out.(*GroupVersionResource) + out.Group = in.Group + out.Version = in.Version + out.Resource = in.Resource + return nil + } +} + +func DeepCopy_unversioned_LabelSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelector) + out := out.(*LabelSelector) + if in.MatchLabels != nil { + in, out := &in.MatchLabels, &out.MatchLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]LabelSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_unversioned_LabelSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_unversioned_LabelSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelectorRequirement) + out := out.(*LabelSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} + +func DeepCopy_unversioned_ListMeta(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ListMeta) + out := out.(*ListMeta) + out.SelfLink = in.SelfLink + out.ResourceVersion = in.ResourceVersion + return nil + } +} + +func DeepCopy_unversioned_Patch(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Patch) + out := out.(*Patch) + _ = in + _ = out + return nil + } +} + +func DeepCopy_unversioned_RootPaths(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RootPaths) + out := out.(*RootPaths) + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Paths = nil + } + return nil + } +} + +func DeepCopy_unversioned_ServerAddressByClientCIDR(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServerAddressByClientCIDR) + out := out.(*ServerAddressByClientCIDR) + out.ClientCIDR = in.ClientCIDR + out.ServerAddress = in.ServerAddress + return nil + } +} + +func DeepCopy_unversioned_Status(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Status) + out := out.(*Status) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + out.Status = in.Status + out.Message = in.Message + out.Reason = in.Reason + if in.Details != nil { + in, out := &in.Details, &out.Details + *out = new(StatusDetails) + if err := DeepCopy_unversioned_StatusDetails(*in, *out, c); err != nil { + return err + } + } else { + out.Details = nil + } + out.Code = in.Code + return nil + } +} + +func DeepCopy_unversioned_StatusCause(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StatusCause) + out := out.(*StatusCause) + out.Type = in.Type + out.Message = in.Message + out.Field = in.Field + return nil + } +} + +func DeepCopy_unversioned_StatusDetails(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StatusDetails) + out := out.(*StatusDetails) + out.Name = in.Name + out.Group = in.Group + out.Kind = in.Kind + if in.Causes != nil { + in, out := &in.Causes, &out.Causes + *out = make([]StatusCause, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Causes = nil + } + out.RetryAfterSeconds = in.RetryAfterSeconds + return nil + } +} + +func DeepCopy_unversioned_Time(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Time) + out := out.(*Time) + if newVal, err := c.DeepCopy(&in.Time); err != nil { + return err + } else { + out.Time = *newVal.(*time.Time) + } + return nil + } +} + +func DeepCopy_unversioned_Timestamp(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Timestamp) + out := out.(*Timestamp) + out.Seconds = in.Seconds + out.Nanos = in.Nanos + return nil + } +} + +func DeepCopy_unversioned_TypeMeta(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TypeMeta) + out := out.(*TypeMeta) + out.Kind = in.Kind + out.APIVersion = in.APIVersion + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/util/group_version.go b/vendor/k8s.io/kubernetes/pkg/api/util/group_version.go index 0cee250234a9..fea2f17f811a 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/util/group_version.go +++ b/vendor/k8s.io/kubernetes/pkg/api/util/group_version.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/conversion.go b/vendor/k8s.io/kubernetes/pkg/api/v1/conversion.go index 98d8b7ed2ab5..f180b3348d75 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,10 +19,13 @@ package v1 import ( "encoding/json" "fmt" + "reflect" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/validation/field" ) const ( @@ -31,6 +34,9 @@ const ( // Value used to identify mirror pods from pre-v1.1 kubelet. mirrorAnnotationValue_1_0 = "mirror" + + // annotation key prefix used to identify non-convertible json paths. + NonConvertibleAnnotationPrefix = "kubernetes.io/non-convertible" ) func addConversionFuncs(scheme *runtime.Scheme) { @@ -43,8 +49,15 @@ func addConversionFuncs(scheme *runtime.Scheme) { Convert_v1_Pod_To_api_Pod, Convert_v1_PodSpec_To_api_PodSpec, Convert_v1_ReplicationControllerSpec_To_api_ReplicationControllerSpec, + Convert_v1_Secret_To_api_Secret, Convert_v1_ServiceSpec_To_api_ServiceSpec, Convert_v1_ResourceList_To_api_ResourceList, + Convert_v1_ReplicationController_to_extensions_ReplicaSet, + Convert_v1_ReplicationControllerSpec_to_extensions_ReplicaSetSpec, + Convert_v1_ReplicationControllerStatus_to_extensions_ReplicaSetStatus, + Convert_extensions_ReplicaSet_to_v1_ReplicationController, + Convert_extensions_ReplicaSetSpec_to_v1_ReplicationControllerSpec, + Convert_extensions_ReplicaSetStatus_to_v1_ReplicationControllerStatus, ) if err != nil { // If one of the conversion functions is malformed, detect it immediately. @@ -198,17 +211,107 @@ func addConversionFuncs(scheme *runtime.Scheme) { } } +func Convert_v1_ReplicationController_to_extensions_ReplicaSet(in *ReplicationController, out *extensions.ReplicaSet, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ReplicationController))(in) + } + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := Convert_v1_ObjectMeta_To_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_v1_ReplicationControllerSpec_to_extensions_ReplicaSetSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1_ReplicationControllerStatus_to_extensions_ReplicaSetStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_v1_ReplicationControllerSpec_to_extensions_ReplicaSetSpec(in *ReplicationControllerSpec, out *extensions.ReplicaSetSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ReplicationControllerSpec))(in) + } + out.Replicas = *in.Replicas + if in.Selector != nil { + api.Convert_map_to_unversioned_LabelSelector(&in.Selector, out.Selector, s) + } + if in.Template != nil { + if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in.Template, &out.Template, s); err != nil { + return err + } + } + return nil +} + +func Convert_v1_ReplicationControllerStatus_to_extensions_ReplicaSetStatus(in *ReplicationControllerStatus, out *extensions.ReplicaSetStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*ReplicationControllerStatus))(in) + } + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil +} + +func Convert_extensions_ReplicaSet_to_v1_ReplicationController(in *extensions.ReplicaSet, out *ReplicationController, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.ReplicaSet))(in) + } + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := Convert_api_ObjectMeta_To_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, s); err != nil { + return err + } + if err := Convert_extensions_ReplicaSetSpec_to_v1_ReplicationControllerSpec(&in.Spec, &out.Spec, s); err != nil { + fieldErr, ok := err.(*field.Error) + if !ok { + return err + } + if out.Annotations == nil { + out.Annotations = make(map[string]string) + } + out.Annotations[NonConvertibleAnnotationPrefix+"/"+fieldErr.Field] = reflect.ValueOf(fieldErr.BadValue).String() + } + if err := Convert_extensions_ReplicaSetStatus_to_v1_ReplicationControllerStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_extensions_ReplicaSetSpec_to_v1_ReplicationControllerSpec(in *extensions.ReplicaSetSpec, out *ReplicationControllerSpec, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.ReplicaSetSpec))(in) + } + out.Replicas = new(int32) + *out.Replicas = in.Replicas + var invalidErr error + if in.Selector != nil { + invalidErr = api.Convert_unversioned_LabelSelector_to_map(in.Selector, &out.Selector, s) + } + out.Template = new(PodTemplateSpec) + if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, out.Template, s); err != nil { + return err + } + return invalidErr +} + +func Convert_extensions_ReplicaSetStatus_to_v1_ReplicationControllerStatus(in *extensions.ReplicaSetStatus, out *ReplicationControllerStatus, s conversion.Scope) error { + if defaulting, found := s.DefaultingInterface(reflect.TypeOf(*in)); found { + defaulting.(func(*extensions.ReplicaSetStatus))(in) + } + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil +} + func Convert_api_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *api.ReplicationControllerSpec, out *ReplicationControllerSpec, s conversion.Scope) error { out.Replicas = &in.Replicas out.Selector = in.Selector - //if in.TemplateRef != nil { - // out.TemplateRef = new(ObjectReference) - // if err := Convert_api_ObjectReference_To_v1_ObjectReference(in.TemplateRef, out.TemplateRef, s); err != nil { - // return err - // } - //} else { - // out.TemplateRef = nil - //} if in.Template != nil { out.Template = new(PodTemplateSpec) if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(in.Template, out.Template, s); err != nil { @@ -223,15 +326,6 @@ func Convert_api_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *a func Convert_v1_ReplicationControllerSpec_To_api_ReplicationControllerSpec(in *ReplicationControllerSpec, out *api.ReplicationControllerSpec, s conversion.Scope) error { out.Replicas = *in.Replicas out.Selector = in.Selector - - //if in.TemplateRef != nil { - // out.TemplateRef = new(api.ObjectReference) - // if err := Convert_v1_ObjectReference_To_api_ObjectReference(in.TemplateRef, out.TemplateRef, s); err != nil { - // return err - // } - //} else { - // out.TemplateRef = nil - //} if in.Template != nil { out.Template = new(api.PodTemplateSpec) if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in.Template, out.Template, s); err != nil { @@ -359,124 +453,34 @@ func Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(in *PodTemplateSpec, out // The following two PodSpec conversions are done here to support ServiceAccount // as an alias for ServiceAccountName. func Convert_api_PodSpec_To_v1_PodSpec(in *api.PodSpec, out *PodSpec, s conversion.Scope) error { - if in.Volumes != nil { - out.Volumes = make([]Volume, len(in.Volumes)) - for i := range in.Volumes { - if err := Convert_api_Volume_To_v1_Volume(&in.Volumes[i], &out.Volumes[i], s); err != nil { - return err - } - } - } else { - out.Volumes = nil - } - if in.InitContainers != nil { - out.InitContainers = make([]Container, len(in.InitContainers)) - for i := range in.InitContainers { - if err := Convert_api_Container_To_v1_Container(&in.InitContainers[i], &out.InitContainers[i], s); err != nil { - return err - } - } - } else { - out.InitContainers = nil - } - if in.Containers != nil { - out.Containers = make([]Container, len(in.Containers)) - for i := range in.Containers { - if err := Convert_api_Container_To_v1_Container(&in.Containers[i], &out.Containers[i], s); err != nil { - return err - } - } - } else { - out.Containers = nil + if err := autoConvert_api_PodSpec_To_v1_PodSpec(in, out, s); err != nil { + return err } - out.RestartPolicy = RestartPolicy(in.RestartPolicy) - out.TerminationGracePeriodSeconds = in.TerminationGracePeriodSeconds - out.ActiveDeadlineSeconds = in.ActiveDeadlineSeconds - out.DNSPolicy = DNSPolicy(in.DNSPolicy) - out.NodeSelector = in.NodeSelector - - out.ServiceAccountName = in.ServiceAccountName // DeprecatedServiceAccount is an alias for ServiceAccountName. out.DeprecatedServiceAccount = in.ServiceAccountName - out.NodeName = in.NodeName - if in.SecurityContext != nil { - out.SecurityContext = new(PodSecurityContext) - if err := Convert_api_PodSecurityContext_To_v1_PodSecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { - return err - } + if in.SecurityContext != nil { // the host namespace fields have to be handled here for backward compatibility // with v1.0.0 out.HostPID = in.SecurityContext.HostPID out.HostNetwork = in.SecurityContext.HostNetwork out.HostIPC = in.SecurityContext.HostIPC } - if in.ImagePullSecrets != nil { - out.ImagePullSecrets = make([]LocalObjectReference, len(in.ImagePullSecrets)) - for i := range in.ImagePullSecrets { - if err := Convert_api_LocalObjectReference_To_v1_LocalObjectReference(&in.ImagePullSecrets[i], &out.ImagePullSecrets[i], s); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - out.Hostname = in.Hostname - out.Subdomain = in.Subdomain + return nil } func Convert_v1_PodSpec_To_api_PodSpec(in *PodSpec, out *api.PodSpec, s conversion.Scope) error { - SetDefaults_PodSpec(in) - if in.Volumes != nil { - out.Volumes = make([]api.Volume, len(in.Volumes)) - for i := range in.Volumes { - if err := Convert_v1_Volume_To_api_Volume(&in.Volumes[i], &out.Volumes[i], s); err != nil { - return err - } - } - } else { - out.Volumes = nil - } - if in.InitContainers != nil { - out.InitContainers = make([]api.Container, len(in.InitContainers)) - for i := range in.InitContainers { - if err := Convert_v1_Container_To_api_Container(&in.InitContainers[i], &out.InitContainers[i], s); err != nil { - return err - } - } - } else { - out.InitContainers = nil - } - if in.Containers != nil { - out.Containers = make([]api.Container, len(in.Containers)) - for i := range in.Containers { - if err := Convert_v1_Container_To_api_Container(&in.Containers[i], &out.Containers[i], s); err != nil { - return err - } - } - } else { - out.Containers = nil + if err := autoConvert_v1_PodSpec_To_api_PodSpec(in, out, s); err != nil { + return err } - out.RestartPolicy = api.RestartPolicy(in.RestartPolicy) - out.TerminationGracePeriodSeconds = in.TerminationGracePeriodSeconds - out.ActiveDeadlineSeconds = in.ActiveDeadlineSeconds - out.DNSPolicy = api.DNSPolicy(in.DNSPolicy) - out.NodeSelector = in.NodeSelector + // We support DeprecatedServiceAccount as an alias for ServiceAccountName. // If both are specified, ServiceAccountName (the new field) wins. - out.ServiceAccountName = in.ServiceAccountName if in.ServiceAccountName == "" { out.ServiceAccountName = in.DeprecatedServiceAccount } - out.NodeName = in.NodeName - if in.SecurityContext != nil { - out.SecurityContext = new(api.PodSecurityContext) - if err := Convert_v1_PodSecurityContext_To_api_PodSecurityContext(in.SecurityContext, out.SecurityContext, s); err != nil { - return err - } - } // the host namespace fields have to be handled specially for backward compatibility // with v1.0.0 @@ -486,18 +490,7 @@ func Convert_v1_PodSpec_To_api_PodSpec(in *PodSpec, out *api.PodSpec, s conversi out.SecurityContext.HostNetwork = in.HostNetwork out.SecurityContext.HostPID = in.HostPID out.SecurityContext.HostIPC = in.HostIPC - if in.ImagePullSecrets != nil { - out.ImagePullSecrets = make([]api.LocalObjectReference, len(in.ImagePullSecrets)) - for i := range in.ImagePullSecrets { - if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&in.ImagePullSecrets[i], &out.ImagePullSecrets[i], s); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - out.Hostname = in.Hostname - out.Subdomain = in.Subdomain + return nil } @@ -598,6 +591,24 @@ func Convert_api_ServiceSpec_To_v1_ServiceSpec(in *api.ServiceSpec, out *Service return nil } +func Convert_v1_Secret_To_api_Secret(in *Secret, out *api.Secret, s conversion.Scope) error { + if err := autoConvert_v1_Secret_To_api_Secret(in, out, s); err != nil { + return err + } + + // StringData overwrites Data + if len(in.StringData) > 0 { + if out.Data == nil { + out.Data = map[string][]byte{} + } + for k, v := range in.StringData { + out.Data[k] = []byte(v) + } + } + + return nil +} + func Convert_v1_ServiceSpec_To_api_ServiceSpec(in *ServiceSpec, out *api.ServiceSpec, s conversion.Scope) error { if err := autoConvert_v1_ServiceSpec_To_api_ServiceSpec(in, out, s); err != nil { return err diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go deleted file mode 100644 index e7d59684a707..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/deep_copy_generated.go +++ /dev/null @@ -1,3261 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1 - -import ( - api "k8s.io/kubernetes/pkg/api" - resource "k8s.io/kubernetes/pkg/api/resource" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" - runtime "k8s.io/kubernetes/pkg/runtime" - types "k8s.io/kubernetes/pkg/types" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1_AWSElasticBlockStoreVolumeSource, - DeepCopy_v1_Affinity, - DeepCopy_v1_AttachedVolume, - DeepCopy_v1_AzureFileVolumeSource, - DeepCopy_v1_Binding, - DeepCopy_v1_Capabilities, - DeepCopy_v1_CephFSVolumeSource, - DeepCopy_v1_CinderVolumeSource, - DeepCopy_v1_ComponentCondition, - DeepCopy_v1_ComponentStatus, - DeepCopy_v1_ComponentStatusList, - DeepCopy_v1_ConfigMap, - DeepCopy_v1_ConfigMapKeySelector, - DeepCopy_v1_ConfigMapList, - DeepCopy_v1_ConfigMapVolumeSource, - DeepCopy_v1_Container, - DeepCopy_v1_ContainerImage, - DeepCopy_v1_ContainerPort, - DeepCopy_v1_ContainerState, - DeepCopy_v1_ContainerStateRunning, - DeepCopy_v1_ContainerStateTerminated, - DeepCopy_v1_ContainerStateWaiting, - DeepCopy_v1_ContainerStatus, - DeepCopy_v1_DaemonEndpoint, - DeepCopy_v1_DeleteOptions, - DeepCopy_v1_DownwardAPIVolumeFile, - DeepCopy_v1_DownwardAPIVolumeSource, - DeepCopy_v1_EmptyDirVolumeSource, - DeepCopy_v1_EndpointAddress, - DeepCopy_v1_EndpointPort, - DeepCopy_v1_EndpointSubset, - DeepCopy_v1_Endpoints, - DeepCopy_v1_EndpointsList, - DeepCopy_v1_EnvVar, - DeepCopy_v1_EnvVarSource, - DeepCopy_v1_Event, - DeepCopy_v1_EventList, - DeepCopy_v1_EventSource, - DeepCopy_v1_ExecAction, - DeepCopy_v1_ExportOptions, - DeepCopy_v1_FCVolumeSource, - DeepCopy_v1_FlexVolumeSource, - DeepCopy_v1_FlockerVolumeSource, - DeepCopy_v1_GCEPersistentDiskVolumeSource, - DeepCopy_v1_GitRepoVolumeSource, - DeepCopy_v1_GlusterfsVolumeSource, - DeepCopy_v1_HTTPGetAction, - DeepCopy_v1_HTTPHeader, - DeepCopy_v1_Handler, - DeepCopy_v1_HostPathVolumeSource, - DeepCopy_v1_ISCSIVolumeSource, - DeepCopy_v1_KeyToPath, - DeepCopy_v1_Lifecycle, - DeepCopy_v1_LimitRange, - DeepCopy_v1_LimitRangeItem, - DeepCopy_v1_LimitRangeList, - DeepCopy_v1_LimitRangeSpec, - DeepCopy_v1_List, - DeepCopy_v1_ListOptions, - DeepCopy_v1_LoadBalancerIngress, - DeepCopy_v1_LoadBalancerStatus, - DeepCopy_v1_LocalObjectReference, - DeepCopy_v1_NFSVolumeSource, - DeepCopy_v1_Namespace, - DeepCopy_v1_NamespaceList, - DeepCopy_v1_NamespaceSpec, - DeepCopy_v1_NamespaceStatus, - DeepCopy_v1_Node, - DeepCopy_v1_NodeAddress, - DeepCopy_v1_NodeAffinity, - DeepCopy_v1_NodeCondition, - DeepCopy_v1_NodeDaemonEndpoints, - DeepCopy_v1_NodeList, - DeepCopy_v1_NodeProxyOptions, - DeepCopy_v1_NodeSelector, - DeepCopy_v1_NodeSelectorRequirement, - DeepCopy_v1_NodeSelectorTerm, - DeepCopy_v1_NodeSpec, - DeepCopy_v1_NodeStatus, - DeepCopy_v1_NodeSystemInfo, - DeepCopy_v1_ObjectFieldSelector, - DeepCopy_v1_ObjectMeta, - DeepCopy_v1_ObjectReference, - DeepCopy_v1_OwnerReference, - DeepCopy_v1_PersistentVolume, - DeepCopy_v1_PersistentVolumeClaim, - DeepCopy_v1_PersistentVolumeClaimList, - DeepCopy_v1_PersistentVolumeClaimSpec, - DeepCopy_v1_PersistentVolumeClaimStatus, - DeepCopy_v1_PersistentVolumeClaimVolumeSource, - DeepCopy_v1_PersistentVolumeList, - DeepCopy_v1_PersistentVolumeSource, - DeepCopy_v1_PersistentVolumeSpec, - DeepCopy_v1_PersistentVolumeStatus, - DeepCopy_v1_Pod, - DeepCopy_v1_PodAffinity, - DeepCopy_v1_PodAffinityTerm, - DeepCopy_v1_PodAntiAffinity, - DeepCopy_v1_PodAttachOptions, - DeepCopy_v1_PodCondition, - DeepCopy_v1_PodExecOptions, - DeepCopy_v1_PodList, - DeepCopy_v1_PodLogOptions, - DeepCopy_v1_PodProxyOptions, - DeepCopy_v1_PodSecurityContext, - DeepCopy_v1_PodSpec, - DeepCopy_v1_PodStatus, - DeepCopy_v1_PodStatusResult, - DeepCopy_v1_PodTemplate, - DeepCopy_v1_PodTemplateList, - DeepCopy_v1_PodTemplateSpec, - DeepCopy_v1_Preconditions, - DeepCopy_v1_PreferredSchedulingTerm, - DeepCopy_v1_Probe, - DeepCopy_v1_RBDVolumeSource, - DeepCopy_v1_RangeAllocation, - DeepCopy_v1_ReplicationController, - DeepCopy_v1_ReplicationControllerList, - DeepCopy_v1_ReplicationControllerSpec, - DeepCopy_v1_ReplicationControllerStatus, - DeepCopy_v1_ResourceFieldSelector, - DeepCopy_v1_ResourceQuota, - DeepCopy_v1_ResourceQuotaList, - DeepCopy_v1_ResourceQuotaSpec, - DeepCopy_v1_ResourceQuotaStatus, - DeepCopy_v1_ResourceRequirements, - DeepCopy_v1_SELinuxOptions, - DeepCopy_v1_Secret, - DeepCopy_v1_SecretKeySelector, - DeepCopy_v1_SecretList, - DeepCopy_v1_SecretVolumeSource, - DeepCopy_v1_SecurityContext, - DeepCopy_v1_SerializedReference, - DeepCopy_v1_Service, - DeepCopy_v1_ServiceAccount, - DeepCopy_v1_ServiceAccountList, - DeepCopy_v1_ServiceList, - DeepCopy_v1_ServicePort, - DeepCopy_v1_ServiceProxyOptions, - DeepCopy_v1_ServiceSpec, - DeepCopy_v1_ServiceStatus, - DeepCopy_v1_TCPSocketAction, - DeepCopy_v1_Taint, - DeepCopy_v1_Toleration, - DeepCopy_v1_Volume, - DeepCopy_v1_VolumeMount, - DeepCopy_v1_VolumeSource, - DeepCopy_v1_VsphereVirtualDiskVolumeSource, - DeepCopy_v1_WeightedPodAffinityTerm, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1_AWSElasticBlockStoreVolumeSource(in AWSElasticBlockStoreVolumeSource, out *AWSElasticBlockStoreVolumeSource, c *conversion.Cloner) error { - out.VolumeID = in.VolumeID - out.FSType = in.FSType - out.Partition = in.Partition - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_Affinity(in Affinity, out *Affinity, c *conversion.Cloner) error { - if in.NodeAffinity != nil { - in, out := in.NodeAffinity, &out.NodeAffinity - *out = new(NodeAffinity) - if err := DeepCopy_v1_NodeAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.NodeAffinity = nil - } - if in.PodAffinity != nil { - in, out := in.PodAffinity, &out.PodAffinity - *out = new(PodAffinity) - if err := DeepCopy_v1_PodAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.PodAffinity = nil - } - if in.PodAntiAffinity != nil { - in, out := in.PodAntiAffinity, &out.PodAntiAffinity - *out = new(PodAntiAffinity) - if err := DeepCopy_v1_PodAntiAffinity(*in, *out, c); err != nil { - return err - } - } else { - out.PodAntiAffinity = nil - } - return nil -} - -func DeepCopy_v1_AttachedVolume(in AttachedVolume, out *AttachedVolume, c *conversion.Cloner) error { - out.Name = in.Name - out.DevicePath = in.DevicePath - return nil -} - -func DeepCopy_v1_AzureFileVolumeSource(in AzureFileVolumeSource, out *AzureFileVolumeSource, c *conversion.Cloner) error { - out.SecretName = in.SecretName - out.ShareName = in.ShareName - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_Binding(in Binding, out *Binding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectReference(in.Target, &out.Target, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_Capabilities(in Capabilities, out *Capabilities, c *conversion.Cloner) error { - if in.Add != nil { - in, out := in.Add, &out.Add - *out = make([]Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Add = nil - } - if in.Drop != nil { - in, out := in.Drop, &out.Drop - *out = make([]Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Drop = nil - } - return nil -} - -func DeepCopy_v1_CephFSVolumeSource(in CephFSVolumeSource, out *CephFSVolumeSource, c *conversion.Cloner) error { - if in.Monitors != nil { - in, out := in.Monitors, &out.Monitors - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Monitors = nil - } - out.Path = in.Path - out.User = in.User - out.SecretFile = in.SecretFile - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_v1_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_CinderVolumeSource(in CinderVolumeSource, out *CinderVolumeSource, c *conversion.Cloner) error { - out.VolumeID = in.VolumeID - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_ComponentCondition(in ComponentCondition, out *ComponentCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - out.Message = in.Message - out.Error = in.Error - return nil -} - -func DeepCopy_v1_ComponentStatus(in ComponentStatus, out *ComponentStatus, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]ComponentCondition, len(in)) - for i := range in { - if err := DeepCopy_v1_ComponentCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - return nil -} - -func DeepCopy_v1_ComponentStatusList(in ComponentStatusList, out *ComponentStatusList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ComponentStatus, len(in)) - for i := range in { - if err := DeepCopy_v1_ComponentStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ConfigMap(in ConfigMap, out *ConfigMap, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_v1_ConfigMapKeySelector(in ConfigMapKeySelector, out *ConfigMapKeySelector, c *conversion.Cloner) error { - if err := DeepCopy_v1_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - out.Key = in.Key - return nil -} - -func DeepCopy_v1_ConfigMapList(in ConfigMapList, out *ConfigMapList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ConfigMap, len(in)) - for i := range in { - if err := DeepCopy_v1_ConfigMap(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ConfigMapVolumeSource(in ConfigMapVolumeSource, out *ConfigMapVolumeSource, c *conversion.Cloner) error { - if err := DeepCopy_v1_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]KeyToPath, len(in)) - for i := range in { - if err := DeepCopy_v1_KeyToPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_Container(in Container, out *Container, c *conversion.Cloner) error { - out.Name = in.Name - out.Image = in.Image - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - if in.Args != nil { - in, out := in.Args, &out.Args - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Args = nil - } - out.WorkingDir = in.WorkingDir - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]ContainerPort, len(in)) - for i := range in { - if err := DeepCopy_v1_ContainerPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.Env != nil { - in, out := in.Env, &out.Env - *out = make([]EnvVar, len(in)) - for i := range in { - if err := DeepCopy_v1_EnvVar(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Env = nil - } - if err := DeepCopy_v1_ResourceRequirements(in.Resources, &out.Resources, c); err != nil { - return err - } - if in.VolumeMounts != nil { - in, out := in.VolumeMounts, &out.VolumeMounts - *out = make([]VolumeMount, len(in)) - for i := range in { - if err := DeepCopy_v1_VolumeMount(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumeMounts = nil - } - if in.LivenessProbe != nil { - in, out := in.LivenessProbe, &out.LivenessProbe - *out = new(Probe) - if err := DeepCopy_v1_Probe(*in, *out, c); err != nil { - return err - } - } else { - out.LivenessProbe = nil - } - if in.ReadinessProbe != nil { - in, out := in.ReadinessProbe, &out.ReadinessProbe - *out = new(Probe) - if err := DeepCopy_v1_Probe(*in, *out, c); err != nil { - return err - } - } else { - out.ReadinessProbe = nil - } - if in.Lifecycle != nil { - in, out := in.Lifecycle, &out.Lifecycle - *out = new(Lifecycle) - if err := DeepCopy_v1_Lifecycle(*in, *out, c); err != nil { - return err - } - } else { - out.Lifecycle = nil - } - out.TerminationMessagePath = in.TerminationMessagePath - out.ImagePullPolicy = in.ImagePullPolicy - if in.SecurityContext != nil { - in, out := in.SecurityContext, &out.SecurityContext - *out = new(SecurityContext) - if err := DeepCopy_v1_SecurityContext(*in, *out, c); err != nil { - return err - } - } else { - out.SecurityContext = nil - } - out.Stdin = in.Stdin - out.StdinOnce = in.StdinOnce - out.TTY = in.TTY - return nil -} - -func DeepCopy_v1_ContainerImage(in ContainerImage, out *ContainerImage, c *conversion.Cloner) error { - if in.Names != nil { - in, out := in.Names, &out.Names - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Names = nil - } - out.SizeBytes = in.SizeBytes - return nil -} - -func DeepCopy_v1_ContainerPort(in ContainerPort, out *ContainerPort, c *conversion.Cloner) error { - out.Name = in.Name - out.HostPort = in.HostPort - out.ContainerPort = in.ContainerPort - out.Protocol = in.Protocol - out.HostIP = in.HostIP - return nil -} - -func DeepCopy_v1_ContainerState(in ContainerState, out *ContainerState, c *conversion.Cloner) error { - if in.Waiting != nil { - in, out := in.Waiting, &out.Waiting - *out = new(ContainerStateWaiting) - if err := DeepCopy_v1_ContainerStateWaiting(*in, *out, c); err != nil { - return err - } - } else { - out.Waiting = nil - } - if in.Running != nil { - in, out := in.Running, &out.Running - *out = new(ContainerStateRunning) - if err := DeepCopy_v1_ContainerStateRunning(*in, *out, c); err != nil { - return err - } - } else { - out.Running = nil - } - if in.Terminated != nil { - in, out := in.Terminated, &out.Terminated - *out = new(ContainerStateTerminated) - if err := DeepCopy_v1_ContainerStateTerminated(*in, *out, c); err != nil { - return err - } - } else { - out.Terminated = nil - } - return nil -} - -func DeepCopy_v1_ContainerStateRunning(in ContainerStateRunning, out *ContainerStateRunning, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_Time(in.StartedAt, &out.StartedAt, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ContainerStateTerminated(in ContainerStateTerminated, out *ContainerStateTerminated, c *conversion.Cloner) error { - out.ExitCode = in.ExitCode - out.Signal = in.Signal - out.Reason = in.Reason - out.Message = in.Message - if err := unversioned.DeepCopy_unversioned_Time(in.StartedAt, &out.StartedAt, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.FinishedAt, &out.FinishedAt, c); err != nil { - return err - } - out.ContainerID = in.ContainerID - return nil -} - -func DeepCopy_v1_ContainerStateWaiting(in ContainerStateWaiting, out *ContainerStateWaiting, c *conversion.Cloner) error { - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v1_ContainerStatus(in ContainerStatus, out *ContainerStatus, c *conversion.Cloner) error { - out.Name = in.Name - if err := DeepCopy_v1_ContainerState(in.State, &out.State, c); err != nil { - return err - } - if err := DeepCopy_v1_ContainerState(in.LastTerminationState, &out.LastTerminationState, c); err != nil { - return err - } - out.Ready = in.Ready - out.RestartCount = in.RestartCount - out.Image = in.Image - out.ImageID = in.ImageID - out.ContainerID = in.ContainerID - return nil -} - -func DeepCopy_v1_DaemonEndpoint(in DaemonEndpoint, out *DaemonEndpoint, c *conversion.Cloner) error { - out.Port = in.Port - return nil -} - -func DeepCopy_v1_DeleteOptions(in DeleteOptions, out *DeleteOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.GracePeriodSeconds != nil { - in, out := in.GracePeriodSeconds, &out.GracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.GracePeriodSeconds = nil - } - if in.Preconditions != nil { - in, out := in.Preconditions, &out.Preconditions - *out = new(Preconditions) - if err := DeepCopy_v1_Preconditions(*in, *out, c); err != nil { - return err - } - } else { - out.Preconditions = nil - } - if in.OrphanDependents != nil { - in, out := in.OrphanDependents, &out.OrphanDependents - *out = new(bool) - **out = *in - } else { - out.OrphanDependents = nil - } - return nil -} - -func DeepCopy_v1_DownwardAPIVolumeFile(in DownwardAPIVolumeFile, out *DownwardAPIVolumeFile, c *conversion.Cloner) error { - out.Path = in.Path - if in.FieldRef != nil { - in, out := in.FieldRef, &out.FieldRef - *out = new(ObjectFieldSelector) - if err := DeepCopy_v1_ObjectFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.FieldRef = nil - } - if in.ResourceFieldRef != nil { - in, out := in.ResourceFieldRef, &out.ResourceFieldRef - *out = new(ResourceFieldSelector) - if err := DeepCopy_v1_ResourceFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceFieldRef = nil - } - return nil -} - -func DeepCopy_v1_DownwardAPIVolumeSource(in DownwardAPIVolumeSource, out *DownwardAPIVolumeSource, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]DownwardAPIVolumeFile, len(in)) - for i := range in { - if err := DeepCopy_v1_DownwardAPIVolumeFile(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_EmptyDirVolumeSource(in EmptyDirVolumeSource, out *EmptyDirVolumeSource, c *conversion.Cloner) error { - out.Medium = in.Medium - return nil -} - -func DeepCopy_v1_EndpointAddress(in EndpointAddress, out *EndpointAddress, c *conversion.Cloner) error { - out.IP = in.IP - out.Hostname = in.Hostname - if in.TargetRef != nil { - in, out := in.TargetRef, &out.TargetRef - *out = new(ObjectReference) - if err := DeepCopy_v1_ObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.TargetRef = nil - } - return nil -} - -func DeepCopy_v1_EndpointPort(in EndpointPort, out *EndpointPort, c *conversion.Cloner) error { - out.Name = in.Name - out.Port = in.Port - out.Protocol = in.Protocol - return nil -} - -func DeepCopy_v1_EndpointSubset(in EndpointSubset, out *EndpointSubset, c *conversion.Cloner) error { - if in.Addresses != nil { - in, out := in.Addresses, &out.Addresses - *out = make([]EndpointAddress, len(in)) - for i := range in { - if err := DeepCopy_v1_EndpointAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Addresses = nil - } - if in.NotReadyAddresses != nil { - in, out := in.NotReadyAddresses, &out.NotReadyAddresses - *out = make([]EndpointAddress, len(in)) - for i := range in { - if err := DeepCopy_v1_EndpointAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.NotReadyAddresses = nil - } - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]EndpointPort, len(in)) - for i := range in { - if err := DeepCopy_v1_EndpointPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - return nil -} - -func DeepCopy_v1_Endpoints(in Endpoints, out *Endpoints, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subsets != nil { - in, out := in.Subsets, &out.Subsets - *out = make([]EndpointSubset, len(in)) - for i := range in { - if err := DeepCopy_v1_EndpointSubset(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subsets = nil - } - return nil -} - -func DeepCopy_v1_EndpointsList(in EndpointsList, out *EndpointsList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Endpoints, len(in)) - for i := range in { - if err := DeepCopy_v1_Endpoints(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_EnvVar(in EnvVar, out *EnvVar, c *conversion.Cloner) error { - out.Name = in.Name - out.Value = in.Value - if in.ValueFrom != nil { - in, out := in.ValueFrom, &out.ValueFrom - *out = new(EnvVarSource) - if err := DeepCopy_v1_EnvVarSource(*in, *out, c); err != nil { - return err - } - } else { - out.ValueFrom = nil - } - return nil -} - -func DeepCopy_v1_EnvVarSource(in EnvVarSource, out *EnvVarSource, c *conversion.Cloner) error { - if in.FieldRef != nil { - in, out := in.FieldRef, &out.FieldRef - *out = new(ObjectFieldSelector) - if err := DeepCopy_v1_ObjectFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.FieldRef = nil - } - if in.ResourceFieldRef != nil { - in, out := in.ResourceFieldRef, &out.ResourceFieldRef - *out = new(ResourceFieldSelector) - if err := DeepCopy_v1_ResourceFieldSelector(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceFieldRef = nil - } - if in.ConfigMapKeyRef != nil { - in, out := in.ConfigMapKeyRef, &out.ConfigMapKeyRef - *out = new(ConfigMapKeySelector) - if err := DeepCopy_v1_ConfigMapKeySelector(*in, *out, c); err != nil { - return err - } - } else { - out.ConfigMapKeyRef = nil - } - if in.SecretKeyRef != nil { - in, out := in.SecretKeyRef, &out.SecretKeyRef - *out = new(SecretKeySelector) - if err := DeepCopy_v1_SecretKeySelector(*in, *out, c); err != nil { - return err - } - } else { - out.SecretKeyRef = nil - } - return nil -} - -func DeepCopy_v1_Event(in Event, out *Event, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectReference(in.InvolvedObject, &out.InvolvedObject, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - if err := DeepCopy_v1_EventSource(in.Source, &out.Source, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.FirstTimestamp, &out.FirstTimestamp, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTimestamp, &out.LastTimestamp, c); err != nil { - return err - } - out.Count = in.Count - out.Type = in.Type - return nil -} - -func DeepCopy_v1_EventList(in EventList, out *EventList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Event, len(in)) - for i := range in { - if err := DeepCopy_v1_Event(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_EventSource(in EventSource, out *EventSource, c *conversion.Cloner) error { - out.Component = in.Component - out.Host = in.Host - return nil -} - -func DeepCopy_v1_ExecAction(in ExecAction, out *ExecAction, c *conversion.Cloner) error { - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - return nil -} - -func DeepCopy_v1_ExportOptions(in ExportOptions, out *ExportOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Export = in.Export - out.Exact = in.Exact - return nil -} - -func DeepCopy_v1_FCVolumeSource(in FCVolumeSource, out *FCVolumeSource, c *conversion.Cloner) error { - if in.TargetWWNs != nil { - in, out := in.TargetWWNs, &out.TargetWWNs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.TargetWWNs = nil - } - if in.Lun != nil { - in, out := in.Lun, &out.Lun - *out = new(int32) - **out = *in - } else { - out.Lun = nil - } - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_FlexVolumeSource(in FlexVolumeSource, out *FlexVolumeSource, c *conversion.Cloner) error { - out.Driver = in.Driver - out.FSType = in.FSType - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_v1_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - if in.Options != nil { - in, out := in.Options, &out.Options - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Options = nil - } - return nil -} - -func DeepCopy_v1_FlockerVolumeSource(in FlockerVolumeSource, out *FlockerVolumeSource, c *conversion.Cloner) error { - out.DatasetName = in.DatasetName - return nil -} - -func DeepCopy_v1_GCEPersistentDiskVolumeSource(in GCEPersistentDiskVolumeSource, out *GCEPersistentDiskVolumeSource, c *conversion.Cloner) error { - out.PDName = in.PDName - out.FSType = in.FSType - out.Partition = in.Partition - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_GitRepoVolumeSource(in GitRepoVolumeSource, out *GitRepoVolumeSource, c *conversion.Cloner) error { - out.Repository = in.Repository - out.Revision = in.Revision - out.Directory = in.Directory - return nil -} - -func DeepCopy_v1_GlusterfsVolumeSource(in GlusterfsVolumeSource, out *GlusterfsVolumeSource, c *conversion.Cloner) error { - out.EndpointsName = in.EndpointsName - out.Path = in.Path - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_HTTPGetAction(in HTTPGetAction, out *HTTPGetAction, c *conversion.Cloner) error { - out.Path = in.Path - if err := intstr.DeepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { - return err - } - out.Host = in.Host - out.Scheme = in.Scheme - if in.HTTPHeaders != nil { - in, out := in.HTTPHeaders, &out.HTTPHeaders - *out = make([]HTTPHeader, len(in)) - for i := range in { - if err := DeepCopy_v1_HTTPHeader(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.HTTPHeaders = nil - } - return nil -} - -func DeepCopy_v1_HTTPHeader(in HTTPHeader, out *HTTPHeader, c *conversion.Cloner) error { - out.Name = in.Name - out.Value = in.Value - return nil -} - -func DeepCopy_v1_Handler(in Handler, out *Handler, c *conversion.Cloner) error { - if in.Exec != nil { - in, out := in.Exec, &out.Exec - *out = new(ExecAction) - if err := DeepCopy_v1_ExecAction(*in, *out, c); err != nil { - return err - } - } else { - out.Exec = nil - } - if in.HTTPGet != nil { - in, out := in.HTTPGet, &out.HTTPGet - *out = new(HTTPGetAction) - if err := DeepCopy_v1_HTTPGetAction(*in, *out, c); err != nil { - return err - } - } else { - out.HTTPGet = nil - } - if in.TCPSocket != nil { - in, out := in.TCPSocket, &out.TCPSocket - *out = new(TCPSocketAction) - if err := DeepCopy_v1_TCPSocketAction(*in, *out, c); err != nil { - return err - } - } else { - out.TCPSocket = nil - } - return nil -} - -func DeepCopy_v1_HostPathVolumeSource(in HostPathVolumeSource, out *HostPathVolumeSource, c *conversion.Cloner) error { - out.Path = in.Path - return nil -} - -func DeepCopy_v1_ISCSIVolumeSource(in ISCSIVolumeSource, out *ISCSIVolumeSource, c *conversion.Cloner) error { - out.TargetPortal = in.TargetPortal - out.IQN = in.IQN - out.Lun = in.Lun - out.ISCSIInterface = in.ISCSIInterface - out.FSType = in.FSType - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_KeyToPath(in KeyToPath, out *KeyToPath, c *conversion.Cloner) error { - out.Key = in.Key - out.Path = in.Path - return nil -} - -func DeepCopy_v1_Lifecycle(in Lifecycle, out *Lifecycle, c *conversion.Cloner) error { - if in.PostStart != nil { - in, out := in.PostStart, &out.PostStart - *out = new(Handler) - if err := DeepCopy_v1_Handler(*in, *out, c); err != nil { - return err - } - } else { - out.PostStart = nil - } - if in.PreStop != nil { - in, out := in.PreStop, &out.PreStop - *out = new(Handler) - if err := DeepCopy_v1_Handler(*in, *out, c); err != nil { - return err - } - } else { - out.PreStop = nil - } - return nil -} - -func DeepCopy_v1_LimitRange(in LimitRange, out *LimitRange, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_LimitRangeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_LimitRangeItem(in LimitRangeItem, out *LimitRangeItem, c *conversion.Cloner) error { - out.Type = in.Type - if in.Max != nil { - in, out := in.Max, &out.Max - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Max = nil - } - if in.Min != nil { - in, out := in.Min, &out.Min - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Min = nil - } - if in.Default != nil { - in, out := in.Default, &out.Default - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Default = nil - } - if in.DefaultRequest != nil { - in, out := in.DefaultRequest, &out.DefaultRequest - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.DefaultRequest = nil - } - if in.MaxLimitRequestRatio != nil { - in, out := in.MaxLimitRequestRatio, &out.MaxLimitRequestRatio - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.MaxLimitRequestRatio = nil - } - return nil -} - -func DeepCopy_v1_LimitRangeList(in LimitRangeList, out *LimitRangeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]LimitRange, len(in)) - for i := range in { - if err := DeepCopy_v1_LimitRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_LimitRangeSpec(in LimitRangeSpec, out *LimitRangeSpec, c *conversion.Cloner) error { - if in.Limits != nil { - in, out := in.Limits, &out.Limits - *out = make([]LimitRangeItem, len(in)) - for i := range in { - if err := DeepCopy_v1_LimitRangeItem(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Limits = nil - } - return nil -} - -func DeepCopy_v1_List(in List, out *List, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]runtime.RawExtension, len(in)) - for i := range in { - if err := runtime.DeepCopy_runtime_RawExtension(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ListOptions(in ListOptions, out *ListOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.LabelSelector = in.LabelSelector - out.FieldSelector = in.FieldSelector - out.Watch = in.Watch - out.ResourceVersion = in.ResourceVersion - if in.TimeoutSeconds != nil { - in, out := in.TimeoutSeconds, &out.TimeoutSeconds - *out = new(int64) - **out = *in - } else { - out.TimeoutSeconds = nil - } - return nil -} - -func DeepCopy_v1_LoadBalancerIngress(in LoadBalancerIngress, out *LoadBalancerIngress, c *conversion.Cloner) error { - out.IP = in.IP - out.Hostname = in.Hostname - return nil -} - -func DeepCopy_v1_LoadBalancerStatus(in LoadBalancerStatus, out *LoadBalancerStatus, c *conversion.Cloner) error { - if in.Ingress != nil { - in, out := in.Ingress, &out.Ingress - *out = make([]LoadBalancerIngress, len(in)) - for i := range in { - if err := DeepCopy_v1_LoadBalancerIngress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ingress = nil - } - return nil -} - -func DeepCopy_v1_LocalObjectReference(in LocalObjectReference, out *LocalObjectReference, c *conversion.Cloner) error { - out.Name = in.Name - return nil -} - -func DeepCopy_v1_NFSVolumeSource(in NFSVolumeSource, out *NFSVolumeSource, c *conversion.Cloner) error { - out.Server = in.Server - out.Path = in.Path - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_Namespace(in Namespace, out *Namespace, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_NamespaceSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_NamespaceStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_NamespaceList(in NamespaceList, out *NamespaceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Namespace, len(in)) - for i := range in { - if err := DeepCopy_v1_Namespace(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_NamespaceSpec(in NamespaceSpec, out *NamespaceSpec, c *conversion.Cloner) error { - if in.Finalizers != nil { - in, out := in.Finalizers, &out.Finalizers - *out = make([]FinalizerName, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Finalizers = nil - } - return nil -} - -func DeepCopy_v1_NamespaceStatus(in NamespaceStatus, out *NamespaceStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - return nil -} - -func DeepCopy_v1_Node(in Node, out *Node, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_NodeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_NodeStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_NodeAddress(in NodeAddress, out *NodeAddress, c *conversion.Cloner) error { - out.Type = in.Type - out.Address = in.Address - return nil -} - -func DeepCopy_v1_NodeAffinity(in NodeAffinity, out *NodeAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = new(NodeSelector) - if err := DeepCopy_v1_NodeSelector(*in, *out, c); err != nil { - return err - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]PreferredSchedulingTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_PreferredSchedulingTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_v1_NodeCondition(in NodeCondition, out *NodeCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastHeartbeatTime, &out.LastHeartbeatTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v1_NodeDaemonEndpoints(in NodeDaemonEndpoints, out *NodeDaemonEndpoints, c *conversion.Cloner) error { - if err := DeepCopy_v1_DaemonEndpoint(in.KubeletEndpoint, &out.KubeletEndpoint, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_NodeList(in NodeList, out *NodeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Node, len(in)) - for i := range in { - if err := DeepCopy_v1_Node(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_NodeProxyOptions(in NodeProxyOptions, out *NodeProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_v1_NodeSelector(in NodeSelector, out *NodeSelector, c *conversion.Cloner) error { - if in.NodeSelectorTerms != nil { - in, out := in.NodeSelectorTerms, &out.NodeSelectorTerms - *out = make([]NodeSelectorTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_NodeSelectorTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.NodeSelectorTerms = nil - } - return nil -} - -func DeepCopy_v1_NodeSelectorRequirement(in NodeSelectorRequirement, out *NodeSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} - -func DeepCopy_v1_NodeSelectorTerm(in NodeSelectorTerm, out *NodeSelectorTerm, c *conversion.Cloner) error { - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]NodeSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_v1_NodeSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_v1_NodeSpec(in NodeSpec, out *NodeSpec, c *conversion.Cloner) error { - out.PodCIDR = in.PodCIDR - out.ExternalID = in.ExternalID - out.ProviderID = in.ProviderID - out.Unschedulable = in.Unschedulable - return nil -} - -func DeepCopy_v1_NodeStatus(in NodeStatus, out *NodeStatus, c *conversion.Cloner) error { - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - if in.Allocatable != nil { - in, out := in.Allocatable, &out.Allocatable - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Allocatable = nil - } - out.Phase = in.Phase - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]NodeCondition, len(in)) - for i := range in { - if err := DeepCopy_v1_NodeCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.Addresses != nil { - in, out := in.Addresses, &out.Addresses - *out = make([]NodeAddress, len(in)) - for i := range in { - if err := DeepCopy_v1_NodeAddress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Addresses = nil - } - if err := DeepCopy_v1_NodeDaemonEndpoints(in.DaemonEndpoints, &out.DaemonEndpoints, c); err != nil { - return err - } - if err := DeepCopy_v1_NodeSystemInfo(in.NodeInfo, &out.NodeInfo, c); err != nil { - return err - } - if in.Images != nil { - in, out := in.Images, &out.Images - *out = make([]ContainerImage, len(in)) - for i := range in { - if err := DeepCopy_v1_ContainerImage(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Images = nil - } - if in.VolumesInUse != nil { - in, out := in.VolumesInUse, &out.VolumesInUse - *out = make([]UniqueVolumeName, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.VolumesInUse = nil - } - if in.VolumesAttached != nil { - in, out := in.VolumesAttached, &out.VolumesAttached - *out = make([]AttachedVolume, len(in)) - for i := range in { - if err := DeepCopy_v1_AttachedVolume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumesAttached = nil - } - return nil -} - -func DeepCopy_v1_NodeSystemInfo(in NodeSystemInfo, out *NodeSystemInfo, c *conversion.Cloner) error { - out.MachineID = in.MachineID - out.SystemUUID = in.SystemUUID - out.BootID = in.BootID - out.KernelVersion = in.KernelVersion - out.OSImage = in.OSImage - out.ContainerRuntimeVersion = in.ContainerRuntimeVersion - out.KubeletVersion = in.KubeletVersion - out.KubeProxyVersion = in.KubeProxyVersion - out.OperatingSystem = in.OperatingSystem - out.Architecture = in.Architecture - return nil -} - -func DeepCopy_v1_ObjectFieldSelector(in ObjectFieldSelector, out *ObjectFieldSelector, c *conversion.Cloner) error { - out.APIVersion = in.APIVersion - out.FieldPath = in.FieldPath - return nil -} - -func DeepCopy_v1_ObjectMeta(in ObjectMeta, out *ObjectMeta, c *conversion.Cloner) error { - out.Name = in.Name - out.GenerateName = in.GenerateName - out.Namespace = in.Namespace - out.SelfLink = in.SelfLink - out.UID = in.UID - out.ResourceVersion = in.ResourceVersion - out.Generation = in.Generation - if err := unversioned.DeepCopy_unversioned_Time(in.CreationTimestamp, &out.CreationTimestamp, c); err != nil { - return err - } - if in.DeletionTimestamp != nil { - in, out := in.DeletionTimestamp, &out.DeletionTimestamp - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.DeletionTimestamp = nil - } - if in.DeletionGracePeriodSeconds != nil { - in, out := in.DeletionGracePeriodSeconds, &out.DeletionGracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.DeletionGracePeriodSeconds = nil - } - if in.Labels != nil { - in, out := in.Labels, &out.Labels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Labels = nil - } - if in.Annotations != nil { - in, out := in.Annotations, &out.Annotations - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Annotations = nil - } - if in.OwnerReferences != nil { - in, out := in.OwnerReferences, &out.OwnerReferences - *out = make([]OwnerReference, len(in)) - for i := range in { - if err := DeepCopy_v1_OwnerReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.OwnerReferences = nil - } - if in.Finalizers != nil { - in, out := in.Finalizers, &out.Finalizers - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Finalizers = nil - } - return nil -} - -func DeepCopy_v1_ObjectReference(in ObjectReference, out *ObjectReference, c *conversion.Cloner) error { - out.Kind = in.Kind - out.Namespace = in.Namespace - out.Name = in.Name - out.UID = in.UID - out.APIVersion = in.APIVersion - out.ResourceVersion = in.ResourceVersion - out.FieldPath = in.FieldPath - return nil -} - -func DeepCopy_v1_OwnerReference(in OwnerReference, out *OwnerReference, c *conversion.Cloner) error { - out.APIVersion = in.APIVersion - out.Kind = in.Kind - out.Name = in.Name - out.UID = in.UID - if in.Controller != nil { - in, out := in.Controller, &out.Controller - *out = new(bool) - **out = *in - } else { - out.Controller = nil - } - return nil -} - -func DeepCopy_v1_PersistentVolume(in PersistentVolume, out *PersistentVolume, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PersistentVolumeSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_PersistentVolumeStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_PersistentVolumeClaim(in PersistentVolumeClaim, out *PersistentVolumeClaim, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PersistentVolumeClaimSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_PersistentVolumeClaimStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_PersistentVolumeClaimList(in PersistentVolumeClaimList, out *PersistentVolumeClaimList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PersistentVolumeClaim, len(in)) - for i := range in { - if err := DeepCopy_v1_PersistentVolumeClaim(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_PersistentVolumeClaimSpec(in PersistentVolumeClaimSpec, out *PersistentVolumeClaimSpec, c *conversion.Cloner) error { - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := DeepCopy_v1_ResourceRequirements(in.Resources, &out.Resources, c); err != nil { - return err - } - out.VolumeName = in.VolumeName - return nil -} - -func DeepCopy_v1_PersistentVolumeClaimStatus(in PersistentVolumeClaimStatus, out *PersistentVolumeClaimStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - return nil -} - -func DeepCopy_v1_PersistentVolumeClaimVolumeSource(in PersistentVolumeClaimVolumeSource, out *PersistentVolumeClaimVolumeSource, c *conversion.Cloner) error { - out.ClaimName = in.ClaimName - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_PersistentVolumeList(in PersistentVolumeList, out *PersistentVolumeList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PersistentVolume, len(in)) - for i := range in { - if err := DeepCopy_v1_PersistentVolume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_PersistentVolumeSource(in PersistentVolumeSource, out *PersistentVolumeSource, c *conversion.Cloner) error { - if in.GCEPersistentDisk != nil { - in, out := in.GCEPersistentDisk, &out.GCEPersistentDisk - *out = new(GCEPersistentDiskVolumeSource) - if err := DeepCopy_v1_GCEPersistentDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GCEPersistentDisk = nil - } - if in.AWSElasticBlockStore != nil { - in, out := in.AWSElasticBlockStore, &out.AWSElasticBlockStore - *out = new(AWSElasticBlockStoreVolumeSource) - if err := DeepCopy_v1_AWSElasticBlockStoreVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AWSElasticBlockStore = nil - } - if in.HostPath != nil { - in, out := in.HostPath, &out.HostPath - *out = new(HostPathVolumeSource) - if err := DeepCopy_v1_HostPathVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.HostPath = nil - } - if in.Glusterfs != nil { - in, out := in.Glusterfs, &out.Glusterfs - *out = new(GlusterfsVolumeSource) - if err := DeepCopy_v1_GlusterfsVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Glusterfs = nil - } - if in.NFS != nil { - in, out := in.NFS, &out.NFS - *out = new(NFSVolumeSource) - if err := DeepCopy_v1_NFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.NFS = nil - } - if in.RBD != nil { - in, out := in.RBD, &out.RBD - *out = new(RBDVolumeSource) - if err := DeepCopy_v1_RBDVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.RBD = nil - } - if in.ISCSI != nil { - in, out := in.ISCSI, &out.ISCSI - *out = new(ISCSIVolumeSource) - if err := DeepCopy_v1_ISCSIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ISCSI = nil - } - if in.Cinder != nil { - in, out := in.Cinder, &out.Cinder - *out = new(CinderVolumeSource) - if err := DeepCopy_v1_CinderVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Cinder = nil - } - if in.CephFS != nil { - in, out := in.CephFS, &out.CephFS - *out = new(CephFSVolumeSource) - if err := DeepCopy_v1_CephFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.CephFS = nil - } - if in.FC != nil { - in, out := in.FC, &out.FC - *out = new(FCVolumeSource) - if err := DeepCopy_v1_FCVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FC = nil - } - if in.Flocker != nil { - in, out := in.Flocker, &out.Flocker - *out = new(FlockerVolumeSource) - if err := DeepCopy_v1_FlockerVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Flocker = nil - } - if in.FlexVolume != nil { - in, out := in.FlexVolume, &out.FlexVolume - *out = new(FlexVolumeSource) - if err := DeepCopy_v1_FlexVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FlexVolume = nil - } - if in.AzureFile != nil { - in, out := in.AzureFile, &out.AzureFile - *out = new(AzureFileVolumeSource) - if err := DeepCopy_v1_AzureFileVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AzureFile = nil - } - if in.VsphereVolume != nil { - in, out := in.VsphereVolume, &out.VsphereVolume - *out = new(VsphereVirtualDiskVolumeSource) - if err := DeepCopy_v1_VsphereVirtualDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.VsphereVolume = nil - } - return nil -} - -func DeepCopy_v1_PersistentVolumeSpec(in PersistentVolumeSpec, out *PersistentVolumeSpec, c *conversion.Cloner) error { - if in.Capacity != nil { - in, out := in.Capacity, &out.Capacity - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Capacity = nil - } - if err := DeepCopy_v1_PersistentVolumeSource(in.PersistentVolumeSource, &out.PersistentVolumeSource, c); err != nil { - return err - } - if in.AccessModes != nil { - in, out := in.AccessModes, &out.AccessModes - *out = make([]PersistentVolumeAccessMode, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AccessModes = nil - } - if in.ClaimRef != nil { - in, out := in.ClaimRef, &out.ClaimRef - *out = new(ObjectReference) - if err := DeepCopy_v1_ObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.ClaimRef = nil - } - out.PersistentVolumeReclaimPolicy = in.PersistentVolumeReclaimPolicy - return nil -} - -func DeepCopy_v1_PersistentVolumeStatus(in PersistentVolumeStatus, out *PersistentVolumeStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - out.Message = in.Message - out.Reason = in.Reason - return nil -} - -func DeepCopy_v1_Pod(in Pod, out *Pod, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PodSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_PodStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_PodAffinity(in PodAffinity, out *PodAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = make([]PodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_PodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]WeightedPodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_WeightedPodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_v1_PodAffinityTerm(in PodAffinityTerm, out *PodAffinityTerm, c *conversion.Cloner) error { - if in.LabelSelector != nil { - in, out := in.LabelSelector, &out.LabelSelector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.LabelSelector = nil - } - if in.Namespaces != nil { - in, out := in.Namespaces, &out.Namespaces - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Namespaces = nil - } - out.TopologyKey = in.TopologyKey - return nil -} - -func DeepCopy_v1_PodAntiAffinity(in PodAntiAffinity, out *PodAntiAffinity, c *conversion.Cloner) error { - if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution - *out = make([]PodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_PodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.RequiredDuringSchedulingIgnoredDuringExecution = nil - } - if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { - in, out := in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution - *out = make([]WeightedPodAffinityTerm, len(in)) - for i := range in { - if err := DeepCopy_v1_WeightedPodAffinityTerm(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.PreferredDuringSchedulingIgnoredDuringExecution = nil - } - return nil -} - -func DeepCopy_v1_PodAttachOptions(in PodAttachOptions, out *PodAttachOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Stdin = in.Stdin - out.Stdout = in.Stdout - out.Stderr = in.Stderr - out.TTY = in.TTY - out.Container = in.Container - return nil -} - -func DeepCopy_v1_PodCondition(in PodCondition, out *PodCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v1_PodExecOptions(in PodExecOptions, out *PodExecOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Stdin = in.Stdin - out.Stdout = in.Stdout - out.Stderr = in.Stderr - out.TTY = in.TTY - out.Container = in.Container - if in.Command != nil { - in, out := in.Command, &out.Command - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Command = nil - } - return nil -} - -func DeepCopy_v1_PodList(in PodList, out *PodList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Pod, len(in)) - for i := range in { - if err := DeepCopy_v1_Pod(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_PodLogOptions(in PodLogOptions, out *PodLogOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Container = in.Container - out.Follow = in.Follow - out.Previous = in.Previous - if in.SinceSeconds != nil { - in, out := in.SinceSeconds, &out.SinceSeconds - *out = new(int64) - **out = *in - } else { - out.SinceSeconds = nil - } - if in.SinceTime != nil { - in, out := in.SinceTime, &out.SinceTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.SinceTime = nil - } - out.Timestamps = in.Timestamps - if in.TailLines != nil { - in, out := in.TailLines, &out.TailLines - *out = new(int64) - **out = *in - } else { - out.TailLines = nil - } - if in.LimitBytes != nil { - in, out := in.LimitBytes, &out.LimitBytes - *out = new(int64) - **out = *in - } else { - out.LimitBytes = nil - } - return nil -} - -func DeepCopy_v1_PodProxyOptions(in PodProxyOptions, out *PodProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_v1_PodSecurityContext(in PodSecurityContext, out *PodSecurityContext, c *conversion.Cloner) error { - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(SELinuxOptions) - if err := DeepCopy_v1_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - if in.RunAsUser != nil { - in, out := in.RunAsUser, &out.RunAsUser - *out = new(int64) - **out = *in - } else { - out.RunAsUser = nil - } - if in.RunAsNonRoot != nil { - in, out := in.RunAsNonRoot, &out.RunAsNonRoot - *out = new(bool) - **out = *in - } else { - out.RunAsNonRoot = nil - } - if in.SupplementalGroups != nil { - in, out := in.SupplementalGroups, &out.SupplementalGroups - *out = make([]int64, len(in)) - copy(*out, in) - } else { - out.SupplementalGroups = nil - } - if in.FSGroup != nil { - in, out := in.FSGroup, &out.FSGroup - *out = new(int64) - **out = *in - } else { - out.FSGroup = nil - } - return nil -} - -func DeepCopy_v1_PodSpec(in PodSpec, out *PodSpec, c *conversion.Cloner) error { - if in.Volumes != nil { - in, out := in.Volumes, &out.Volumes - *out = make([]Volume, len(in)) - for i := range in { - if err := DeepCopy_v1_Volume(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Volumes = nil - } - if in.InitContainers != nil { - in, out := in.InitContainers, &out.InitContainers - *out = make([]Container, len(in)) - for i := range in { - if err := DeepCopy_v1_Container(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.InitContainers = nil - } - if in.Containers != nil { - in, out := in.Containers, &out.Containers - *out = make([]Container, len(in)) - for i := range in { - if err := DeepCopy_v1_Container(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Containers = nil - } - out.RestartPolicy = in.RestartPolicy - if in.TerminationGracePeriodSeconds != nil { - in, out := in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds - *out = new(int64) - **out = *in - } else { - out.TerminationGracePeriodSeconds = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - out.DNSPolicy = in.DNSPolicy - if in.NodeSelector != nil { - in, out := in.NodeSelector, &out.NodeSelector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.NodeSelector = nil - } - out.ServiceAccountName = in.ServiceAccountName - out.DeprecatedServiceAccount = in.DeprecatedServiceAccount - out.NodeName = in.NodeName - out.HostNetwork = in.HostNetwork - out.HostPID = in.HostPID - out.HostIPC = in.HostIPC - if in.SecurityContext != nil { - in, out := in.SecurityContext, &out.SecurityContext - *out = new(PodSecurityContext) - if err := DeepCopy_v1_PodSecurityContext(*in, *out, c); err != nil { - return err - } - } else { - out.SecurityContext = nil - } - if in.ImagePullSecrets != nil { - in, out := in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]LocalObjectReference, len(in)) - for i := range in { - if err := DeepCopy_v1_LocalObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - out.Hostname = in.Hostname - out.Subdomain = in.Subdomain - return nil -} - -func DeepCopy_v1_PodStatus(in PodStatus, out *PodStatus, c *conversion.Cloner) error { - out.Phase = in.Phase - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]PodCondition, len(in)) - for i := range in { - if err := DeepCopy_v1_PodCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - out.Message = in.Message - out.Reason = in.Reason - out.HostIP = in.HostIP - out.PodIP = in.PodIP - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.InitContainerStatuses != nil { - in, out := in.InitContainerStatuses, &out.InitContainerStatuses - *out = make([]ContainerStatus, len(in)) - for i := range in { - if err := DeepCopy_v1_ContainerStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.InitContainerStatuses = nil - } - if in.ContainerStatuses != nil { - in, out := in.ContainerStatuses, &out.ContainerStatuses - *out = make([]ContainerStatus, len(in)) - for i := range in { - if err := DeepCopy_v1_ContainerStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ContainerStatuses = nil - } - return nil -} - -func DeepCopy_v1_PodStatusResult(in PodStatusResult, out *PodStatusResult, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PodStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_PodTemplate(in PodTemplate, out *PodTemplate, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_PodTemplateList(in PodTemplateList, out *PodTemplateList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodTemplate, len(in)) - for i := range in { - if err := DeepCopy_v1_PodTemplate(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_PodTemplateSpec(in PodTemplateSpec, out *PodTemplateSpec, c *conversion.Cloner) error { - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_PodSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_Preconditions(in Preconditions, out *Preconditions, c *conversion.Cloner) error { - if in.UID != nil { - in, out := in.UID, &out.UID - *out = new(types.UID) - **out = *in - } else { - out.UID = nil - } - return nil -} - -func DeepCopy_v1_PreferredSchedulingTerm(in PreferredSchedulingTerm, out *PreferredSchedulingTerm, c *conversion.Cloner) error { - out.Weight = in.Weight - if err := DeepCopy_v1_NodeSelectorTerm(in.Preference, &out.Preference, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_Probe(in Probe, out *Probe, c *conversion.Cloner) error { - if err := DeepCopy_v1_Handler(in.Handler, &out.Handler, c); err != nil { - return err - } - out.InitialDelaySeconds = in.InitialDelaySeconds - out.TimeoutSeconds = in.TimeoutSeconds - out.PeriodSeconds = in.PeriodSeconds - out.SuccessThreshold = in.SuccessThreshold - out.FailureThreshold = in.FailureThreshold - return nil -} - -func DeepCopy_v1_RBDVolumeSource(in RBDVolumeSource, out *RBDVolumeSource, c *conversion.Cloner) error { - if in.CephMonitors != nil { - in, out := in.CephMonitors, &out.CephMonitors - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.CephMonitors = nil - } - out.RBDImage = in.RBDImage - out.FSType = in.FSType - out.RBDPool = in.RBDPool - out.RadosUser = in.RadosUser - out.Keyring = in.Keyring - if in.SecretRef != nil { - in, out := in.SecretRef, &out.SecretRef - *out = new(LocalObjectReference) - if err := DeepCopy_v1_LocalObjectReference(*in, *out, c); err != nil { - return err - } - } else { - out.SecretRef = nil - } - out.ReadOnly = in.ReadOnly - return nil -} - -func DeepCopy_v1_RangeAllocation(in RangeAllocation, out *RangeAllocation, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - out.Range = in.Range - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_v1_ReplicationController(in ReplicationController, out *ReplicationController, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ReplicationControllerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_ReplicationControllerStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ReplicationControllerList(in ReplicationControllerList, out *ReplicationControllerList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ReplicationController, len(in)) - for i := range in { - if err := DeepCopy_v1_ReplicationController(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ReplicationControllerSpec(in ReplicationControllerSpec, out *ReplicationControllerSpec, c *conversion.Cloner) error { - if in.Replicas != nil { - in, out := in.Replicas, &out.Replicas - *out = new(int32) - **out = *in - } else { - out.Replicas = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Selector = nil - } - if in.Template != nil { - in, out := in.Template, &out.Template - *out = new(PodTemplateSpec) - if err := DeepCopy_v1_PodTemplateSpec(*in, *out, c); err != nil { - return err - } - } else { - out.Template = nil - } - return nil -} - -func DeepCopy_v1_ReplicationControllerStatus(in ReplicationControllerStatus, out *ReplicationControllerStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.FullyLabeledReplicas = in.FullyLabeledReplicas - out.ObservedGeneration = in.ObservedGeneration - return nil -} - -func DeepCopy_v1_ResourceFieldSelector(in ResourceFieldSelector, out *ResourceFieldSelector, c *conversion.Cloner) error { - out.ContainerName = in.ContainerName - out.Resource = in.Resource - if err := resource.DeepCopy_resource_Quantity(in.Divisor, &out.Divisor, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ResourceQuota(in ResourceQuota, out *ResourceQuota, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ResourceQuotaSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_ResourceQuotaStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ResourceQuotaList(in ResourceQuotaList, out *ResourceQuotaList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ResourceQuota, len(in)) - for i := range in { - if err := DeepCopy_v1_ResourceQuota(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ResourceQuotaSpec(in ResourceQuotaSpec, out *ResourceQuotaSpec, c *conversion.Cloner) error { - if in.Hard != nil { - in, out := in.Hard, &out.Hard - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Hard = nil - } - if in.Scopes != nil { - in, out := in.Scopes, &out.Scopes - *out = make([]ResourceQuotaScope, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Scopes = nil - } - return nil -} - -func DeepCopy_v1_ResourceQuotaStatus(in ResourceQuotaStatus, out *ResourceQuotaStatus, c *conversion.Cloner) error { - if in.Hard != nil { - in, out := in.Hard, &out.Hard - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Hard = nil - } - if in.Used != nil { - in, out := in.Used, &out.Used - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Used = nil - } - return nil -} - -func DeepCopy_v1_ResourceRequirements(in ResourceRequirements, out *ResourceRequirements, c *conversion.Cloner) error { - if in.Limits != nil { - in, out := in.Limits, &out.Limits - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Limits = nil - } - if in.Requests != nil { - in, out := in.Requests, &out.Requests - *out = make(ResourceList) - for key, val := range in { - newVal := new(resource.Quantity) - if err := resource.DeepCopy_resource_Quantity(val, newVal, c); err != nil { - return err - } - (*out)[key] = *newVal - } - } else { - out.Requests = nil - } - return nil -} - -func DeepCopy_v1_SELinuxOptions(in SELinuxOptions, out *SELinuxOptions, c *conversion.Cloner) error { - out.User = in.User - out.Role = in.Role - out.Type = in.Type - out.Level = in.Level - return nil -} - -func DeepCopy_v1_Secret(in Secret, out *Secret, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make(map[string][]byte) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]byte) - } - } - } else { - out.Data = nil - } - out.Type = in.Type - return nil -} - -func DeepCopy_v1_SecretKeySelector(in SecretKeySelector, out *SecretKeySelector, c *conversion.Cloner) error { - if err := DeepCopy_v1_LocalObjectReference(in.LocalObjectReference, &out.LocalObjectReference, c); err != nil { - return err - } - out.Key = in.Key - return nil -} - -func DeepCopy_v1_SecretList(in SecretList, out *SecretList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Secret, len(in)) - for i := range in { - if err := DeepCopy_v1_Secret(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_SecretVolumeSource(in SecretVolumeSource, out *SecretVolumeSource, c *conversion.Cloner) error { - out.SecretName = in.SecretName - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]KeyToPath, len(in)) - for i := range in { - if err := DeepCopy_v1_KeyToPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_SecurityContext(in SecurityContext, out *SecurityContext, c *conversion.Cloner) error { - if in.Capabilities != nil { - in, out := in.Capabilities, &out.Capabilities - *out = new(Capabilities) - if err := DeepCopy_v1_Capabilities(*in, *out, c); err != nil { - return err - } - } else { - out.Capabilities = nil - } - if in.Privileged != nil { - in, out := in.Privileged, &out.Privileged - *out = new(bool) - **out = *in - } else { - out.Privileged = nil - } - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(SELinuxOptions) - if err := DeepCopy_v1_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - if in.RunAsUser != nil { - in, out := in.RunAsUser, &out.RunAsUser - *out = new(int64) - **out = *in - } else { - out.RunAsUser = nil - } - if in.RunAsNonRoot != nil { - in, out := in.RunAsNonRoot, &out.RunAsNonRoot - *out = new(bool) - **out = *in - } else { - out.RunAsNonRoot = nil - } - if in.ReadOnlyRootFilesystem != nil { - in, out := in.ReadOnlyRootFilesystem, &out.ReadOnlyRootFilesystem - *out = new(bool) - **out = *in - } else { - out.ReadOnlyRootFilesystem = nil - } - return nil -} - -func DeepCopy_v1_SerializedReference(in SerializedReference, out *SerializedReference, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectReference(in.Reference, &out.Reference, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_Service(in Service, out *Service, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ServiceSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_ServiceStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ServiceAccount(in ServiceAccount, out *ServiceAccount, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Secrets != nil { - in, out := in.Secrets, &out.Secrets - *out = make([]ObjectReference, len(in)) - for i := range in { - if err := DeepCopy_v1_ObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Secrets = nil - } - if in.ImagePullSecrets != nil { - in, out := in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]LocalObjectReference, len(in)) - for i := range in { - if err := DeepCopy_v1_LocalObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.ImagePullSecrets = nil - } - return nil -} - -func DeepCopy_v1_ServiceAccountList(in ServiceAccountList, out *ServiceAccountList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ServiceAccount, len(in)) - for i := range in { - if err := DeepCopy_v1_ServiceAccount(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ServiceList(in ServiceList, out *ServiceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Service, len(in)) - for i := range in { - if err := DeepCopy_v1_Service(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_ServicePort(in ServicePort, out *ServicePort, c *conversion.Cloner) error { - out.Name = in.Name - out.Protocol = in.Protocol - out.Port = in.Port - if err := intstr.DeepCopy_intstr_IntOrString(in.TargetPort, &out.TargetPort, c); err != nil { - return err - } - out.NodePort = in.NodePort - return nil -} - -func DeepCopy_v1_ServiceProxyOptions(in ServiceProxyOptions, out *ServiceProxyOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Path = in.Path - return nil -} - -func DeepCopy_v1_ServiceSpec(in ServiceSpec, out *ServiceSpec, c *conversion.Cloner) error { - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]ServicePort, len(in)) - for i := range in { - if err := DeepCopy_v1_ServicePort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Selector = nil - } - out.ClusterIP = in.ClusterIP - out.Type = in.Type - if in.ExternalIPs != nil { - in, out := in.ExternalIPs, &out.ExternalIPs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.ExternalIPs = nil - } - if in.DeprecatedPublicIPs != nil { - in, out := in.DeprecatedPublicIPs, &out.DeprecatedPublicIPs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.DeprecatedPublicIPs = nil - } - out.SessionAffinity = in.SessionAffinity - out.LoadBalancerIP = in.LoadBalancerIP - if in.LoadBalancerSourceRanges != nil { - in, out := in.LoadBalancerSourceRanges, &out.LoadBalancerSourceRanges - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.LoadBalancerSourceRanges = nil - } - return nil -} - -func DeepCopy_v1_ServiceStatus(in ServiceStatus, out *ServiceStatus, c *conversion.Cloner) error { - if err := DeepCopy_v1_LoadBalancerStatus(in.LoadBalancer, &out.LoadBalancer, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_TCPSocketAction(in TCPSocketAction, out *TCPSocketAction, c *conversion.Cloner) error { - if err := intstr.DeepCopy_intstr_IntOrString(in.Port, &out.Port, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_Taint(in Taint, out *Taint, c *conversion.Cloner) error { - out.Key = in.Key - out.Value = in.Value - out.Effect = in.Effect - return nil -} - -func DeepCopy_v1_Toleration(in Toleration, out *Toleration, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - out.Value = in.Value - out.Effect = in.Effect - return nil -} - -func DeepCopy_v1_Volume(in Volume, out *Volume, c *conversion.Cloner) error { - out.Name = in.Name - if err := DeepCopy_v1_VolumeSource(in.VolumeSource, &out.VolumeSource, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_VolumeMount(in VolumeMount, out *VolumeMount, c *conversion.Cloner) error { - out.Name = in.Name - out.ReadOnly = in.ReadOnly - out.MountPath = in.MountPath - out.SubPath = in.SubPath - return nil -} - -func DeepCopy_v1_VolumeSource(in VolumeSource, out *VolumeSource, c *conversion.Cloner) error { - if in.HostPath != nil { - in, out := in.HostPath, &out.HostPath - *out = new(HostPathVolumeSource) - if err := DeepCopy_v1_HostPathVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.HostPath = nil - } - if in.EmptyDir != nil { - in, out := in.EmptyDir, &out.EmptyDir - *out = new(EmptyDirVolumeSource) - if err := DeepCopy_v1_EmptyDirVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.EmptyDir = nil - } - if in.GCEPersistentDisk != nil { - in, out := in.GCEPersistentDisk, &out.GCEPersistentDisk - *out = new(GCEPersistentDiskVolumeSource) - if err := DeepCopy_v1_GCEPersistentDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GCEPersistentDisk = nil - } - if in.AWSElasticBlockStore != nil { - in, out := in.AWSElasticBlockStore, &out.AWSElasticBlockStore - *out = new(AWSElasticBlockStoreVolumeSource) - if err := DeepCopy_v1_AWSElasticBlockStoreVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AWSElasticBlockStore = nil - } - if in.GitRepo != nil { - in, out := in.GitRepo, &out.GitRepo - *out = new(GitRepoVolumeSource) - if err := DeepCopy_v1_GitRepoVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.GitRepo = nil - } - if in.Secret != nil { - in, out := in.Secret, &out.Secret - *out = new(SecretVolumeSource) - if err := DeepCopy_v1_SecretVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Secret = nil - } - if in.NFS != nil { - in, out := in.NFS, &out.NFS - *out = new(NFSVolumeSource) - if err := DeepCopy_v1_NFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.NFS = nil - } - if in.ISCSI != nil { - in, out := in.ISCSI, &out.ISCSI - *out = new(ISCSIVolumeSource) - if err := DeepCopy_v1_ISCSIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ISCSI = nil - } - if in.Glusterfs != nil { - in, out := in.Glusterfs, &out.Glusterfs - *out = new(GlusterfsVolumeSource) - if err := DeepCopy_v1_GlusterfsVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Glusterfs = nil - } - if in.PersistentVolumeClaim != nil { - in, out := in.PersistentVolumeClaim, &out.PersistentVolumeClaim - *out = new(PersistentVolumeClaimVolumeSource) - if err := DeepCopy_v1_PersistentVolumeClaimVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.PersistentVolumeClaim = nil - } - if in.RBD != nil { - in, out := in.RBD, &out.RBD - *out = new(RBDVolumeSource) - if err := DeepCopy_v1_RBDVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.RBD = nil - } - if in.FlexVolume != nil { - in, out := in.FlexVolume, &out.FlexVolume - *out = new(FlexVolumeSource) - if err := DeepCopy_v1_FlexVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FlexVolume = nil - } - if in.Cinder != nil { - in, out := in.Cinder, &out.Cinder - *out = new(CinderVolumeSource) - if err := DeepCopy_v1_CinderVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Cinder = nil - } - if in.CephFS != nil { - in, out := in.CephFS, &out.CephFS - *out = new(CephFSVolumeSource) - if err := DeepCopy_v1_CephFSVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.CephFS = nil - } - if in.Flocker != nil { - in, out := in.Flocker, &out.Flocker - *out = new(FlockerVolumeSource) - if err := DeepCopy_v1_FlockerVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.Flocker = nil - } - if in.DownwardAPI != nil { - in, out := in.DownwardAPI, &out.DownwardAPI - *out = new(DownwardAPIVolumeSource) - if err := DeepCopy_v1_DownwardAPIVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.DownwardAPI = nil - } - if in.FC != nil { - in, out := in.FC, &out.FC - *out = new(FCVolumeSource) - if err := DeepCopy_v1_FCVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.FC = nil - } - if in.AzureFile != nil { - in, out := in.AzureFile, &out.AzureFile - *out = new(AzureFileVolumeSource) - if err := DeepCopy_v1_AzureFileVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.AzureFile = nil - } - if in.ConfigMap != nil { - in, out := in.ConfigMap, &out.ConfigMap - *out = new(ConfigMapVolumeSource) - if err := DeepCopy_v1_ConfigMapVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.ConfigMap = nil - } - if in.VsphereVolume != nil { - in, out := in.VsphereVolume, &out.VsphereVolume - *out = new(VsphereVirtualDiskVolumeSource) - if err := DeepCopy_v1_VsphereVirtualDiskVolumeSource(*in, *out, c); err != nil { - return err - } - } else { - out.VsphereVolume = nil - } - return nil -} - -func DeepCopy_v1_VsphereVirtualDiskVolumeSource(in VsphereVirtualDiskVolumeSource, out *VsphereVirtualDiskVolumeSource, c *conversion.Cloner) error { - out.VolumePath = in.VolumePath - out.FSType = in.FSType - return nil -} - -func DeepCopy_v1_WeightedPodAffinityTerm(in WeightedPodAffinityTerm, out *WeightedPodAffinityTerm, c *conversion.Cloner) error { - out.Weight = in.Weight - if err := DeepCopy_v1_PodAffinityTerm(in.PodAffinityTerm, &out.PodAffinityTerm, c); err != nil { - return err - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/defaults.go b/vendor/k8s.io/kubernetes/pkg/api/v1/defaults.go index c6f11b4ee166..5d6323fb4fe4 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/doc.go b/vendor/k8s.io/kubernetes/pkg/api/v1/doc.go index bf85d77a1695..8849ee1cb13d 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/api + // Package v1 is the v1 version of the API. -// +genconversion=true package v1 diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/api/v1/generated.pb.go index 78477e4bfa01..ee80e293948f 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ limitations under the License. AWSElasticBlockStoreVolumeSource Affinity AttachedVolume + AvoidPods AzureFileVolumeSource Binding Capabilities @@ -130,6 +131,7 @@ limitations under the License. PodLogOptions PodProxyOptions PodSecurityContext + PodSignature PodSpec PodStatus PodStatusResult @@ -137,6 +139,7 @@ limitations under the License. PodTemplateList PodTemplateSpec Preconditions + PreferAvoidPodsEntry PreferredSchedulingTerm Probe RBDVolumeSource @@ -187,6 +190,10 @@ import k8s_io_kubernetes_pkg_runtime "k8s.io/kubernetes/pkg/runtime" import k8s_io_kubernetes_pkg_types "k8s.io/kubernetes/pkg/types" +import strings "strings" +import reflect "reflect" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -194,606 +201,467 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *AWSElasticBlockStoreVolumeSource) Reset() { *m = AWSElasticBlockStoreVolumeSource{} } -func (m *AWSElasticBlockStoreVolumeSource) String() string { return proto.CompactTextString(m) } -func (*AWSElasticBlockStoreVolumeSource) ProtoMessage() {} +func (m *AWSElasticBlockStoreVolumeSource) Reset() { *m = AWSElasticBlockStoreVolumeSource{} } +func (*AWSElasticBlockStoreVolumeSource) ProtoMessage() {} + +func (m *Affinity) Reset() { *m = Affinity{} } +func (*Affinity) ProtoMessage() {} + +func (m *AttachedVolume) Reset() { *m = AttachedVolume{} } +func (*AttachedVolume) ProtoMessage() {} + +func (m *AvoidPods) Reset() { *m = AvoidPods{} } +func (*AvoidPods) ProtoMessage() {} -func (m *Affinity) Reset() { *m = Affinity{} } -func (m *Affinity) String() string { return proto.CompactTextString(m) } -func (*Affinity) ProtoMessage() {} +func (m *AzureFileVolumeSource) Reset() { *m = AzureFileVolumeSource{} } +func (*AzureFileVolumeSource) ProtoMessage() {} -func (m *AttachedVolume) Reset() { *m = AttachedVolume{} } -func (m *AttachedVolume) String() string { return proto.CompactTextString(m) } -func (*AttachedVolume) ProtoMessage() {} +func (m *Binding) Reset() { *m = Binding{} } +func (*Binding) ProtoMessage() {} -func (m *AzureFileVolumeSource) Reset() { *m = AzureFileVolumeSource{} } -func (m *AzureFileVolumeSource) String() string { return proto.CompactTextString(m) } -func (*AzureFileVolumeSource) ProtoMessage() {} +func (m *Capabilities) Reset() { *m = Capabilities{} } +func (*Capabilities) ProtoMessage() {} -func (m *Binding) Reset() { *m = Binding{} } -func (m *Binding) String() string { return proto.CompactTextString(m) } -func (*Binding) ProtoMessage() {} +func (m *CephFSVolumeSource) Reset() { *m = CephFSVolumeSource{} } +func (*CephFSVolumeSource) ProtoMessage() {} -func (m *Capabilities) Reset() { *m = Capabilities{} } -func (m *Capabilities) String() string { return proto.CompactTextString(m) } -func (*Capabilities) ProtoMessage() {} +func (m *CinderVolumeSource) Reset() { *m = CinderVolumeSource{} } +func (*CinderVolumeSource) ProtoMessage() {} -func (m *CephFSVolumeSource) Reset() { *m = CephFSVolumeSource{} } -func (m *CephFSVolumeSource) String() string { return proto.CompactTextString(m) } -func (*CephFSVolumeSource) ProtoMessage() {} +func (m *ComponentCondition) Reset() { *m = ComponentCondition{} } +func (*ComponentCondition) ProtoMessage() {} -func (m *CinderVolumeSource) Reset() { *m = CinderVolumeSource{} } -func (m *CinderVolumeSource) String() string { return proto.CompactTextString(m) } -func (*CinderVolumeSource) ProtoMessage() {} +func (m *ComponentStatus) Reset() { *m = ComponentStatus{} } +func (*ComponentStatus) ProtoMessage() {} -func (m *ComponentCondition) Reset() { *m = ComponentCondition{} } -func (m *ComponentCondition) String() string { return proto.CompactTextString(m) } -func (*ComponentCondition) ProtoMessage() {} +func (m *ComponentStatusList) Reset() { *m = ComponentStatusList{} } +func (*ComponentStatusList) ProtoMessage() {} -func (m *ComponentStatus) Reset() { *m = ComponentStatus{} } -func (m *ComponentStatus) String() string { return proto.CompactTextString(m) } -func (*ComponentStatus) ProtoMessage() {} +func (m *ConfigMap) Reset() { *m = ConfigMap{} } +func (*ConfigMap) ProtoMessage() {} -func (m *ComponentStatusList) Reset() { *m = ComponentStatusList{} } -func (m *ComponentStatusList) String() string { return proto.CompactTextString(m) } -func (*ComponentStatusList) ProtoMessage() {} +func (m *ConfigMapKeySelector) Reset() { *m = ConfigMapKeySelector{} } +func (*ConfigMapKeySelector) ProtoMessage() {} -func (m *ConfigMap) Reset() { *m = ConfigMap{} } -func (m *ConfigMap) String() string { return proto.CompactTextString(m) } -func (*ConfigMap) ProtoMessage() {} +func (m *ConfigMapList) Reset() { *m = ConfigMapList{} } +func (*ConfigMapList) ProtoMessage() {} -func (m *ConfigMapKeySelector) Reset() { *m = ConfigMapKeySelector{} } -func (m *ConfigMapKeySelector) String() string { return proto.CompactTextString(m) } -func (*ConfigMapKeySelector) ProtoMessage() {} +func (m *ConfigMapVolumeSource) Reset() { *m = ConfigMapVolumeSource{} } +func (*ConfigMapVolumeSource) ProtoMessage() {} -func (m *ConfigMapList) Reset() { *m = ConfigMapList{} } -func (m *ConfigMapList) String() string { return proto.CompactTextString(m) } -func (*ConfigMapList) ProtoMessage() {} +func (m *Container) Reset() { *m = Container{} } +func (*Container) ProtoMessage() {} -func (m *ConfigMapVolumeSource) Reset() { *m = ConfigMapVolumeSource{} } -func (m *ConfigMapVolumeSource) String() string { return proto.CompactTextString(m) } -func (*ConfigMapVolumeSource) ProtoMessage() {} +func (m *ContainerImage) Reset() { *m = ContainerImage{} } +func (*ContainerImage) ProtoMessage() {} -func (m *Container) Reset() { *m = Container{} } -func (m *Container) String() string { return proto.CompactTextString(m) } -func (*Container) ProtoMessage() {} +func (m *ContainerPort) Reset() { *m = ContainerPort{} } +func (*ContainerPort) ProtoMessage() {} -func (m *ContainerImage) Reset() { *m = ContainerImage{} } -func (m *ContainerImage) String() string { return proto.CompactTextString(m) } -func (*ContainerImage) ProtoMessage() {} +func (m *ContainerState) Reset() { *m = ContainerState{} } +func (*ContainerState) ProtoMessage() {} -func (m *ContainerPort) Reset() { *m = ContainerPort{} } -func (m *ContainerPort) String() string { return proto.CompactTextString(m) } -func (*ContainerPort) ProtoMessage() {} +func (m *ContainerStateRunning) Reset() { *m = ContainerStateRunning{} } +func (*ContainerStateRunning) ProtoMessage() {} -func (m *ContainerState) Reset() { *m = ContainerState{} } -func (m *ContainerState) String() string { return proto.CompactTextString(m) } -func (*ContainerState) ProtoMessage() {} +func (m *ContainerStateTerminated) Reset() { *m = ContainerStateTerminated{} } +func (*ContainerStateTerminated) ProtoMessage() {} -func (m *ContainerStateRunning) Reset() { *m = ContainerStateRunning{} } -func (m *ContainerStateRunning) String() string { return proto.CompactTextString(m) } -func (*ContainerStateRunning) ProtoMessage() {} +func (m *ContainerStateWaiting) Reset() { *m = ContainerStateWaiting{} } +func (*ContainerStateWaiting) ProtoMessage() {} -func (m *ContainerStateTerminated) Reset() { *m = ContainerStateTerminated{} } -func (m *ContainerStateTerminated) String() string { return proto.CompactTextString(m) } -func (*ContainerStateTerminated) ProtoMessage() {} +func (m *ContainerStatus) Reset() { *m = ContainerStatus{} } +func (*ContainerStatus) ProtoMessage() {} -func (m *ContainerStateWaiting) Reset() { *m = ContainerStateWaiting{} } -func (m *ContainerStateWaiting) String() string { return proto.CompactTextString(m) } -func (*ContainerStateWaiting) ProtoMessage() {} +func (m *DaemonEndpoint) Reset() { *m = DaemonEndpoint{} } +func (*DaemonEndpoint) ProtoMessage() {} -func (m *ContainerStatus) Reset() { *m = ContainerStatus{} } -func (m *ContainerStatus) String() string { return proto.CompactTextString(m) } -func (*ContainerStatus) ProtoMessage() {} +func (m *DeleteOptions) Reset() { *m = DeleteOptions{} } +func (*DeleteOptions) ProtoMessage() {} -func (m *DaemonEndpoint) Reset() { *m = DaemonEndpoint{} } -func (m *DaemonEndpoint) String() string { return proto.CompactTextString(m) } -func (*DaemonEndpoint) ProtoMessage() {} +func (m *DownwardAPIVolumeFile) Reset() { *m = DownwardAPIVolumeFile{} } +func (*DownwardAPIVolumeFile) ProtoMessage() {} -func (m *DeleteOptions) Reset() { *m = DeleteOptions{} } -func (m *DeleteOptions) String() string { return proto.CompactTextString(m) } -func (*DeleteOptions) ProtoMessage() {} +func (m *DownwardAPIVolumeSource) Reset() { *m = DownwardAPIVolumeSource{} } +func (*DownwardAPIVolumeSource) ProtoMessage() {} -func (m *DownwardAPIVolumeFile) Reset() { *m = DownwardAPIVolumeFile{} } -func (m *DownwardAPIVolumeFile) String() string { return proto.CompactTextString(m) } -func (*DownwardAPIVolumeFile) ProtoMessage() {} +func (m *EmptyDirVolumeSource) Reset() { *m = EmptyDirVolumeSource{} } +func (*EmptyDirVolumeSource) ProtoMessage() {} -func (m *DownwardAPIVolumeSource) Reset() { *m = DownwardAPIVolumeSource{} } -func (m *DownwardAPIVolumeSource) String() string { return proto.CompactTextString(m) } -func (*DownwardAPIVolumeSource) ProtoMessage() {} +func (m *EndpointAddress) Reset() { *m = EndpointAddress{} } +func (*EndpointAddress) ProtoMessage() {} -func (m *EmptyDirVolumeSource) Reset() { *m = EmptyDirVolumeSource{} } -func (m *EmptyDirVolumeSource) String() string { return proto.CompactTextString(m) } -func (*EmptyDirVolumeSource) ProtoMessage() {} +func (m *EndpointPort) Reset() { *m = EndpointPort{} } +func (*EndpointPort) ProtoMessage() {} -func (m *EndpointAddress) Reset() { *m = EndpointAddress{} } -func (m *EndpointAddress) String() string { return proto.CompactTextString(m) } -func (*EndpointAddress) ProtoMessage() {} +func (m *EndpointSubset) Reset() { *m = EndpointSubset{} } +func (*EndpointSubset) ProtoMessage() {} -func (m *EndpointPort) Reset() { *m = EndpointPort{} } -func (m *EndpointPort) String() string { return proto.CompactTextString(m) } -func (*EndpointPort) ProtoMessage() {} +func (m *Endpoints) Reset() { *m = Endpoints{} } +func (*Endpoints) ProtoMessage() {} -func (m *EndpointSubset) Reset() { *m = EndpointSubset{} } -func (m *EndpointSubset) String() string { return proto.CompactTextString(m) } -func (*EndpointSubset) ProtoMessage() {} +func (m *EndpointsList) Reset() { *m = EndpointsList{} } +func (*EndpointsList) ProtoMessage() {} -func (m *Endpoints) Reset() { *m = Endpoints{} } -func (m *Endpoints) String() string { return proto.CompactTextString(m) } -func (*Endpoints) ProtoMessage() {} +func (m *EnvVar) Reset() { *m = EnvVar{} } +func (*EnvVar) ProtoMessage() {} -func (m *EndpointsList) Reset() { *m = EndpointsList{} } -func (m *EndpointsList) String() string { return proto.CompactTextString(m) } -func (*EndpointsList) ProtoMessage() {} +func (m *EnvVarSource) Reset() { *m = EnvVarSource{} } +func (*EnvVarSource) ProtoMessage() {} -func (m *EnvVar) Reset() { *m = EnvVar{} } -func (m *EnvVar) String() string { return proto.CompactTextString(m) } -func (*EnvVar) ProtoMessage() {} +func (m *Event) Reset() { *m = Event{} } +func (*Event) ProtoMessage() {} -func (m *EnvVarSource) Reset() { *m = EnvVarSource{} } -func (m *EnvVarSource) String() string { return proto.CompactTextString(m) } -func (*EnvVarSource) ProtoMessage() {} +func (m *EventList) Reset() { *m = EventList{} } +func (*EventList) ProtoMessage() {} -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} +func (m *EventSource) Reset() { *m = EventSource{} } +func (*EventSource) ProtoMessage() {} -func (m *EventList) Reset() { *m = EventList{} } -func (m *EventList) String() string { return proto.CompactTextString(m) } -func (*EventList) ProtoMessage() {} +func (m *ExecAction) Reset() { *m = ExecAction{} } +func (*ExecAction) ProtoMessage() {} -func (m *EventSource) Reset() { *m = EventSource{} } -func (m *EventSource) String() string { return proto.CompactTextString(m) } -func (*EventSource) ProtoMessage() {} +func (m *ExportOptions) Reset() { *m = ExportOptions{} } +func (*ExportOptions) ProtoMessage() {} -func (m *ExecAction) Reset() { *m = ExecAction{} } -func (m *ExecAction) String() string { return proto.CompactTextString(m) } -func (*ExecAction) ProtoMessage() {} +func (m *FCVolumeSource) Reset() { *m = FCVolumeSource{} } +func (*FCVolumeSource) ProtoMessage() {} -func (m *ExportOptions) Reset() { *m = ExportOptions{} } -func (m *ExportOptions) String() string { return proto.CompactTextString(m) } -func (*ExportOptions) ProtoMessage() {} +func (m *FlexVolumeSource) Reset() { *m = FlexVolumeSource{} } +func (*FlexVolumeSource) ProtoMessage() {} -func (m *FCVolumeSource) Reset() { *m = FCVolumeSource{} } -func (m *FCVolumeSource) String() string { return proto.CompactTextString(m) } -func (*FCVolumeSource) ProtoMessage() {} +func (m *FlockerVolumeSource) Reset() { *m = FlockerVolumeSource{} } +func (*FlockerVolumeSource) ProtoMessage() {} -func (m *FlexVolumeSource) Reset() { *m = FlexVolumeSource{} } -func (m *FlexVolumeSource) String() string { return proto.CompactTextString(m) } -func (*FlexVolumeSource) ProtoMessage() {} +func (m *GCEPersistentDiskVolumeSource) Reset() { *m = GCEPersistentDiskVolumeSource{} } +func (*GCEPersistentDiskVolumeSource) ProtoMessage() {} -func (m *FlockerVolumeSource) Reset() { *m = FlockerVolumeSource{} } -func (m *FlockerVolumeSource) String() string { return proto.CompactTextString(m) } -func (*FlockerVolumeSource) ProtoMessage() {} +func (m *GitRepoVolumeSource) Reset() { *m = GitRepoVolumeSource{} } +func (*GitRepoVolumeSource) ProtoMessage() {} -func (m *GCEPersistentDiskVolumeSource) Reset() { *m = GCEPersistentDiskVolumeSource{} } -func (m *GCEPersistentDiskVolumeSource) String() string { return proto.CompactTextString(m) } -func (*GCEPersistentDiskVolumeSource) ProtoMessage() {} +func (m *GlusterfsVolumeSource) Reset() { *m = GlusterfsVolumeSource{} } +func (*GlusterfsVolumeSource) ProtoMessage() {} -func (m *GitRepoVolumeSource) Reset() { *m = GitRepoVolumeSource{} } -func (m *GitRepoVolumeSource) String() string { return proto.CompactTextString(m) } -func (*GitRepoVolumeSource) ProtoMessage() {} +func (m *HTTPGetAction) Reset() { *m = HTTPGetAction{} } +func (*HTTPGetAction) ProtoMessage() {} -func (m *GlusterfsVolumeSource) Reset() { *m = GlusterfsVolumeSource{} } -func (m *GlusterfsVolumeSource) String() string { return proto.CompactTextString(m) } -func (*GlusterfsVolumeSource) ProtoMessage() {} +func (m *HTTPHeader) Reset() { *m = HTTPHeader{} } +func (*HTTPHeader) ProtoMessage() {} -func (m *HTTPGetAction) Reset() { *m = HTTPGetAction{} } -func (m *HTTPGetAction) String() string { return proto.CompactTextString(m) } -func (*HTTPGetAction) ProtoMessage() {} +func (m *Handler) Reset() { *m = Handler{} } +func (*Handler) ProtoMessage() {} -func (m *HTTPHeader) Reset() { *m = HTTPHeader{} } -func (m *HTTPHeader) String() string { return proto.CompactTextString(m) } -func (*HTTPHeader) ProtoMessage() {} +func (m *HostPathVolumeSource) Reset() { *m = HostPathVolumeSource{} } +func (*HostPathVolumeSource) ProtoMessage() {} -func (m *Handler) Reset() { *m = Handler{} } -func (m *Handler) String() string { return proto.CompactTextString(m) } -func (*Handler) ProtoMessage() {} +func (m *ISCSIVolumeSource) Reset() { *m = ISCSIVolumeSource{} } +func (*ISCSIVolumeSource) ProtoMessage() {} -func (m *HostPathVolumeSource) Reset() { *m = HostPathVolumeSource{} } -func (m *HostPathVolumeSource) String() string { return proto.CompactTextString(m) } -func (*HostPathVolumeSource) ProtoMessage() {} +func (m *KeyToPath) Reset() { *m = KeyToPath{} } +func (*KeyToPath) ProtoMessage() {} -func (m *ISCSIVolumeSource) Reset() { *m = ISCSIVolumeSource{} } -func (m *ISCSIVolumeSource) String() string { return proto.CompactTextString(m) } -func (*ISCSIVolumeSource) ProtoMessage() {} +func (m *Lifecycle) Reset() { *m = Lifecycle{} } +func (*Lifecycle) ProtoMessage() {} -func (m *KeyToPath) Reset() { *m = KeyToPath{} } -func (m *KeyToPath) String() string { return proto.CompactTextString(m) } -func (*KeyToPath) ProtoMessage() {} +func (m *LimitRange) Reset() { *m = LimitRange{} } +func (*LimitRange) ProtoMessage() {} -func (m *Lifecycle) Reset() { *m = Lifecycle{} } -func (m *Lifecycle) String() string { return proto.CompactTextString(m) } -func (*Lifecycle) ProtoMessage() {} +func (m *LimitRangeItem) Reset() { *m = LimitRangeItem{} } +func (*LimitRangeItem) ProtoMessage() {} -func (m *LimitRange) Reset() { *m = LimitRange{} } -func (m *LimitRange) String() string { return proto.CompactTextString(m) } -func (*LimitRange) ProtoMessage() {} +func (m *LimitRangeList) Reset() { *m = LimitRangeList{} } +func (*LimitRangeList) ProtoMessage() {} -func (m *LimitRangeItem) Reset() { *m = LimitRangeItem{} } -func (m *LimitRangeItem) String() string { return proto.CompactTextString(m) } -func (*LimitRangeItem) ProtoMessage() {} +func (m *LimitRangeSpec) Reset() { *m = LimitRangeSpec{} } +func (*LimitRangeSpec) ProtoMessage() {} -func (m *LimitRangeList) Reset() { *m = LimitRangeList{} } -func (m *LimitRangeList) String() string { return proto.CompactTextString(m) } -func (*LimitRangeList) ProtoMessage() {} +func (m *List) Reset() { *m = List{} } +func (*List) ProtoMessage() {} -func (m *LimitRangeSpec) Reset() { *m = LimitRangeSpec{} } -func (m *LimitRangeSpec) String() string { return proto.CompactTextString(m) } -func (*LimitRangeSpec) ProtoMessage() {} +func (m *ListOptions) Reset() { *m = ListOptions{} } +func (*ListOptions) ProtoMessage() {} -func (m *List) Reset() { *m = List{} } -func (m *List) String() string { return proto.CompactTextString(m) } -func (*List) ProtoMessage() {} +func (m *LoadBalancerIngress) Reset() { *m = LoadBalancerIngress{} } +func (*LoadBalancerIngress) ProtoMessage() {} -func (m *ListOptions) Reset() { *m = ListOptions{} } -func (m *ListOptions) String() string { return proto.CompactTextString(m) } -func (*ListOptions) ProtoMessage() {} +func (m *LoadBalancerStatus) Reset() { *m = LoadBalancerStatus{} } +func (*LoadBalancerStatus) ProtoMessage() {} -func (m *LoadBalancerIngress) Reset() { *m = LoadBalancerIngress{} } -func (m *LoadBalancerIngress) String() string { return proto.CompactTextString(m) } -func (*LoadBalancerIngress) ProtoMessage() {} +func (m *LocalObjectReference) Reset() { *m = LocalObjectReference{} } +func (*LocalObjectReference) ProtoMessage() {} -func (m *LoadBalancerStatus) Reset() { *m = LoadBalancerStatus{} } -func (m *LoadBalancerStatus) String() string { return proto.CompactTextString(m) } -func (*LoadBalancerStatus) ProtoMessage() {} +func (m *NFSVolumeSource) Reset() { *m = NFSVolumeSource{} } +func (*NFSVolumeSource) ProtoMessage() {} -func (m *LocalObjectReference) Reset() { *m = LocalObjectReference{} } -func (m *LocalObjectReference) String() string { return proto.CompactTextString(m) } -func (*LocalObjectReference) ProtoMessage() {} +func (m *Namespace) Reset() { *m = Namespace{} } +func (*Namespace) ProtoMessage() {} -func (m *NFSVolumeSource) Reset() { *m = NFSVolumeSource{} } -func (m *NFSVolumeSource) String() string { return proto.CompactTextString(m) } -func (*NFSVolumeSource) ProtoMessage() {} +func (m *NamespaceList) Reset() { *m = NamespaceList{} } +func (*NamespaceList) ProtoMessage() {} -func (m *Namespace) Reset() { *m = Namespace{} } -func (m *Namespace) String() string { return proto.CompactTextString(m) } -func (*Namespace) ProtoMessage() {} +func (m *NamespaceSpec) Reset() { *m = NamespaceSpec{} } +func (*NamespaceSpec) ProtoMessage() {} -func (m *NamespaceList) Reset() { *m = NamespaceList{} } -func (m *NamespaceList) String() string { return proto.CompactTextString(m) } -func (*NamespaceList) ProtoMessage() {} +func (m *NamespaceStatus) Reset() { *m = NamespaceStatus{} } +func (*NamespaceStatus) ProtoMessage() {} -func (m *NamespaceSpec) Reset() { *m = NamespaceSpec{} } -func (m *NamespaceSpec) String() string { return proto.CompactTextString(m) } -func (*NamespaceSpec) ProtoMessage() {} +func (m *Node) Reset() { *m = Node{} } +func (*Node) ProtoMessage() {} -func (m *NamespaceStatus) Reset() { *m = NamespaceStatus{} } -func (m *NamespaceStatus) String() string { return proto.CompactTextString(m) } -func (*NamespaceStatus) ProtoMessage() {} +func (m *NodeAddress) Reset() { *m = NodeAddress{} } +func (*NodeAddress) ProtoMessage() {} -func (m *Node) Reset() { *m = Node{} } -func (m *Node) String() string { return proto.CompactTextString(m) } -func (*Node) ProtoMessage() {} +func (m *NodeAffinity) Reset() { *m = NodeAffinity{} } +func (*NodeAffinity) ProtoMessage() {} -func (m *NodeAddress) Reset() { *m = NodeAddress{} } -func (m *NodeAddress) String() string { return proto.CompactTextString(m) } -func (*NodeAddress) ProtoMessage() {} +func (m *NodeCondition) Reset() { *m = NodeCondition{} } +func (*NodeCondition) ProtoMessage() {} -func (m *NodeAffinity) Reset() { *m = NodeAffinity{} } -func (m *NodeAffinity) String() string { return proto.CompactTextString(m) } -func (*NodeAffinity) ProtoMessage() {} +func (m *NodeDaemonEndpoints) Reset() { *m = NodeDaemonEndpoints{} } +func (*NodeDaemonEndpoints) ProtoMessage() {} -func (m *NodeCondition) Reset() { *m = NodeCondition{} } -func (m *NodeCondition) String() string { return proto.CompactTextString(m) } -func (*NodeCondition) ProtoMessage() {} +func (m *NodeList) Reset() { *m = NodeList{} } +func (*NodeList) ProtoMessage() {} -func (m *NodeDaemonEndpoints) Reset() { *m = NodeDaemonEndpoints{} } -func (m *NodeDaemonEndpoints) String() string { return proto.CompactTextString(m) } -func (*NodeDaemonEndpoints) ProtoMessage() {} +func (m *NodeProxyOptions) Reset() { *m = NodeProxyOptions{} } +func (*NodeProxyOptions) ProtoMessage() {} -func (m *NodeList) Reset() { *m = NodeList{} } -func (m *NodeList) String() string { return proto.CompactTextString(m) } -func (*NodeList) ProtoMessage() {} +func (m *NodeSelector) Reset() { *m = NodeSelector{} } +func (*NodeSelector) ProtoMessage() {} -func (m *NodeProxyOptions) Reset() { *m = NodeProxyOptions{} } -func (m *NodeProxyOptions) String() string { return proto.CompactTextString(m) } -func (*NodeProxyOptions) ProtoMessage() {} +func (m *NodeSelectorRequirement) Reset() { *m = NodeSelectorRequirement{} } +func (*NodeSelectorRequirement) ProtoMessage() {} -func (m *NodeSelector) Reset() { *m = NodeSelector{} } -func (m *NodeSelector) String() string { return proto.CompactTextString(m) } -func (*NodeSelector) ProtoMessage() {} +func (m *NodeSelectorTerm) Reset() { *m = NodeSelectorTerm{} } +func (*NodeSelectorTerm) ProtoMessage() {} -func (m *NodeSelectorRequirement) Reset() { *m = NodeSelectorRequirement{} } -func (m *NodeSelectorRequirement) String() string { return proto.CompactTextString(m) } -func (*NodeSelectorRequirement) ProtoMessage() {} +func (m *NodeSpec) Reset() { *m = NodeSpec{} } +func (*NodeSpec) ProtoMessage() {} -func (m *NodeSelectorTerm) Reset() { *m = NodeSelectorTerm{} } -func (m *NodeSelectorTerm) String() string { return proto.CompactTextString(m) } -func (*NodeSelectorTerm) ProtoMessage() {} +func (m *NodeStatus) Reset() { *m = NodeStatus{} } +func (*NodeStatus) ProtoMessage() {} -func (m *NodeSpec) Reset() { *m = NodeSpec{} } -func (m *NodeSpec) String() string { return proto.CompactTextString(m) } -func (*NodeSpec) ProtoMessage() {} +func (m *NodeSystemInfo) Reset() { *m = NodeSystemInfo{} } +func (*NodeSystemInfo) ProtoMessage() {} -func (m *NodeStatus) Reset() { *m = NodeStatus{} } -func (m *NodeStatus) String() string { return proto.CompactTextString(m) } -func (*NodeStatus) ProtoMessage() {} +func (m *ObjectFieldSelector) Reset() { *m = ObjectFieldSelector{} } +func (*ObjectFieldSelector) ProtoMessage() {} -func (m *NodeSystemInfo) Reset() { *m = NodeSystemInfo{} } -func (m *NodeSystemInfo) String() string { return proto.CompactTextString(m) } -func (*NodeSystemInfo) ProtoMessage() {} +func (m *ObjectMeta) Reset() { *m = ObjectMeta{} } +func (*ObjectMeta) ProtoMessage() {} -func (m *ObjectFieldSelector) Reset() { *m = ObjectFieldSelector{} } -func (m *ObjectFieldSelector) String() string { return proto.CompactTextString(m) } -func (*ObjectFieldSelector) ProtoMessage() {} +func (m *ObjectReference) Reset() { *m = ObjectReference{} } +func (*ObjectReference) ProtoMessage() {} -func (m *ObjectMeta) Reset() { *m = ObjectMeta{} } -func (m *ObjectMeta) String() string { return proto.CompactTextString(m) } -func (*ObjectMeta) ProtoMessage() {} +func (m *OwnerReference) Reset() { *m = OwnerReference{} } +func (*OwnerReference) ProtoMessage() {} -func (m *ObjectReference) Reset() { *m = ObjectReference{} } -func (m *ObjectReference) String() string { return proto.CompactTextString(m) } -func (*ObjectReference) ProtoMessage() {} +func (m *PersistentVolume) Reset() { *m = PersistentVolume{} } +func (*PersistentVolume) ProtoMessage() {} -func (m *OwnerReference) Reset() { *m = OwnerReference{} } -func (m *OwnerReference) String() string { return proto.CompactTextString(m) } -func (*OwnerReference) ProtoMessage() {} +func (m *PersistentVolumeClaim) Reset() { *m = PersistentVolumeClaim{} } +func (*PersistentVolumeClaim) ProtoMessage() {} -func (m *PersistentVolume) Reset() { *m = PersistentVolume{} } -func (m *PersistentVolume) String() string { return proto.CompactTextString(m) } -func (*PersistentVolume) ProtoMessage() {} +func (m *PersistentVolumeClaimList) Reset() { *m = PersistentVolumeClaimList{} } +func (*PersistentVolumeClaimList) ProtoMessage() {} -func (m *PersistentVolumeClaim) Reset() { *m = PersistentVolumeClaim{} } -func (m *PersistentVolumeClaim) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeClaim) ProtoMessage() {} +func (m *PersistentVolumeClaimSpec) Reset() { *m = PersistentVolumeClaimSpec{} } +func (*PersistentVolumeClaimSpec) ProtoMessage() {} -func (m *PersistentVolumeClaimList) Reset() { *m = PersistentVolumeClaimList{} } -func (m *PersistentVolumeClaimList) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeClaimList) ProtoMessage() {} +func (m *PersistentVolumeClaimStatus) Reset() { *m = PersistentVolumeClaimStatus{} } +func (*PersistentVolumeClaimStatus) ProtoMessage() {} -func (m *PersistentVolumeClaimSpec) Reset() { *m = PersistentVolumeClaimSpec{} } -func (m *PersistentVolumeClaimSpec) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeClaimSpec) ProtoMessage() {} +func (m *PersistentVolumeClaimVolumeSource) Reset() { *m = PersistentVolumeClaimVolumeSource{} } +func (*PersistentVolumeClaimVolumeSource) ProtoMessage() {} -func (m *PersistentVolumeClaimStatus) Reset() { *m = PersistentVolumeClaimStatus{} } -func (m *PersistentVolumeClaimStatus) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeClaimStatus) ProtoMessage() {} +func (m *PersistentVolumeList) Reset() { *m = PersistentVolumeList{} } +func (*PersistentVolumeList) ProtoMessage() {} -func (m *PersistentVolumeClaimVolumeSource) Reset() { *m = PersistentVolumeClaimVolumeSource{} } -func (m *PersistentVolumeClaimVolumeSource) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeClaimVolumeSource) ProtoMessage() {} +func (m *PersistentVolumeSource) Reset() { *m = PersistentVolumeSource{} } +func (*PersistentVolumeSource) ProtoMessage() {} -func (m *PersistentVolumeList) Reset() { *m = PersistentVolumeList{} } -func (m *PersistentVolumeList) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeList) ProtoMessage() {} +func (m *PersistentVolumeSpec) Reset() { *m = PersistentVolumeSpec{} } +func (*PersistentVolumeSpec) ProtoMessage() {} -func (m *PersistentVolumeSource) Reset() { *m = PersistentVolumeSource{} } -func (m *PersistentVolumeSource) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeSource) ProtoMessage() {} +func (m *PersistentVolumeStatus) Reset() { *m = PersistentVolumeStatus{} } +func (*PersistentVolumeStatus) ProtoMessage() {} -func (m *PersistentVolumeSpec) Reset() { *m = PersistentVolumeSpec{} } -func (m *PersistentVolumeSpec) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeSpec) ProtoMessage() {} +func (m *Pod) Reset() { *m = Pod{} } +func (*Pod) ProtoMessage() {} -func (m *PersistentVolumeStatus) Reset() { *m = PersistentVolumeStatus{} } -func (m *PersistentVolumeStatus) String() string { return proto.CompactTextString(m) } -func (*PersistentVolumeStatus) ProtoMessage() {} +func (m *PodAffinity) Reset() { *m = PodAffinity{} } +func (*PodAffinity) ProtoMessage() {} -func (m *Pod) Reset() { *m = Pod{} } -func (m *Pod) String() string { return proto.CompactTextString(m) } -func (*Pod) ProtoMessage() {} +func (m *PodAffinityTerm) Reset() { *m = PodAffinityTerm{} } +func (*PodAffinityTerm) ProtoMessage() {} -func (m *PodAffinity) Reset() { *m = PodAffinity{} } -func (m *PodAffinity) String() string { return proto.CompactTextString(m) } -func (*PodAffinity) ProtoMessage() {} +func (m *PodAntiAffinity) Reset() { *m = PodAntiAffinity{} } +func (*PodAntiAffinity) ProtoMessage() {} -func (m *PodAffinityTerm) Reset() { *m = PodAffinityTerm{} } -func (m *PodAffinityTerm) String() string { return proto.CompactTextString(m) } -func (*PodAffinityTerm) ProtoMessage() {} +func (m *PodAttachOptions) Reset() { *m = PodAttachOptions{} } +func (*PodAttachOptions) ProtoMessage() {} -func (m *PodAntiAffinity) Reset() { *m = PodAntiAffinity{} } -func (m *PodAntiAffinity) String() string { return proto.CompactTextString(m) } -func (*PodAntiAffinity) ProtoMessage() {} +func (m *PodCondition) Reset() { *m = PodCondition{} } +func (*PodCondition) ProtoMessage() {} -func (m *PodAttachOptions) Reset() { *m = PodAttachOptions{} } -func (m *PodAttachOptions) String() string { return proto.CompactTextString(m) } -func (*PodAttachOptions) ProtoMessage() {} +func (m *PodExecOptions) Reset() { *m = PodExecOptions{} } +func (*PodExecOptions) ProtoMessage() {} -func (m *PodCondition) Reset() { *m = PodCondition{} } -func (m *PodCondition) String() string { return proto.CompactTextString(m) } -func (*PodCondition) ProtoMessage() {} +func (m *PodList) Reset() { *m = PodList{} } +func (*PodList) ProtoMessage() {} -func (m *PodExecOptions) Reset() { *m = PodExecOptions{} } -func (m *PodExecOptions) String() string { return proto.CompactTextString(m) } -func (*PodExecOptions) ProtoMessage() {} +func (m *PodLogOptions) Reset() { *m = PodLogOptions{} } +func (*PodLogOptions) ProtoMessage() {} -func (m *PodList) Reset() { *m = PodList{} } -func (m *PodList) String() string { return proto.CompactTextString(m) } -func (*PodList) ProtoMessage() {} +func (m *PodProxyOptions) Reset() { *m = PodProxyOptions{} } +func (*PodProxyOptions) ProtoMessage() {} -func (m *PodLogOptions) Reset() { *m = PodLogOptions{} } -func (m *PodLogOptions) String() string { return proto.CompactTextString(m) } -func (*PodLogOptions) ProtoMessage() {} +func (m *PodSecurityContext) Reset() { *m = PodSecurityContext{} } +func (*PodSecurityContext) ProtoMessage() {} -func (m *PodProxyOptions) Reset() { *m = PodProxyOptions{} } -func (m *PodProxyOptions) String() string { return proto.CompactTextString(m) } -func (*PodProxyOptions) ProtoMessage() {} +func (m *PodSignature) Reset() { *m = PodSignature{} } +func (*PodSignature) ProtoMessage() {} -func (m *PodSecurityContext) Reset() { *m = PodSecurityContext{} } -func (m *PodSecurityContext) String() string { return proto.CompactTextString(m) } -func (*PodSecurityContext) ProtoMessage() {} +func (m *PodSpec) Reset() { *m = PodSpec{} } +func (*PodSpec) ProtoMessage() {} -func (m *PodSpec) Reset() { *m = PodSpec{} } -func (m *PodSpec) String() string { return proto.CompactTextString(m) } -func (*PodSpec) ProtoMessage() {} +func (m *PodStatus) Reset() { *m = PodStatus{} } +func (*PodStatus) ProtoMessage() {} -func (m *PodStatus) Reset() { *m = PodStatus{} } -func (m *PodStatus) String() string { return proto.CompactTextString(m) } -func (*PodStatus) ProtoMessage() {} +func (m *PodStatusResult) Reset() { *m = PodStatusResult{} } +func (*PodStatusResult) ProtoMessage() {} -func (m *PodStatusResult) Reset() { *m = PodStatusResult{} } -func (m *PodStatusResult) String() string { return proto.CompactTextString(m) } -func (*PodStatusResult) ProtoMessage() {} +func (m *PodTemplate) Reset() { *m = PodTemplate{} } +func (*PodTemplate) ProtoMessage() {} -func (m *PodTemplate) Reset() { *m = PodTemplate{} } -func (m *PodTemplate) String() string { return proto.CompactTextString(m) } -func (*PodTemplate) ProtoMessage() {} +func (m *PodTemplateList) Reset() { *m = PodTemplateList{} } +func (*PodTemplateList) ProtoMessage() {} -func (m *PodTemplateList) Reset() { *m = PodTemplateList{} } -func (m *PodTemplateList) String() string { return proto.CompactTextString(m) } -func (*PodTemplateList) ProtoMessage() {} +func (m *PodTemplateSpec) Reset() { *m = PodTemplateSpec{} } +func (*PodTemplateSpec) ProtoMessage() {} -func (m *PodTemplateSpec) Reset() { *m = PodTemplateSpec{} } -func (m *PodTemplateSpec) String() string { return proto.CompactTextString(m) } -func (*PodTemplateSpec) ProtoMessage() {} +func (m *Preconditions) Reset() { *m = Preconditions{} } +func (*Preconditions) ProtoMessage() {} -func (m *Preconditions) Reset() { *m = Preconditions{} } -func (m *Preconditions) String() string { return proto.CompactTextString(m) } -func (*Preconditions) ProtoMessage() {} +func (m *PreferAvoidPodsEntry) Reset() { *m = PreferAvoidPodsEntry{} } +func (*PreferAvoidPodsEntry) ProtoMessage() {} -func (m *PreferredSchedulingTerm) Reset() { *m = PreferredSchedulingTerm{} } -func (m *PreferredSchedulingTerm) String() string { return proto.CompactTextString(m) } -func (*PreferredSchedulingTerm) ProtoMessage() {} +func (m *PreferredSchedulingTerm) Reset() { *m = PreferredSchedulingTerm{} } +func (*PreferredSchedulingTerm) ProtoMessage() {} -func (m *Probe) Reset() { *m = Probe{} } -func (m *Probe) String() string { return proto.CompactTextString(m) } -func (*Probe) ProtoMessage() {} +func (m *Probe) Reset() { *m = Probe{} } +func (*Probe) ProtoMessage() {} -func (m *RBDVolumeSource) Reset() { *m = RBDVolumeSource{} } -func (m *RBDVolumeSource) String() string { return proto.CompactTextString(m) } -func (*RBDVolumeSource) ProtoMessage() {} +func (m *RBDVolumeSource) Reset() { *m = RBDVolumeSource{} } +func (*RBDVolumeSource) ProtoMessage() {} -func (m *RangeAllocation) Reset() { *m = RangeAllocation{} } -func (m *RangeAllocation) String() string { return proto.CompactTextString(m) } -func (*RangeAllocation) ProtoMessage() {} +func (m *RangeAllocation) Reset() { *m = RangeAllocation{} } +func (*RangeAllocation) ProtoMessage() {} -func (m *ReplicationController) Reset() { *m = ReplicationController{} } -func (m *ReplicationController) String() string { return proto.CompactTextString(m) } -func (*ReplicationController) ProtoMessage() {} +func (m *ReplicationController) Reset() { *m = ReplicationController{} } +func (*ReplicationController) ProtoMessage() {} -func (m *ReplicationControllerList) Reset() { *m = ReplicationControllerList{} } -func (m *ReplicationControllerList) String() string { return proto.CompactTextString(m) } -func (*ReplicationControllerList) ProtoMessage() {} +func (m *ReplicationControllerList) Reset() { *m = ReplicationControllerList{} } +func (*ReplicationControllerList) ProtoMessage() {} -func (m *ReplicationControllerSpec) Reset() { *m = ReplicationControllerSpec{} } -func (m *ReplicationControllerSpec) String() string { return proto.CompactTextString(m) } -func (*ReplicationControllerSpec) ProtoMessage() {} +func (m *ReplicationControllerSpec) Reset() { *m = ReplicationControllerSpec{} } +func (*ReplicationControllerSpec) ProtoMessage() {} -func (m *ReplicationControllerStatus) Reset() { *m = ReplicationControllerStatus{} } -func (m *ReplicationControllerStatus) String() string { return proto.CompactTextString(m) } -func (*ReplicationControllerStatus) ProtoMessage() {} +func (m *ReplicationControllerStatus) Reset() { *m = ReplicationControllerStatus{} } +func (*ReplicationControllerStatus) ProtoMessage() {} -func (m *ResourceFieldSelector) Reset() { *m = ResourceFieldSelector{} } -func (m *ResourceFieldSelector) String() string { return proto.CompactTextString(m) } -func (*ResourceFieldSelector) ProtoMessage() {} +func (m *ResourceFieldSelector) Reset() { *m = ResourceFieldSelector{} } +func (*ResourceFieldSelector) ProtoMessage() {} -func (m *ResourceQuota) Reset() { *m = ResourceQuota{} } -func (m *ResourceQuota) String() string { return proto.CompactTextString(m) } -func (*ResourceQuota) ProtoMessage() {} +func (m *ResourceQuota) Reset() { *m = ResourceQuota{} } +func (*ResourceQuota) ProtoMessage() {} -func (m *ResourceQuotaList) Reset() { *m = ResourceQuotaList{} } -func (m *ResourceQuotaList) String() string { return proto.CompactTextString(m) } -func (*ResourceQuotaList) ProtoMessage() {} +func (m *ResourceQuotaList) Reset() { *m = ResourceQuotaList{} } +func (*ResourceQuotaList) ProtoMessage() {} -func (m *ResourceQuotaSpec) Reset() { *m = ResourceQuotaSpec{} } -func (m *ResourceQuotaSpec) String() string { return proto.CompactTextString(m) } -func (*ResourceQuotaSpec) ProtoMessage() {} +func (m *ResourceQuotaSpec) Reset() { *m = ResourceQuotaSpec{} } +func (*ResourceQuotaSpec) ProtoMessage() {} -func (m *ResourceQuotaStatus) Reset() { *m = ResourceQuotaStatus{} } -func (m *ResourceQuotaStatus) String() string { return proto.CompactTextString(m) } -func (*ResourceQuotaStatus) ProtoMessage() {} +func (m *ResourceQuotaStatus) Reset() { *m = ResourceQuotaStatus{} } +func (*ResourceQuotaStatus) ProtoMessage() {} -func (m *ResourceRequirements) Reset() { *m = ResourceRequirements{} } -func (m *ResourceRequirements) String() string { return proto.CompactTextString(m) } -func (*ResourceRequirements) ProtoMessage() {} +func (m *ResourceRequirements) Reset() { *m = ResourceRequirements{} } +func (*ResourceRequirements) ProtoMessage() {} -func (m *SELinuxOptions) Reset() { *m = SELinuxOptions{} } -func (m *SELinuxOptions) String() string { return proto.CompactTextString(m) } -func (*SELinuxOptions) ProtoMessage() {} +func (m *SELinuxOptions) Reset() { *m = SELinuxOptions{} } +func (*SELinuxOptions) ProtoMessage() {} -func (m *Secret) Reset() { *m = Secret{} } -func (m *Secret) String() string { return proto.CompactTextString(m) } -func (*Secret) ProtoMessage() {} +func (m *Secret) Reset() { *m = Secret{} } +func (*Secret) ProtoMessage() {} -func (m *SecretKeySelector) Reset() { *m = SecretKeySelector{} } -func (m *SecretKeySelector) String() string { return proto.CompactTextString(m) } -func (*SecretKeySelector) ProtoMessage() {} +func (m *SecretKeySelector) Reset() { *m = SecretKeySelector{} } +func (*SecretKeySelector) ProtoMessage() {} -func (m *SecretList) Reset() { *m = SecretList{} } -func (m *SecretList) String() string { return proto.CompactTextString(m) } -func (*SecretList) ProtoMessage() {} +func (m *SecretList) Reset() { *m = SecretList{} } +func (*SecretList) ProtoMessage() {} -func (m *SecretVolumeSource) Reset() { *m = SecretVolumeSource{} } -func (m *SecretVolumeSource) String() string { return proto.CompactTextString(m) } -func (*SecretVolumeSource) ProtoMessage() {} +func (m *SecretVolumeSource) Reset() { *m = SecretVolumeSource{} } +func (*SecretVolumeSource) ProtoMessage() {} -func (m *SecurityContext) Reset() { *m = SecurityContext{} } -func (m *SecurityContext) String() string { return proto.CompactTextString(m) } -func (*SecurityContext) ProtoMessage() {} +func (m *SecurityContext) Reset() { *m = SecurityContext{} } +func (*SecurityContext) ProtoMessage() {} -func (m *SerializedReference) Reset() { *m = SerializedReference{} } -func (m *SerializedReference) String() string { return proto.CompactTextString(m) } -func (*SerializedReference) ProtoMessage() {} +func (m *SerializedReference) Reset() { *m = SerializedReference{} } +func (*SerializedReference) ProtoMessage() {} -func (m *Service) Reset() { *m = Service{} } -func (m *Service) String() string { return proto.CompactTextString(m) } -func (*Service) ProtoMessage() {} +func (m *Service) Reset() { *m = Service{} } +func (*Service) ProtoMessage() {} -func (m *ServiceAccount) Reset() { *m = ServiceAccount{} } -func (m *ServiceAccount) String() string { return proto.CompactTextString(m) } -func (*ServiceAccount) ProtoMessage() {} +func (m *ServiceAccount) Reset() { *m = ServiceAccount{} } +func (*ServiceAccount) ProtoMessage() {} -func (m *ServiceAccountList) Reset() { *m = ServiceAccountList{} } -func (m *ServiceAccountList) String() string { return proto.CompactTextString(m) } -func (*ServiceAccountList) ProtoMessage() {} +func (m *ServiceAccountList) Reset() { *m = ServiceAccountList{} } +func (*ServiceAccountList) ProtoMessage() {} -func (m *ServiceList) Reset() { *m = ServiceList{} } -func (m *ServiceList) String() string { return proto.CompactTextString(m) } -func (*ServiceList) ProtoMessage() {} +func (m *ServiceList) Reset() { *m = ServiceList{} } +func (*ServiceList) ProtoMessage() {} -func (m *ServicePort) Reset() { *m = ServicePort{} } -func (m *ServicePort) String() string { return proto.CompactTextString(m) } -func (*ServicePort) ProtoMessage() {} +func (m *ServicePort) Reset() { *m = ServicePort{} } +func (*ServicePort) ProtoMessage() {} -func (m *ServiceProxyOptions) Reset() { *m = ServiceProxyOptions{} } -func (m *ServiceProxyOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceProxyOptions) ProtoMessage() {} +func (m *ServiceProxyOptions) Reset() { *m = ServiceProxyOptions{} } +func (*ServiceProxyOptions) ProtoMessage() {} -func (m *ServiceSpec) Reset() { *m = ServiceSpec{} } -func (m *ServiceSpec) String() string { return proto.CompactTextString(m) } -func (*ServiceSpec) ProtoMessage() {} +func (m *ServiceSpec) Reset() { *m = ServiceSpec{} } +func (*ServiceSpec) ProtoMessage() {} -func (m *ServiceStatus) Reset() { *m = ServiceStatus{} } -func (m *ServiceStatus) String() string { return proto.CompactTextString(m) } -func (*ServiceStatus) ProtoMessage() {} +func (m *ServiceStatus) Reset() { *m = ServiceStatus{} } +func (*ServiceStatus) ProtoMessage() {} -func (m *TCPSocketAction) Reset() { *m = TCPSocketAction{} } -func (m *TCPSocketAction) String() string { return proto.CompactTextString(m) } -func (*TCPSocketAction) ProtoMessage() {} +func (m *TCPSocketAction) Reset() { *m = TCPSocketAction{} } +func (*TCPSocketAction) ProtoMessage() {} -func (m *Taint) Reset() { *m = Taint{} } -func (m *Taint) String() string { return proto.CompactTextString(m) } -func (*Taint) ProtoMessage() {} +func (m *Taint) Reset() { *m = Taint{} } +func (*Taint) ProtoMessage() {} -func (m *Toleration) Reset() { *m = Toleration{} } -func (m *Toleration) String() string { return proto.CompactTextString(m) } -func (*Toleration) ProtoMessage() {} +func (m *Toleration) Reset() { *m = Toleration{} } +func (*Toleration) ProtoMessage() {} -func (m *Volume) Reset() { *m = Volume{} } -func (m *Volume) String() string { return proto.CompactTextString(m) } -func (*Volume) ProtoMessage() {} +func (m *Volume) Reset() { *m = Volume{} } +func (*Volume) ProtoMessage() {} -func (m *VolumeMount) Reset() { *m = VolumeMount{} } -func (m *VolumeMount) String() string { return proto.CompactTextString(m) } -func (*VolumeMount) ProtoMessage() {} +func (m *VolumeMount) Reset() { *m = VolumeMount{} } +func (*VolumeMount) ProtoMessage() {} -func (m *VolumeSource) Reset() { *m = VolumeSource{} } -func (m *VolumeSource) String() string { return proto.CompactTextString(m) } -func (*VolumeSource) ProtoMessage() {} +func (m *VolumeSource) Reset() { *m = VolumeSource{} } +func (*VolumeSource) ProtoMessage() {} -func (m *VsphereVirtualDiskVolumeSource) Reset() { *m = VsphereVirtualDiskVolumeSource{} } -func (m *VsphereVirtualDiskVolumeSource) String() string { return proto.CompactTextString(m) } -func (*VsphereVirtualDiskVolumeSource) ProtoMessage() {} +func (m *VsphereVirtualDiskVolumeSource) Reset() { *m = VsphereVirtualDiskVolumeSource{} } +func (*VsphereVirtualDiskVolumeSource) ProtoMessage() {} -func (m *WeightedPodAffinityTerm) Reset() { *m = WeightedPodAffinityTerm{} } -func (m *WeightedPodAffinityTerm) String() string { return proto.CompactTextString(m) } -func (*WeightedPodAffinityTerm) ProtoMessage() {} +func (m *WeightedPodAffinityTerm) Reset() { *m = WeightedPodAffinityTerm{} } +func (*WeightedPodAffinityTerm) ProtoMessage() {} func init() { proto.RegisterType((*AWSElasticBlockStoreVolumeSource)(nil), "k8s.io.kubernetes.pkg.api.v1.AWSElasticBlockStoreVolumeSource") proto.RegisterType((*Affinity)(nil), "k8s.io.kubernetes.pkg.api.v1.Affinity") proto.RegisterType((*AttachedVolume)(nil), "k8s.io.kubernetes.pkg.api.v1.AttachedVolume") + proto.RegisterType((*AvoidPods)(nil), "k8s.io.kubernetes.pkg.api.v1.AvoidPods") proto.RegisterType((*AzureFileVolumeSource)(nil), "k8s.io.kubernetes.pkg.api.v1.AzureFileVolumeSource") proto.RegisterType((*Binding)(nil), "k8s.io.kubernetes.pkg.api.v1.Binding") proto.RegisterType((*Capabilities)(nil), "k8s.io.kubernetes.pkg.api.v1.Capabilities") @@ -896,6 +764,7 @@ func init() { proto.RegisterType((*PodLogOptions)(nil), "k8s.io.kubernetes.pkg.api.v1.PodLogOptions") proto.RegisterType((*PodProxyOptions)(nil), "k8s.io.kubernetes.pkg.api.v1.PodProxyOptions") proto.RegisterType((*PodSecurityContext)(nil), "k8s.io.kubernetes.pkg.api.v1.PodSecurityContext") + proto.RegisterType((*PodSignature)(nil), "k8s.io.kubernetes.pkg.api.v1.PodSignature") proto.RegisterType((*PodSpec)(nil), "k8s.io.kubernetes.pkg.api.v1.PodSpec") proto.RegisterType((*PodStatus)(nil), "k8s.io.kubernetes.pkg.api.v1.PodStatus") proto.RegisterType((*PodStatusResult)(nil), "k8s.io.kubernetes.pkg.api.v1.PodStatusResult") @@ -903,6 +772,7 @@ func init() { proto.RegisterType((*PodTemplateList)(nil), "k8s.io.kubernetes.pkg.api.v1.PodTemplateList") proto.RegisterType((*PodTemplateSpec)(nil), "k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec") proto.RegisterType((*Preconditions)(nil), "k8s.io.kubernetes.pkg.api.v1.Preconditions") + proto.RegisterType((*PreferAvoidPodsEntry)(nil), "k8s.io.kubernetes.pkg.api.v1.PreferAvoidPodsEntry") proto.RegisterType((*PreferredSchedulingTerm)(nil), "k8s.io.kubernetes.pkg.api.v1.PreferredSchedulingTerm") proto.RegisterType((*Probe)(nil), "k8s.io.kubernetes.pkg.api.v1.Probe") proto.RegisterType((*RBDVolumeSource)(nil), "k8s.io.kubernetes.pkg.api.v1.RBDVolumeSource") @@ -1052,6 +922,36 @@ func (m *AttachedVolume) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *AvoidPods) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *AvoidPods) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.PreferAvoidPods) > 0 { + for _, msg := range m.PreferAvoidPods { + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(msg.Size())) + n, err := msg.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + func (m *AzureFileVolumeSource) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -5625,6 +5525,34 @@ func (m *PodSecurityContext) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *PodSignature) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *PodSignature) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.PodController != nil { + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.PodController.Size())) + n114, err := m.PodController.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n114 + } + return i, nil +} + func (m *PodSpec) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -5739,11 +5667,11 @@ func (m *PodSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x72 i++ i = encodeVarintGenerated(data, i, uint64(m.SecurityContext.Size())) - n114, err := m.SecurityContext.MarshalTo(data[i:]) + n115, err := m.SecurityContext.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n114 + i += n115 } if len(m.ImagePullSecrets) > 0 { for _, msg := range m.ImagePullSecrets { @@ -5823,11 +5751,11 @@ func (m *PodStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x3a i++ i = encodeVarintGenerated(data, i, uint64(m.StartTime.Size())) - n115, err := m.StartTime.MarshalTo(data[i:]) + n116, err := m.StartTime.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n115 + i += n116 } if len(m.ContainerStatuses) > 0 { for _, msg := range m.ContainerStatuses { @@ -5862,19 +5790,19 @@ func (m *PodStatusResult) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n116, err := m.ObjectMeta.MarshalTo(data[i:]) + n117, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n116 + i += n117 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n117, err := m.Status.MarshalTo(data[i:]) + n118, err := m.Status.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n117 + i += n118 return i, nil } @@ -5896,19 +5824,19 @@ func (m *PodTemplate) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n118, err := m.ObjectMeta.MarshalTo(data[i:]) + n119, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n118 + i += n119 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) - n119, err := m.Template.MarshalTo(data[i:]) + n120, err := m.Template.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n119 + i += n120 return i, nil } @@ -5930,11 +5858,11 @@ func (m *PodTemplateList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n120, err := m.ListMeta.MarshalTo(data[i:]) + n121, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n120 + i += n121 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -5968,19 +5896,19 @@ func (m *PodTemplateSpec) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n121, err := m.ObjectMeta.MarshalTo(data[i:]) + n122, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n121 + i += n122 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n122, err := m.Spec.MarshalTo(data[i:]) + n123, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n122 + i += n123 return i, nil } @@ -6008,6 +5936,48 @@ func (m *Preconditions) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *PreferAvoidPodsEntry) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *PreferAvoidPodsEntry) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.PodSignature.Size())) + n124, err := m.PodSignature.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n124 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.EvictionTime.Size())) + n125, err := m.EvictionTime.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n125 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Reason))) + i += copy(data[i:], m.Reason) + data[i] = 0x22 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Message))) + i += copy(data[i:], m.Message) + return i, nil +} + func (m *PreferredSchedulingTerm) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -6029,11 +5999,11 @@ func (m *PreferredSchedulingTerm) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Preference.Size())) - n123, err := m.Preference.MarshalTo(data[i:]) + n126, err := m.Preference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n123 + i += n126 return i, nil } @@ -6055,11 +6025,11 @@ func (m *Probe) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Handler.Size())) - n124, err := m.Handler.MarshalTo(data[i:]) + n127, err := m.Handler.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n124 + i += n127 data[i] = 0x10 i++ i = encodeVarintGenerated(data, i, uint64(m.InitialDelaySeconds)) @@ -6132,11 +6102,11 @@ func (m *RBDVolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x3a i++ i = encodeVarintGenerated(data, i, uint64(m.SecretRef.Size())) - n125, err := m.SecretRef.MarshalTo(data[i:]) + n128, err := m.SecretRef.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n125 + i += n128 } data[i] = 0x40 i++ @@ -6167,11 +6137,11 @@ func (m *RangeAllocation) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n126, err := m.ObjectMeta.MarshalTo(data[i:]) + n129, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n126 + i += n129 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Range))) @@ -6203,27 +6173,27 @@ func (m *ReplicationController) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n127, err := m.ObjectMeta.MarshalTo(data[i:]) + n130, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n127 + i += n130 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n128, err := m.Spec.MarshalTo(data[i:]) + n131, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n128 + i += n131 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n129, err := m.Status.MarshalTo(data[i:]) + n132, err := m.Status.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n129 + i += n132 return i, nil } @@ -6245,11 +6215,11 @@ func (m *ReplicationControllerList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n130, err := m.ListMeta.MarshalTo(data[i:]) + n133, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n130 + i += n133 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6306,11 +6276,11 @@ func (m *ReplicationControllerSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Template.Size())) - n131, err := m.Template.MarshalTo(data[i:]) + n134, err := m.Template.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n131 + i += n134 } return i, nil } @@ -6368,11 +6338,11 @@ func (m *ResourceFieldSelector) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Divisor.Size())) - n132, err := m.Divisor.MarshalTo(data[i:]) + n135, err := m.Divisor.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n132 + i += n135 return i, nil } @@ -6394,27 +6364,27 @@ func (m *ResourceQuota) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n133, err := m.ObjectMeta.MarshalTo(data[i:]) + n136, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n133 + i += n136 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n134, err := m.Spec.MarshalTo(data[i:]) + n137, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n134 + i += n137 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n135, err := m.Status.MarshalTo(data[i:]) + n138, err := m.Status.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n135 + i += n138 return i, nil } @@ -6436,11 +6406,11 @@ func (m *ResourceQuotaList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n136, err := m.ListMeta.MarshalTo(data[i:]) + n139, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n136 + i += n139 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6486,11 +6456,11 @@ func (m *ResourceQuotaSpec) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n137, err := (&v).MarshalTo(data[i:]) + n140, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n137 + i += n140 } } if len(m.Scopes) > 0 { @@ -6541,11 +6511,11 @@ func (m *ResourceQuotaStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n138, err := (&v).MarshalTo(data[i:]) + n141, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n138 + i += n141 } } if len(m.Used) > 0 { @@ -6563,11 +6533,11 @@ func (m *ResourceQuotaStatus) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n139, err := (&v).MarshalTo(data[i:]) + n142, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n139 + i += n142 } } return i, nil @@ -6603,11 +6573,11 @@ func (m *ResourceRequirements) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n140, err := (&v).MarshalTo(data[i:]) + n143, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n140 + i += n143 } } if len(m.Requests) > 0 { @@ -6625,11 +6595,11 @@ func (m *ResourceRequirements) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64((&v).Size())) - n141, err := (&v).MarshalTo(data[i:]) + n144, err := (&v).MarshalTo(data[i:]) if err != nil { return 0, err } - i += n141 + i += n144 } } return i, nil @@ -6687,11 +6657,11 @@ func (m *Secret) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n142, err := m.ObjectMeta.MarshalTo(data[i:]) + n145, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n142 + i += n145 if len(m.Data) > 0 { for k := range m.Data { data[i] = 0x12 @@ -6713,6 +6683,23 @@ func (m *Secret) MarshalTo(data []byte) (int, error) { i++ i = encodeVarintGenerated(data, i, uint64(len(m.Type))) i += copy(data[i:], m.Type) + if len(m.StringData) > 0 { + for k := range m.StringData { + data[i] = 0x22 + i++ + v := m.StringData[k] + mapSize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + i = encodeVarintGenerated(data, i, uint64(mapSize)) + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(k))) + i += copy(data[i:], k) + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(v))) + i += copy(data[i:], v) + } + } return i, nil } @@ -6734,11 +6721,11 @@ func (m *SecretKeySelector) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.LocalObjectReference.Size())) - n143, err := m.LocalObjectReference.MarshalTo(data[i:]) + n146, err := m.LocalObjectReference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n143 + i += n146 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Key))) @@ -6764,11 +6751,11 @@ func (m *SecretList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n144, err := m.ListMeta.MarshalTo(data[i:]) + n147, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n144 + i += n147 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -6837,11 +6824,11 @@ func (m *SecurityContext) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Capabilities.Size())) - n145, err := m.Capabilities.MarshalTo(data[i:]) + n148, err := m.Capabilities.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n145 + i += n148 } if m.Privileged != nil { data[i] = 0x10 @@ -6857,11 +6844,11 @@ func (m *SecurityContext) MarshalTo(data []byte) (int, error) { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.SELinuxOptions.Size())) - n146, err := m.SELinuxOptions.MarshalTo(data[i:]) + n149, err := m.SELinuxOptions.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n146 + i += n149 } if m.RunAsUser != nil { data[i] = 0x20 @@ -6909,11 +6896,11 @@ func (m *SerializedReference) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Reference.Size())) - n147, err := m.Reference.MarshalTo(data[i:]) + n150, err := m.Reference.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n147 + i += n150 return i, nil } @@ -6935,27 +6922,27 @@ func (m *Service) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n148, err := m.ObjectMeta.MarshalTo(data[i:]) + n151, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n148 + i += n151 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) - n149, err := m.Spec.MarshalTo(data[i:]) + n152, err := m.Spec.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n149 + i += n152 data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) - n150, err := m.Status.MarshalTo(data[i:]) + n153, err := m.Status.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n150 + i += n153 return i, nil } @@ -6977,11 +6964,11 @@ func (m *ServiceAccount) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n151, err := m.ObjectMeta.MarshalTo(data[i:]) + n154, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n151 + i += n154 if len(m.Secrets) > 0 { for _, msg := range m.Secrets { data[i] = 0x12 @@ -7027,11 +7014,11 @@ func (m *ServiceAccountList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n152, err := m.ListMeta.MarshalTo(data[i:]) + n155, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n152 + i += n155 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -7065,11 +7052,11 @@ func (m *ServiceList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n153, err := m.ListMeta.MarshalTo(data[i:]) + n156, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n153 + i += n156 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -7114,11 +7101,11 @@ func (m *ServicePort) MarshalTo(data []byte) (int, error) { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(m.TargetPort.Size())) - n154, err := m.TargetPort.MarshalTo(data[i:]) + n157, err := m.TargetPort.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n154 + i += n157 data[i] = 0x28 i++ i = encodeVarintGenerated(data, i, uint64(m.NodePort)) @@ -7273,11 +7260,11 @@ func (m *ServiceStatus) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.LoadBalancer.Size())) - n155, err := m.LoadBalancer.MarshalTo(data[i:]) + n158, err := m.LoadBalancer.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n155 + i += n158 return i, nil } @@ -7299,11 +7286,11 @@ func (m *TCPSocketAction) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.Port.Size())) - n156, err := m.Port.MarshalTo(data[i:]) + n159, err := m.Port.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n156 + i += n159 return i, nil } @@ -7393,11 +7380,11 @@ func (m *Volume) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.VolumeSource.Size())) - n157, err := m.VolumeSource.MarshalTo(data[i:]) + n160, err := m.VolumeSource.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n157 + i += n160 return i, nil } @@ -7458,151 +7445,151 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.HostPath.Size())) - n158, err := m.HostPath.MarshalTo(data[i:]) + n161, err := m.HostPath.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n158 + i += n161 } if m.EmptyDir != nil { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.EmptyDir.Size())) - n159, err := m.EmptyDir.MarshalTo(data[i:]) + n162, err := m.EmptyDir.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n159 + i += n162 } if m.GCEPersistentDisk != nil { data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(m.GCEPersistentDisk.Size())) - n160, err := m.GCEPersistentDisk.MarshalTo(data[i:]) + n163, err := m.GCEPersistentDisk.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n160 + i += n163 } if m.AWSElasticBlockStore != nil { data[i] = 0x22 i++ i = encodeVarintGenerated(data, i, uint64(m.AWSElasticBlockStore.Size())) - n161, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) + n164, err := m.AWSElasticBlockStore.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n161 + i += n164 } if m.GitRepo != nil { data[i] = 0x2a i++ i = encodeVarintGenerated(data, i, uint64(m.GitRepo.Size())) - n162, err := m.GitRepo.MarshalTo(data[i:]) + n165, err := m.GitRepo.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n162 + i += n165 } if m.Secret != nil { data[i] = 0x32 i++ i = encodeVarintGenerated(data, i, uint64(m.Secret.Size())) - n163, err := m.Secret.MarshalTo(data[i:]) + n166, err := m.Secret.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n163 + i += n166 } if m.NFS != nil { data[i] = 0x3a i++ i = encodeVarintGenerated(data, i, uint64(m.NFS.Size())) - n164, err := m.NFS.MarshalTo(data[i:]) + n167, err := m.NFS.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n164 + i += n167 } if m.ISCSI != nil { data[i] = 0x42 i++ i = encodeVarintGenerated(data, i, uint64(m.ISCSI.Size())) - n165, err := m.ISCSI.MarshalTo(data[i:]) + n168, err := m.ISCSI.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n165 + i += n168 } if m.Glusterfs != nil { data[i] = 0x4a i++ i = encodeVarintGenerated(data, i, uint64(m.Glusterfs.Size())) - n166, err := m.Glusterfs.MarshalTo(data[i:]) + n169, err := m.Glusterfs.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n166 + i += n169 } if m.PersistentVolumeClaim != nil { data[i] = 0x52 i++ i = encodeVarintGenerated(data, i, uint64(m.PersistentVolumeClaim.Size())) - n167, err := m.PersistentVolumeClaim.MarshalTo(data[i:]) + n170, err := m.PersistentVolumeClaim.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n167 + i += n170 } if m.RBD != nil { data[i] = 0x5a i++ i = encodeVarintGenerated(data, i, uint64(m.RBD.Size())) - n168, err := m.RBD.MarshalTo(data[i:]) + n171, err := m.RBD.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n168 + i += n171 } if m.FlexVolume != nil { data[i] = 0x62 i++ i = encodeVarintGenerated(data, i, uint64(m.FlexVolume.Size())) - n169, err := m.FlexVolume.MarshalTo(data[i:]) + n172, err := m.FlexVolume.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n169 + i += n172 } if m.Cinder != nil { data[i] = 0x6a i++ i = encodeVarintGenerated(data, i, uint64(m.Cinder.Size())) - n170, err := m.Cinder.MarshalTo(data[i:]) + n173, err := m.Cinder.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n170 + i += n173 } if m.CephFS != nil { data[i] = 0x72 i++ i = encodeVarintGenerated(data, i, uint64(m.CephFS.Size())) - n171, err := m.CephFS.MarshalTo(data[i:]) + n174, err := m.CephFS.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n171 + i += n174 } if m.Flocker != nil { data[i] = 0x7a i++ i = encodeVarintGenerated(data, i, uint64(m.Flocker.Size())) - n172, err := m.Flocker.MarshalTo(data[i:]) + n175, err := m.Flocker.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n172 + i += n175 } if m.DownwardAPI != nil { data[i] = 0x82 @@ -7610,11 +7597,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.DownwardAPI.Size())) - n173, err := m.DownwardAPI.MarshalTo(data[i:]) + n176, err := m.DownwardAPI.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n173 + i += n176 } if m.FC != nil { data[i] = 0x8a @@ -7622,11 +7609,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.FC.Size())) - n174, err := m.FC.MarshalTo(data[i:]) + n177, err := m.FC.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n174 + i += n177 } if m.AzureFile != nil { data[i] = 0x92 @@ -7634,11 +7621,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.AzureFile.Size())) - n175, err := m.AzureFile.MarshalTo(data[i:]) + n178, err := m.AzureFile.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n175 + i += n178 } if m.ConfigMap != nil { data[i] = 0x9a @@ -7646,11 +7633,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.ConfigMap.Size())) - n176, err := m.ConfigMap.MarshalTo(data[i:]) + n179, err := m.ConfigMap.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n176 + i += n179 } if m.VsphereVolume != nil { data[i] = 0xa2 @@ -7658,11 +7645,11 @@ func (m *VolumeSource) MarshalTo(data []byte) (int, error) { data[i] = 0x1 i++ i = encodeVarintGenerated(data, i, uint64(m.VsphereVolume.Size())) - n177, err := m.VsphereVolume.MarshalTo(data[i:]) + n180, err := m.VsphereVolume.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n177 + i += n180 } return i, nil } @@ -7714,11 +7701,11 @@ func (m *WeightedPodAffinityTerm) MarshalTo(data []byte) (int, error) { data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(m.PodAffinityTerm.Size())) - n178, err := m.PodAffinityTerm.MarshalTo(data[i:]) + n181, err := m.PodAffinityTerm.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n178 + i += n181 return i, nil } @@ -7789,6 +7776,18 @@ func (m *AttachedVolume) Size() (n int) { return n } +func (m *AvoidPods) Size() (n int) { + var l int + _ = l + if len(m.PreferAvoidPods) > 0 { + for _, e := range m.PreferAvoidPods { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *AzureFileVolumeSource) Size() (n int) { var l int _ = l @@ -9470,6 +9469,16 @@ func (m *PodSecurityContext) Size() (n int) { return n } +func (m *PodSignature) Size() (n int) { + var l int + _ = l + if m.PodController != nil { + l = m.PodController.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + func (m *PodSpec) Size() (n int) { var l int _ = l @@ -9615,6 +9624,20 @@ func (m *Preconditions) Size() (n int) { return n } +func (m *PreferAvoidPodsEntry) Size() (n int) { + var l int + _ = l + l = m.PodSignature.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.EvictionTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + return n +} + func (m *PreferredSchedulingTerm) Size() (n int) { var l int _ = l @@ -9870,6 +9893,14 @@ func (m *Secret) Size() (n int) { } l = len(m.Type) n += 1 + l + sovGenerated(uint64(l)) + if len(m.StringData) > 0 { + for k, v := range m.StringData { + _ = k + _ = v + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } return n } @@ -10256,6 +10287,2144 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *AWSElasticBlockStoreVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AWSElasticBlockStoreVolumeSource{`, + `VolumeID:` + fmt.Sprintf("%v", this.VolumeID) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `Partition:` + fmt.Sprintf("%v", this.Partition) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *Affinity) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Affinity{`, + `NodeAffinity:` + strings.Replace(fmt.Sprintf("%v", this.NodeAffinity), "NodeAffinity", "NodeAffinity", 1) + `,`, + `PodAffinity:` + strings.Replace(fmt.Sprintf("%v", this.PodAffinity), "PodAffinity", "PodAffinity", 1) + `,`, + `PodAntiAffinity:` + strings.Replace(fmt.Sprintf("%v", this.PodAntiAffinity), "PodAntiAffinity", "PodAntiAffinity", 1) + `,`, + `}`, + }, "") + return s +} +func (this *AttachedVolume) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AttachedVolume{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `DevicePath:` + fmt.Sprintf("%v", this.DevicePath) + `,`, + `}`, + }, "") + return s +} +func (this *AvoidPods) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AvoidPods{`, + `PreferAvoidPods:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.PreferAvoidPods), "PreferAvoidPodsEntry", "PreferAvoidPodsEntry", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *AzureFileVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&AzureFileVolumeSource{`, + `SecretName:` + fmt.Sprintf("%v", this.SecretName) + `,`, + `ShareName:` + fmt.Sprintf("%v", this.ShareName) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *Binding) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Binding{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Target:` + strings.Replace(strings.Replace(this.Target.String(), "ObjectReference", "ObjectReference", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Capabilities) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Capabilities{`, + `Add:` + fmt.Sprintf("%v", this.Add) + `,`, + `Drop:` + fmt.Sprintf("%v", this.Drop) + `,`, + `}`, + }, "") + return s +} +func (this *CephFSVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CephFSVolumeSource{`, + `Monitors:` + fmt.Sprintf("%v", this.Monitors) + `,`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `User:` + fmt.Sprintf("%v", this.User) + `,`, + `SecretFile:` + fmt.Sprintf("%v", this.SecretFile) + `,`, + `SecretRef:` + strings.Replace(fmt.Sprintf("%v", this.SecretRef), "LocalObjectReference", "LocalObjectReference", 1) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *CinderVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CinderVolumeSource{`, + `VolumeID:` + fmt.Sprintf("%v", this.VolumeID) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *ComponentCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ComponentCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Error:` + fmt.Sprintf("%v", this.Error) + `,`, + `}`, + }, "") + return s +} +func (this *ComponentStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ComponentStatus{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "ComponentCondition", "ComponentCondition", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ComponentStatusList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ComponentStatusList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ComponentStatus", "ComponentStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ConfigMap) String() string { + if this == nil { + return "nil" + } + keysForData := make([]string, 0, len(this.Data)) + for k := range this.Data { + keysForData = append(keysForData, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForData) + mapStringForData := "map[string]string{" + for _, k := range keysForData { + mapStringForData += fmt.Sprintf("%v: %v,", k, this.Data[k]) + } + mapStringForData += "}" + s := strings.Join([]string{`&ConfigMap{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Data:` + mapStringForData + `,`, + `}`, + }, "") + return s +} +func (this *ConfigMapKeySelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ConfigMapKeySelector{`, + `LocalObjectReference:` + strings.Replace(strings.Replace(this.LocalObjectReference.String(), "LocalObjectReference", "LocalObjectReference", 1), `&`, ``, 1) + `,`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `}`, + }, "") + return s +} +func (this *ConfigMapList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ConfigMapList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ConfigMap", "ConfigMap", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ConfigMapVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ConfigMapVolumeSource{`, + `LocalObjectReference:` + strings.Replace(strings.Replace(this.LocalObjectReference.String(), "LocalObjectReference", "LocalObjectReference", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "KeyToPath", "KeyToPath", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Container) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Container{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Image:` + fmt.Sprintf("%v", this.Image) + `,`, + `Command:` + fmt.Sprintf("%v", this.Command) + `,`, + `Args:` + fmt.Sprintf("%v", this.Args) + `,`, + `WorkingDir:` + fmt.Sprintf("%v", this.WorkingDir) + `,`, + `Ports:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ports), "ContainerPort", "ContainerPort", 1), `&`, ``, 1) + `,`, + `Env:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Env), "EnvVar", "EnvVar", 1), `&`, ``, 1) + `,`, + `Resources:` + strings.Replace(strings.Replace(this.Resources.String(), "ResourceRequirements", "ResourceRequirements", 1), `&`, ``, 1) + `,`, + `VolumeMounts:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.VolumeMounts), "VolumeMount", "VolumeMount", 1), `&`, ``, 1) + `,`, + `LivenessProbe:` + strings.Replace(fmt.Sprintf("%v", this.LivenessProbe), "Probe", "Probe", 1) + `,`, + `ReadinessProbe:` + strings.Replace(fmt.Sprintf("%v", this.ReadinessProbe), "Probe", "Probe", 1) + `,`, + `Lifecycle:` + strings.Replace(fmt.Sprintf("%v", this.Lifecycle), "Lifecycle", "Lifecycle", 1) + `,`, + `TerminationMessagePath:` + fmt.Sprintf("%v", this.TerminationMessagePath) + `,`, + `ImagePullPolicy:` + fmt.Sprintf("%v", this.ImagePullPolicy) + `,`, + `SecurityContext:` + strings.Replace(fmt.Sprintf("%v", this.SecurityContext), "SecurityContext", "SecurityContext", 1) + `,`, + `Stdin:` + fmt.Sprintf("%v", this.Stdin) + `,`, + `StdinOnce:` + fmt.Sprintf("%v", this.StdinOnce) + `,`, + `TTY:` + fmt.Sprintf("%v", this.TTY) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerImage) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerImage{`, + `Names:` + fmt.Sprintf("%v", this.Names) + `,`, + `SizeBytes:` + fmt.Sprintf("%v", this.SizeBytes) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerPort) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerPort{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `HostPort:` + fmt.Sprintf("%v", this.HostPort) + `,`, + `ContainerPort:` + fmt.Sprintf("%v", this.ContainerPort) + `,`, + `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`, + `HostIP:` + fmt.Sprintf("%v", this.HostIP) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerState) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerState{`, + `Waiting:` + strings.Replace(fmt.Sprintf("%v", this.Waiting), "ContainerStateWaiting", "ContainerStateWaiting", 1) + `,`, + `Running:` + strings.Replace(fmt.Sprintf("%v", this.Running), "ContainerStateRunning", "ContainerStateRunning", 1) + `,`, + `Terminated:` + strings.Replace(fmt.Sprintf("%v", this.Terminated), "ContainerStateTerminated", "ContainerStateTerminated", 1) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerStateRunning) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerStateRunning{`, + `StartedAt:` + strings.Replace(strings.Replace(this.StartedAt.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerStateTerminated) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerStateTerminated{`, + `ExitCode:` + fmt.Sprintf("%v", this.ExitCode) + `,`, + `Signal:` + fmt.Sprintf("%v", this.Signal) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `StartedAt:` + strings.Replace(strings.Replace(this.StartedAt.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `FinishedAt:` + strings.Replace(strings.Replace(this.FinishedAt.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `ContainerID:` + fmt.Sprintf("%v", this.ContainerID) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerStateWaiting) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerStateWaiting{`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *ContainerStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ContainerStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `State:` + strings.Replace(strings.Replace(this.State.String(), "ContainerState", "ContainerState", 1), `&`, ``, 1) + `,`, + `LastTerminationState:` + strings.Replace(strings.Replace(this.LastTerminationState.String(), "ContainerState", "ContainerState", 1), `&`, ``, 1) + `,`, + `Ready:` + fmt.Sprintf("%v", this.Ready) + `,`, + `RestartCount:` + fmt.Sprintf("%v", this.RestartCount) + `,`, + `Image:` + fmt.Sprintf("%v", this.Image) + `,`, + `ImageID:` + fmt.Sprintf("%v", this.ImageID) + `,`, + `ContainerID:` + fmt.Sprintf("%v", this.ContainerID) + `,`, + `}`, + }, "") + return s +} +func (this *DaemonEndpoint) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DaemonEndpoint{`, + `Port:` + fmt.Sprintf("%v", this.Port) + `,`, + `}`, + }, "") + return s +} +func (this *DeleteOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeleteOptions{`, + `GracePeriodSeconds:` + valueToStringGenerated(this.GracePeriodSeconds) + `,`, + `Preconditions:` + strings.Replace(fmt.Sprintf("%v", this.Preconditions), "Preconditions", "Preconditions", 1) + `,`, + `OrphanDependents:` + valueToStringGenerated(this.OrphanDependents) + `,`, + `}`, + }, "") + return s +} +func (this *DownwardAPIVolumeFile) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DownwardAPIVolumeFile{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `FieldRef:` + strings.Replace(fmt.Sprintf("%v", this.FieldRef), "ObjectFieldSelector", "ObjectFieldSelector", 1) + `,`, + `ResourceFieldRef:` + strings.Replace(fmt.Sprintf("%v", this.ResourceFieldRef), "ResourceFieldSelector", "ResourceFieldSelector", 1) + `,`, + `}`, + }, "") + return s +} +func (this *DownwardAPIVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DownwardAPIVolumeSource{`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "DownwardAPIVolumeFile", "DownwardAPIVolumeFile", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *EmptyDirVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EmptyDirVolumeSource{`, + `Medium:` + fmt.Sprintf("%v", this.Medium) + `,`, + `}`, + }, "") + return s +} +func (this *EndpointAddress) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EndpointAddress{`, + `IP:` + fmt.Sprintf("%v", this.IP) + `,`, + `TargetRef:` + strings.Replace(fmt.Sprintf("%v", this.TargetRef), "ObjectReference", "ObjectReference", 1) + `,`, + `Hostname:` + fmt.Sprintf("%v", this.Hostname) + `,`, + `}`, + }, "") + return s +} +func (this *EndpointPort) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EndpointPort{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Port:` + fmt.Sprintf("%v", this.Port) + `,`, + `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`, + `}`, + }, "") + return s +} +func (this *EndpointSubset) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EndpointSubset{`, + `Addresses:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Addresses), "EndpointAddress", "EndpointAddress", 1), `&`, ``, 1) + `,`, + `NotReadyAddresses:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.NotReadyAddresses), "EndpointAddress", "EndpointAddress", 1), `&`, ``, 1) + `,`, + `Ports:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ports), "EndpointPort", "EndpointPort", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Endpoints) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Endpoints{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Subsets:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Subsets), "EndpointSubset", "EndpointSubset", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *EndpointsList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EndpointsList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Endpoints", "Endpoints", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *EnvVar) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EnvVar{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `ValueFrom:` + strings.Replace(fmt.Sprintf("%v", this.ValueFrom), "EnvVarSource", "EnvVarSource", 1) + `,`, + `}`, + }, "") + return s +} +func (this *EnvVarSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EnvVarSource{`, + `FieldRef:` + strings.Replace(fmt.Sprintf("%v", this.FieldRef), "ObjectFieldSelector", "ObjectFieldSelector", 1) + `,`, + `ResourceFieldRef:` + strings.Replace(fmt.Sprintf("%v", this.ResourceFieldRef), "ResourceFieldSelector", "ResourceFieldSelector", 1) + `,`, + `ConfigMapKeyRef:` + strings.Replace(fmt.Sprintf("%v", this.ConfigMapKeyRef), "ConfigMapKeySelector", "ConfigMapKeySelector", 1) + `,`, + `SecretKeyRef:` + strings.Replace(fmt.Sprintf("%v", this.SecretKeyRef), "SecretKeySelector", "SecretKeySelector", 1) + `,`, + `}`, + }, "") + return s +} +func (this *Event) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Event{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `InvolvedObject:` + strings.Replace(strings.Replace(this.InvolvedObject.String(), "ObjectReference", "ObjectReference", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Source:` + strings.Replace(strings.Replace(this.Source.String(), "EventSource", "EventSource", 1), `&`, ``, 1) + `,`, + `FirstTimestamp:` + strings.Replace(strings.Replace(this.FirstTimestamp.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTimestamp:` + strings.Replace(strings.Replace(this.LastTimestamp.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Count:` + fmt.Sprintf("%v", this.Count) + `,`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `}`, + }, "") + return s +} +func (this *EventList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EventList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Event", "Event", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *EventSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&EventSource{`, + `Component:` + fmt.Sprintf("%v", this.Component) + `,`, + `Host:` + fmt.Sprintf("%v", this.Host) + `,`, + `}`, + }, "") + return s +} +func (this *ExecAction) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ExecAction{`, + `Command:` + fmt.Sprintf("%v", this.Command) + `,`, + `}`, + }, "") + return s +} +func (this *ExportOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ExportOptions{`, + `Export:` + fmt.Sprintf("%v", this.Export) + `,`, + `Exact:` + fmt.Sprintf("%v", this.Exact) + `,`, + `}`, + }, "") + return s +} +func (this *FCVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&FCVolumeSource{`, + `TargetWWNs:` + fmt.Sprintf("%v", this.TargetWWNs) + `,`, + `Lun:` + valueToStringGenerated(this.Lun) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *FlexVolumeSource) String() string { + if this == nil { + return "nil" + } + keysForOptions := make([]string, 0, len(this.Options)) + for k := range this.Options { + keysForOptions = append(keysForOptions, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForOptions) + mapStringForOptions := "map[string]string{" + for _, k := range keysForOptions { + mapStringForOptions += fmt.Sprintf("%v: %v,", k, this.Options[k]) + } + mapStringForOptions += "}" + s := strings.Join([]string{`&FlexVolumeSource{`, + `Driver:` + fmt.Sprintf("%v", this.Driver) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `SecretRef:` + strings.Replace(fmt.Sprintf("%v", this.SecretRef), "LocalObjectReference", "LocalObjectReference", 1) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `Options:` + mapStringForOptions + `,`, + `}`, + }, "") + return s +} +func (this *FlockerVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&FlockerVolumeSource{`, + `DatasetName:` + fmt.Sprintf("%v", this.DatasetName) + `,`, + `}`, + }, "") + return s +} +func (this *GCEPersistentDiskVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GCEPersistentDiskVolumeSource{`, + `PDName:` + fmt.Sprintf("%v", this.PDName) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `Partition:` + fmt.Sprintf("%v", this.Partition) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *GitRepoVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GitRepoVolumeSource{`, + `Repository:` + fmt.Sprintf("%v", this.Repository) + `,`, + `Revision:` + fmt.Sprintf("%v", this.Revision) + `,`, + `Directory:` + fmt.Sprintf("%v", this.Directory) + `,`, + `}`, + }, "") + return s +} +func (this *GlusterfsVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&GlusterfsVolumeSource{`, + `EndpointsName:` + fmt.Sprintf("%v", this.EndpointsName) + `,`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *HTTPGetAction) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HTTPGetAction{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `Port:` + strings.Replace(strings.Replace(this.Port.String(), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1), `&`, ``, 1) + `,`, + `Host:` + fmt.Sprintf("%v", this.Host) + `,`, + `Scheme:` + fmt.Sprintf("%v", this.Scheme) + `,`, + `HTTPHeaders:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.HTTPHeaders), "HTTPHeader", "HTTPHeader", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HTTPHeader) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HTTPHeader{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `}`, + }, "") + return s +} +func (this *Handler) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Handler{`, + `Exec:` + strings.Replace(fmt.Sprintf("%v", this.Exec), "ExecAction", "ExecAction", 1) + `,`, + `HTTPGet:` + strings.Replace(fmt.Sprintf("%v", this.HTTPGet), "HTTPGetAction", "HTTPGetAction", 1) + `,`, + `TCPSocket:` + strings.Replace(fmt.Sprintf("%v", this.TCPSocket), "TCPSocketAction", "TCPSocketAction", 1) + `,`, + `}`, + }, "") + return s +} +func (this *HostPathVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HostPathVolumeSource{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `}`, + }, "") + return s +} +func (this *ISCSIVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ISCSIVolumeSource{`, + `TargetPortal:` + fmt.Sprintf("%v", this.TargetPortal) + `,`, + `IQN:` + fmt.Sprintf("%v", this.IQN) + `,`, + `Lun:` + fmt.Sprintf("%v", this.Lun) + `,`, + `ISCSIInterface:` + fmt.Sprintf("%v", this.ISCSIInterface) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *KeyToPath) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&KeyToPath{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `}`, + }, "") + return s +} +func (this *Lifecycle) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Lifecycle{`, + `PostStart:` + strings.Replace(fmt.Sprintf("%v", this.PostStart), "Handler", "Handler", 1) + `,`, + `PreStop:` + strings.Replace(fmt.Sprintf("%v", this.PreStop), "Handler", "Handler", 1) + `,`, + `}`, + }, "") + return s +} +func (this *LimitRange) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LimitRange{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "LimitRangeSpec", "LimitRangeSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LimitRangeItem) String() string { + if this == nil { + return "nil" + } + keysForMax := make([]string, 0, len(this.Max)) + for k := range this.Max { + keysForMax = append(keysForMax, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMax) + mapStringForMax := "ResourceList{" + for _, k := range keysForMax { + mapStringForMax += fmt.Sprintf("%v: %v,", k, this.Max[ResourceName(k)]) + } + mapStringForMax += "}" + keysForMin := make([]string, 0, len(this.Min)) + for k := range this.Min { + keysForMin = append(keysForMin, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMin) + mapStringForMin := "ResourceList{" + for _, k := range keysForMin { + mapStringForMin += fmt.Sprintf("%v: %v,", k, this.Min[ResourceName(k)]) + } + mapStringForMin += "}" + keysForDefault := make([]string, 0, len(this.Default)) + for k := range this.Default { + keysForDefault = append(keysForDefault, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForDefault) + mapStringForDefault := "ResourceList{" + for _, k := range keysForDefault { + mapStringForDefault += fmt.Sprintf("%v: %v,", k, this.Default[ResourceName(k)]) + } + mapStringForDefault += "}" + keysForDefaultRequest := make([]string, 0, len(this.DefaultRequest)) + for k := range this.DefaultRequest { + keysForDefaultRequest = append(keysForDefaultRequest, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForDefaultRequest) + mapStringForDefaultRequest := "ResourceList{" + for _, k := range keysForDefaultRequest { + mapStringForDefaultRequest += fmt.Sprintf("%v: %v,", k, this.DefaultRequest[ResourceName(k)]) + } + mapStringForDefaultRequest += "}" + keysForMaxLimitRequestRatio := make([]string, 0, len(this.MaxLimitRequestRatio)) + for k := range this.MaxLimitRequestRatio { + keysForMaxLimitRequestRatio = append(keysForMaxLimitRequestRatio, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMaxLimitRequestRatio) + mapStringForMaxLimitRequestRatio := "ResourceList{" + for _, k := range keysForMaxLimitRequestRatio { + mapStringForMaxLimitRequestRatio += fmt.Sprintf("%v: %v,", k, this.MaxLimitRequestRatio[ResourceName(k)]) + } + mapStringForMaxLimitRequestRatio += "}" + s := strings.Join([]string{`&LimitRangeItem{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Max:` + mapStringForMax + `,`, + `Min:` + mapStringForMin + `,`, + `Default:` + mapStringForDefault + `,`, + `DefaultRequest:` + mapStringForDefaultRequest + `,`, + `MaxLimitRequestRatio:` + mapStringForMaxLimitRequestRatio + `,`, + `}`, + }, "") + return s +} +func (this *LimitRangeList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LimitRangeList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "LimitRange", "LimitRange", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LimitRangeSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LimitRangeSpec{`, + `Limits:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Limits), "LimitRangeItem", "LimitRangeItem", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *List) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&List{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "RawExtension", "k8s_io_kubernetes_pkg_runtime.RawExtension", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ListOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ListOptions{`, + `LabelSelector:` + fmt.Sprintf("%v", this.LabelSelector) + `,`, + `FieldSelector:` + fmt.Sprintf("%v", this.FieldSelector) + `,`, + `Watch:` + fmt.Sprintf("%v", this.Watch) + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `TimeoutSeconds:` + valueToStringGenerated(this.TimeoutSeconds) + `,`, + `}`, + }, "") + return s +} +func (this *LoadBalancerIngress) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LoadBalancerIngress{`, + `IP:` + fmt.Sprintf("%v", this.IP) + `,`, + `Hostname:` + fmt.Sprintf("%v", this.Hostname) + `,`, + `}`, + }, "") + return s +} +func (this *LoadBalancerStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LoadBalancerStatus{`, + `Ingress:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ingress), "LoadBalancerIngress", "LoadBalancerIngress", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LocalObjectReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LocalObjectReference{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `}`, + }, "") + return s +} +func (this *NFSVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NFSVolumeSource{`, + `Server:` + fmt.Sprintf("%v", this.Server) + `,`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *Namespace) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Namespace{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "NamespaceSpec", "NamespaceSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "NamespaceStatus", "NamespaceStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NamespaceList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NamespaceList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Namespace", "Namespace", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NamespaceSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NamespaceSpec{`, + `Finalizers:` + fmt.Sprintf("%v", this.Finalizers) + `,`, + `}`, + }, "") + return s +} +func (this *NamespaceStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NamespaceStatus{`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `}`, + }, "") + return s +} +func (this *Node) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Node{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "NodeSpec", "NodeSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "NodeStatus", "NodeStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAddress) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAddress{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Address:` + fmt.Sprintf("%v", this.Address) + `,`, + `}`, + }, "") + return s +} +func (this *NodeAffinity) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeAffinity{`, + `RequiredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(fmt.Sprintf("%v", this.RequiredDuringSchedulingIgnoredDuringExecution), "NodeSelector", "NodeSelector", 1) + `,`, + `PreferredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.PreferredDuringSchedulingIgnoredDuringExecution), "PreferredSchedulingTerm", "PreferredSchedulingTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `LastHeartbeatTime:` + strings.Replace(strings.Replace(this.LastHeartbeatTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(this.LastTransitionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *NodeDaemonEndpoints) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeDaemonEndpoints{`, + `KubeletEndpoint:` + strings.Replace(strings.Replace(this.KubeletEndpoint.String(), "DaemonEndpoint", "DaemonEndpoint", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Node", "Node", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeProxyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeProxyOptions{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `}`, + }, "") + return s +} +func (this *NodeSelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeSelector{`, + `NodeSelectorTerms:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.NodeSelectorTerms), "NodeSelectorTerm", "NodeSelectorTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeSelectorRequirement) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeSelectorRequirement{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Values:` + fmt.Sprintf("%v", this.Values) + `,`, + `}`, + }, "") + return s +} +func (this *NodeSelectorTerm) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeSelectorTerm{`, + `MatchExpressions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.MatchExpressions), "NodeSelectorRequirement", "NodeSelectorRequirement", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeSpec{`, + `PodCIDR:` + fmt.Sprintf("%v", this.PodCIDR) + `,`, + `ExternalID:` + fmt.Sprintf("%v", this.ExternalID) + `,`, + `ProviderID:` + fmt.Sprintf("%v", this.ProviderID) + `,`, + `Unschedulable:` + fmt.Sprintf("%v", this.Unschedulable) + `,`, + `}`, + }, "") + return s +} +func (this *NodeStatus) String() string { + if this == nil { + return "nil" + } + keysForCapacity := make([]string, 0, len(this.Capacity)) + for k := range this.Capacity { + keysForCapacity = append(keysForCapacity, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForCapacity) + mapStringForCapacity := "ResourceList{" + for _, k := range keysForCapacity { + mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[ResourceName(k)]) + } + mapStringForCapacity += "}" + keysForAllocatable := make([]string, 0, len(this.Allocatable)) + for k := range this.Allocatable { + keysForAllocatable = append(keysForAllocatable, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForAllocatable) + mapStringForAllocatable := "ResourceList{" + for _, k := range keysForAllocatable { + mapStringForAllocatable += fmt.Sprintf("%v: %v,", k, this.Allocatable[ResourceName(k)]) + } + mapStringForAllocatable += "}" + s := strings.Join([]string{`&NodeStatus{`, + `Capacity:` + mapStringForCapacity + `,`, + `Allocatable:` + mapStringForAllocatable + `,`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "NodeCondition", "NodeCondition", 1), `&`, ``, 1) + `,`, + `Addresses:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Addresses), "NodeAddress", "NodeAddress", 1), `&`, ``, 1) + `,`, + `DaemonEndpoints:` + strings.Replace(strings.Replace(this.DaemonEndpoints.String(), "NodeDaemonEndpoints", "NodeDaemonEndpoints", 1), `&`, ``, 1) + `,`, + `NodeInfo:` + strings.Replace(strings.Replace(this.NodeInfo.String(), "NodeSystemInfo", "NodeSystemInfo", 1), `&`, ``, 1) + `,`, + `Images:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Images), "ContainerImage", "ContainerImage", 1), `&`, ``, 1) + `,`, + `VolumesInUse:` + fmt.Sprintf("%v", this.VolumesInUse) + `,`, + `VolumesAttached:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.VolumesAttached), "AttachedVolume", "AttachedVolume", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NodeSystemInfo) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NodeSystemInfo{`, + `MachineID:` + fmt.Sprintf("%v", this.MachineID) + `,`, + `SystemUUID:` + fmt.Sprintf("%v", this.SystemUUID) + `,`, + `BootID:` + fmt.Sprintf("%v", this.BootID) + `,`, + `KernelVersion:` + fmt.Sprintf("%v", this.KernelVersion) + `,`, + `OSImage:` + fmt.Sprintf("%v", this.OSImage) + `,`, + `ContainerRuntimeVersion:` + fmt.Sprintf("%v", this.ContainerRuntimeVersion) + `,`, + `KubeletVersion:` + fmt.Sprintf("%v", this.KubeletVersion) + `,`, + `KubeProxyVersion:` + fmt.Sprintf("%v", this.KubeProxyVersion) + `,`, + `OperatingSystem:` + fmt.Sprintf("%v", this.OperatingSystem) + `,`, + `Architecture:` + fmt.Sprintf("%v", this.Architecture) + `,`, + `}`, + }, "") + return s +} +func (this *ObjectFieldSelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ObjectFieldSelector{`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `FieldPath:` + fmt.Sprintf("%v", this.FieldPath) + `,`, + `}`, + }, "") + return s +} +func (this *ObjectMeta) String() string { + if this == nil { + return "nil" + } + keysForLabels := make([]string, 0, len(this.Labels)) + for k := range this.Labels { + keysForLabels = append(keysForLabels, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForLabels) + mapStringForLabels := "map[string]string{" + for _, k := range keysForLabels { + mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k]) + } + mapStringForLabels += "}" + keysForAnnotations := make([]string, 0, len(this.Annotations)) + for k := range this.Annotations { + keysForAnnotations = append(keysForAnnotations, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForAnnotations) + mapStringForAnnotations := "map[string]string{" + for _, k := range keysForAnnotations { + mapStringForAnnotations += fmt.Sprintf("%v: %v,", k, this.Annotations[k]) + } + mapStringForAnnotations += "}" + s := strings.Join([]string{`&ObjectMeta{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `GenerateName:` + fmt.Sprintf("%v", this.GenerateName) + `,`, + `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, + `SelfLink:` + fmt.Sprintf("%v", this.SelfLink) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `Generation:` + fmt.Sprintf("%v", this.Generation) + `,`, + `CreationTimestamp:` + strings.Replace(strings.Replace(this.CreationTimestamp.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `DeletionTimestamp:` + strings.Replace(fmt.Sprintf("%v", this.DeletionTimestamp), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `DeletionGracePeriodSeconds:` + valueToStringGenerated(this.DeletionGracePeriodSeconds) + `,`, + `Labels:` + mapStringForLabels + `,`, + `Annotations:` + mapStringForAnnotations + `,`, + `OwnerReferences:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.OwnerReferences), "OwnerReference", "OwnerReference", 1), `&`, ``, 1) + `,`, + `Finalizers:` + fmt.Sprintf("%v", this.Finalizers) + `,`, + `}`, + }, "") + return s +} +func (this *ObjectReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ObjectReference{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `FieldPath:` + fmt.Sprintf("%v", this.FieldPath) + `,`, + `}`, + }, "") + return s +} +func (this *OwnerReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&OwnerReference{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `Controller:` + valueToStringGenerated(this.Controller) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolume) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolume{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PersistentVolumeSpec", "PersistentVolumeSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PersistentVolumeStatus", "PersistentVolumeStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeClaim) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeClaim{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PersistentVolumeClaimSpec", "PersistentVolumeClaimSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PersistentVolumeClaimStatus", "PersistentVolumeClaimStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeClaimList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeClaimList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PersistentVolumeClaim", "PersistentVolumeClaim", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeClaimSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeClaimSpec{`, + `AccessModes:` + fmt.Sprintf("%v", this.AccessModes) + `,`, + `Resources:` + strings.Replace(strings.Replace(this.Resources.String(), "ResourceRequirements", "ResourceRequirements", 1), `&`, ``, 1) + `,`, + `VolumeName:` + fmt.Sprintf("%v", this.VolumeName) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "k8s_io_kubernetes_pkg_api_unversioned.LabelSelector", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeClaimStatus) String() string { + if this == nil { + return "nil" + } + keysForCapacity := make([]string, 0, len(this.Capacity)) + for k := range this.Capacity { + keysForCapacity = append(keysForCapacity, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForCapacity) + mapStringForCapacity := "ResourceList{" + for _, k := range keysForCapacity { + mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[ResourceName(k)]) + } + mapStringForCapacity += "}" + s := strings.Join([]string{`&PersistentVolumeClaimStatus{`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `AccessModes:` + fmt.Sprintf("%v", this.AccessModes) + `,`, + `Capacity:` + mapStringForCapacity + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeClaimVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeClaimVolumeSource{`, + `ClaimName:` + fmt.Sprintf("%v", this.ClaimName) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PersistentVolume", "PersistentVolume", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeSource{`, + `GCEPersistentDisk:` + strings.Replace(fmt.Sprintf("%v", this.GCEPersistentDisk), "GCEPersistentDiskVolumeSource", "GCEPersistentDiskVolumeSource", 1) + `,`, + `AWSElasticBlockStore:` + strings.Replace(fmt.Sprintf("%v", this.AWSElasticBlockStore), "AWSElasticBlockStoreVolumeSource", "AWSElasticBlockStoreVolumeSource", 1) + `,`, + `HostPath:` + strings.Replace(fmt.Sprintf("%v", this.HostPath), "HostPathVolumeSource", "HostPathVolumeSource", 1) + `,`, + `Glusterfs:` + strings.Replace(fmt.Sprintf("%v", this.Glusterfs), "GlusterfsVolumeSource", "GlusterfsVolumeSource", 1) + `,`, + `NFS:` + strings.Replace(fmt.Sprintf("%v", this.NFS), "NFSVolumeSource", "NFSVolumeSource", 1) + `,`, + `RBD:` + strings.Replace(fmt.Sprintf("%v", this.RBD), "RBDVolumeSource", "RBDVolumeSource", 1) + `,`, + `ISCSI:` + strings.Replace(fmt.Sprintf("%v", this.ISCSI), "ISCSIVolumeSource", "ISCSIVolumeSource", 1) + `,`, + `Cinder:` + strings.Replace(fmt.Sprintf("%v", this.Cinder), "CinderVolumeSource", "CinderVolumeSource", 1) + `,`, + `CephFS:` + strings.Replace(fmt.Sprintf("%v", this.CephFS), "CephFSVolumeSource", "CephFSVolumeSource", 1) + `,`, + `FC:` + strings.Replace(fmt.Sprintf("%v", this.FC), "FCVolumeSource", "FCVolumeSource", 1) + `,`, + `Flocker:` + strings.Replace(fmt.Sprintf("%v", this.Flocker), "FlockerVolumeSource", "FlockerVolumeSource", 1) + `,`, + `FlexVolume:` + strings.Replace(fmt.Sprintf("%v", this.FlexVolume), "FlexVolumeSource", "FlexVolumeSource", 1) + `,`, + `AzureFile:` + strings.Replace(fmt.Sprintf("%v", this.AzureFile), "AzureFileVolumeSource", "AzureFileVolumeSource", 1) + `,`, + `VsphereVolume:` + strings.Replace(fmt.Sprintf("%v", this.VsphereVolume), "VsphereVirtualDiskVolumeSource", "VsphereVirtualDiskVolumeSource", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeSpec) String() string { + if this == nil { + return "nil" + } + keysForCapacity := make([]string, 0, len(this.Capacity)) + for k := range this.Capacity { + keysForCapacity = append(keysForCapacity, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForCapacity) + mapStringForCapacity := "ResourceList{" + for _, k := range keysForCapacity { + mapStringForCapacity += fmt.Sprintf("%v: %v,", k, this.Capacity[ResourceName(k)]) + } + mapStringForCapacity += "}" + s := strings.Join([]string{`&PersistentVolumeSpec{`, + `Capacity:` + mapStringForCapacity + `,`, + `PersistentVolumeSource:` + strings.Replace(strings.Replace(this.PersistentVolumeSource.String(), "PersistentVolumeSource", "PersistentVolumeSource", 1), `&`, ``, 1) + `,`, + `AccessModes:` + fmt.Sprintf("%v", this.AccessModes) + `,`, + `ClaimRef:` + strings.Replace(fmt.Sprintf("%v", this.ClaimRef), "ObjectReference", "ObjectReference", 1) + `,`, + `PersistentVolumeReclaimPolicy:` + fmt.Sprintf("%v", this.PersistentVolumeReclaimPolicy) + `,`, + `}`, + }, "") + return s +} +func (this *PersistentVolumeStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PersistentVolumeStatus{`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `}`, + }, "") + return s +} +func (this *Pod) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Pod{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodSpec", "PodSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodStatus", "PodStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodAffinity) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodAffinity{`, + `RequiredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.RequiredDuringSchedulingIgnoredDuringExecution), "PodAffinityTerm", "PodAffinityTerm", 1), `&`, ``, 1) + `,`, + `PreferredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.PreferredDuringSchedulingIgnoredDuringExecution), "WeightedPodAffinityTerm", "WeightedPodAffinityTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodAffinityTerm) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodAffinityTerm{`, + `LabelSelector:` + strings.Replace(fmt.Sprintf("%v", this.LabelSelector), "LabelSelector", "k8s_io_kubernetes_pkg_api_unversioned.LabelSelector", 1) + `,`, + `Namespaces:` + fmt.Sprintf("%v", this.Namespaces) + `,`, + `TopologyKey:` + fmt.Sprintf("%v", this.TopologyKey) + `,`, + `}`, + }, "") + return s +} +func (this *PodAntiAffinity) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodAntiAffinity{`, + `RequiredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.RequiredDuringSchedulingIgnoredDuringExecution), "PodAffinityTerm", "PodAffinityTerm", 1), `&`, ``, 1) + `,`, + `PreferredDuringSchedulingIgnoredDuringExecution:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.PreferredDuringSchedulingIgnoredDuringExecution), "WeightedPodAffinityTerm", "WeightedPodAffinityTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodAttachOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodAttachOptions{`, + `Stdin:` + fmt.Sprintf("%v", this.Stdin) + `,`, + `Stdout:` + fmt.Sprintf("%v", this.Stdout) + `,`, + `Stderr:` + fmt.Sprintf("%v", this.Stderr) + `,`, + `TTY:` + fmt.Sprintf("%v", this.TTY) + `,`, + `Container:` + fmt.Sprintf("%v", this.Container) + `,`, + `}`, + }, "") + return s +} +func (this *PodCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `LastProbeTime:` + strings.Replace(strings.Replace(this.LastProbeTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(this.LastTransitionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *PodExecOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodExecOptions{`, + `Stdin:` + fmt.Sprintf("%v", this.Stdin) + `,`, + `Stdout:` + fmt.Sprintf("%v", this.Stdout) + `,`, + `Stderr:` + fmt.Sprintf("%v", this.Stderr) + `,`, + `TTY:` + fmt.Sprintf("%v", this.TTY) + `,`, + `Container:` + fmt.Sprintf("%v", this.Container) + `,`, + `Command:` + fmt.Sprintf("%v", this.Command) + `,`, + `}`, + }, "") + return s +} +func (this *PodList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Pod", "Pod", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodLogOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodLogOptions{`, + `Container:` + fmt.Sprintf("%v", this.Container) + `,`, + `Follow:` + fmt.Sprintf("%v", this.Follow) + `,`, + `Previous:` + fmt.Sprintf("%v", this.Previous) + `,`, + `SinceSeconds:` + valueToStringGenerated(this.SinceSeconds) + `,`, + `SinceTime:` + strings.Replace(fmt.Sprintf("%v", this.SinceTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `Timestamps:` + fmt.Sprintf("%v", this.Timestamps) + `,`, + `TailLines:` + valueToStringGenerated(this.TailLines) + `,`, + `LimitBytes:` + valueToStringGenerated(this.LimitBytes) + `,`, + `}`, + }, "") + return s +} +func (this *PodProxyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodProxyOptions{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `}`, + }, "") + return s +} +func (this *PodSecurityContext) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodSecurityContext{`, + `SELinuxOptions:` + strings.Replace(fmt.Sprintf("%v", this.SELinuxOptions), "SELinuxOptions", "SELinuxOptions", 1) + `,`, + `RunAsUser:` + valueToStringGenerated(this.RunAsUser) + `,`, + `RunAsNonRoot:` + valueToStringGenerated(this.RunAsNonRoot) + `,`, + `SupplementalGroups:` + fmt.Sprintf("%v", this.SupplementalGroups) + `,`, + `FSGroup:` + valueToStringGenerated(this.FSGroup) + `,`, + `}`, + }, "") + return s +} +func (this *PodSignature) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodSignature{`, + `PodController:` + strings.Replace(fmt.Sprintf("%v", this.PodController), "OwnerReference", "OwnerReference", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodSpec) String() string { + if this == nil { + return "nil" + } + keysForNodeSelector := make([]string, 0, len(this.NodeSelector)) + for k := range this.NodeSelector { + keysForNodeSelector = append(keysForNodeSelector, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForNodeSelector) + mapStringForNodeSelector := "map[string]string{" + for _, k := range keysForNodeSelector { + mapStringForNodeSelector += fmt.Sprintf("%v: %v,", k, this.NodeSelector[k]) + } + mapStringForNodeSelector += "}" + s := strings.Join([]string{`&PodSpec{`, + `Volumes:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Volumes), "Volume", "Volume", 1), `&`, ``, 1) + `,`, + `Containers:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Containers), "Container", "Container", 1), `&`, ``, 1) + `,`, + `RestartPolicy:` + fmt.Sprintf("%v", this.RestartPolicy) + `,`, + `TerminationGracePeriodSeconds:` + valueToStringGenerated(this.TerminationGracePeriodSeconds) + `,`, + `ActiveDeadlineSeconds:` + valueToStringGenerated(this.ActiveDeadlineSeconds) + `,`, + `DNSPolicy:` + fmt.Sprintf("%v", this.DNSPolicy) + `,`, + `NodeSelector:` + mapStringForNodeSelector + `,`, + `ServiceAccountName:` + fmt.Sprintf("%v", this.ServiceAccountName) + `,`, + `DeprecatedServiceAccount:` + fmt.Sprintf("%v", this.DeprecatedServiceAccount) + `,`, + `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`, + `HostNetwork:` + fmt.Sprintf("%v", this.HostNetwork) + `,`, + `HostPID:` + fmt.Sprintf("%v", this.HostPID) + `,`, + `HostIPC:` + fmt.Sprintf("%v", this.HostIPC) + `,`, + `SecurityContext:` + strings.Replace(fmt.Sprintf("%v", this.SecurityContext), "PodSecurityContext", "PodSecurityContext", 1) + `,`, + `ImagePullSecrets:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ImagePullSecrets), "LocalObjectReference", "LocalObjectReference", 1), `&`, ``, 1) + `,`, + `Hostname:` + fmt.Sprintf("%v", this.Hostname) + `,`, + `Subdomain:` + fmt.Sprintf("%v", this.Subdomain) + `,`, + `}`, + }, "") + return s +} +func (this *PodStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodStatus{`, + `Phase:` + fmt.Sprintf("%v", this.Phase) + `,`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "PodCondition", "PodCondition", 1), `&`, ``, 1) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `HostIP:` + fmt.Sprintf("%v", this.HostIP) + `,`, + `PodIP:` + fmt.Sprintf("%v", this.PodIP) + `,`, + `StartTime:` + strings.Replace(fmt.Sprintf("%v", this.StartTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `ContainerStatuses:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ContainerStatuses), "ContainerStatus", "ContainerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodStatusResult) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodStatusResult{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodStatus", "PodStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodTemplate) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodTemplate{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodTemplateList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodTemplateList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PodTemplate", "PodTemplate", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodTemplateSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodTemplateSpec{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodSpec", "PodSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Preconditions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Preconditions{`, + `UID:` + valueToStringGenerated(this.UID) + `,`, + `}`, + }, "") + return s +} +func (this *PreferAvoidPodsEntry) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PreferAvoidPodsEntry{`, + `PodSignature:` + strings.Replace(strings.Replace(this.PodSignature.String(), "PodSignature", "PodSignature", 1), `&`, ``, 1) + `,`, + `EvictionTime:` + strings.Replace(strings.Replace(this.EvictionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *PreferredSchedulingTerm) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PreferredSchedulingTerm{`, + `Weight:` + fmt.Sprintf("%v", this.Weight) + `,`, + `Preference:` + strings.Replace(strings.Replace(this.Preference.String(), "NodeSelectorTerm", "NodeSelectorTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Probe) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Probe{`, + `Handler:` + strings.Replace(strings.Replace(this.Handler.String(), "Handler", "Handler", 1), `&`, ``, 1) + `,`, + `InitialDelaySeconds:` + fmt.Sprintf("%v", this.InitialDelaySeconds) + `,`, + `TimeoutSeconds:` + fmt.Sprintf("%v", this.TimeoutSeconds) + `,`, + `PeriodSeconds:` + fmt.Sprintf("%v", this.PeriodSeconds) + `,`, + `SuccessThreshold:` + fmt.Sprintf("%v", this.SuccessThreshold) + `,`, + `FailureThreshold:` + fmt.Sprintf("%v", this.FailureThreshold) + `,`, + `}`, + }, "") + return s +} +func (this *RBDVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RBDVolumeSource{`, + `CephMonitors:` + fmt.Sprintf("%v", this.CephMonitors) + `,`, + `RBDImage:` + fmt.Sprintf("%v", this.RBDImage) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `RBDPool:` + fmt.Sprintf("%v", this.RBDPool) + `,`, + `RadosUser:` + fmt.Sprintf("%v", this.RadosUser) + `,`, + `Keyring:` + fmt.Sprintf("%v", this.Keyring) + `,`, + `SecretRef:` + strings.Replace(fmt.Sprintf("%v", this.SecretRef), "LocalObjectReference", "LocalObjectReference", 1) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `}`, + }, "") + return s +} +func (this *RangeAllocation) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RangeAllocation{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Range:` + fmt.Sprintf("%v", this.Range) + `,`, + `Data:` + valueToStringGenerated(this.Data) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicationController) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicationController{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ReplicationControllerSpec", "ReplicationControllerSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ReplicationControllerStatus", "ReplicationControllerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicationControllerList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicationControllerList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ReplicationController", "ReplicationController", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicationControllerSpec) String() string { + if this == nil { + return "nil" + } + keysForSelector := make([]string, 0, len(this.Selector)) + for k := range this.Selector { + keysForSelector = append(keysForSelector, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForSelector) + mapStringForSelector := "map[string]string{" + for _, k := range keysForSelector { + mapStringForSelector += fmt.Sprintf("%v: %v,", k, this.Selector[k]) + } + mapStringForSelector += "}" + s := strings.Join([]string{`&ReplicationControllerSpec{`, + `Replicas:` + valueToStringGenerated(this.Replicas) + `,`, + `Selector:` + mapStringForSelector + `,`, + `Template:` + strings.Replace(fmt.Sprintf("%v", this.Template), "PodTemplateSpec", "PodTemplateSpec", 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicationControllerStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicationControllerStatus{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `FullyLabeledReplicas:` + fmt.Sprintf("%v", this.FullyLabeledReplicas) + `,`, + `ObservedGeneration:` + fmt.Sprintf("%v", this.ObservedGeneration) + `,`, + `}`, + }, "") + return s +} +func (this *ResourceFieldSelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ResourceFieldSelector{`, + `ContainerName:` + fmt.Sprintf("%v", this.ContainerName) + `,`, + `Resource:` + fmt.Sprintf("%v", this.Resource) + `,`, + `Divisor:` + strings.Replace(strings.Replace(this.Divisor.String(), "Quantity", "k8s_io_kubernetes_pkg_api_resource.Quantity", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ResourceQuota) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ResourceQuota{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ResourceQuotaSpec", "ResourceQuotaSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ResourceQuotaStatus", "ResourceQuotaStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ResourceQuotaList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ResourceQuotaList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ResourceQuota", "ResourceQuota", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ResourceQuotaSpec) String() string { + if this == nil { + return "nil" + } + keysForHard := make([]string, 0, len(this.Hard)) + for k := range this.Hard { + keysForHard = append(keysForHard, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForHard) + mapStringForHard := "ResourceList{" + for _, k := range keysForHard { + mapStringForHard += fmt.Sprintf("%v: %v,", k, this.Hard[ResourceName(k)]) + } + mapStringForHard += "}" + s := strings.Join([]string{`&ResourceQuotaSpec{`, + `Hard:` + mapStringForHard + `,`, + `Scopes:` + fmt.Sprintf("%v", this.Scopes) + `,`, + `}`, + }, "") + return s +} +func (this *ResourceQuotaStatus) String() string { + if this == nil { + return "nil" + } + keysForHard := make([]string, 0, len(this.Hard)) + for k := range this.Hard { + keysForHard = append(keysForHard, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForHard) + mapStringForHard := "ResourceList{" + for _, k := range keysForHard { + mapStringForHard += fmt.Sprintf("%v: %v,", k, this.Hard[ResourceName(k)]) + } + mapStringForHard += "}" + keysForUsed := make([]string, 0, len(this.Used)) + for k := range this.Used { + keysForUsed = append(keysForUsed, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForUsed) + mapStringForUsed := "ResourceList{" + for _, k := range keysForUsed { + mapStringForUsed += fmt.Sprintf("%v: %v,", k, this.Used[ResourceName(k)]) + } + mapStringForUsed += "}" + s := strings.Join([]string{`&ResourceQuotaStatus{`, + `Hard:` + mapStringForHard + `,`, + `Used:` + mapStringForUsed + `,`, + `}`, + }, "") + return s +} +func (this *ResourceRequirements) String() string { + if this == nil { + return "nil" + } + keysForLimits := make([]string, 0, len(this.Limits)) + for k := range this.Limits { + keysForLimits = append(keysForLimits, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForLimits) + mapStringForLimits := "ResourceList{" + for _, k := range keysForLimits { + mapStringForLimits += fmt.Sprintf("%v: %v,", k, this.Limits[ResourceName(k)]) + } + mapStringForLimits += "}" + keysForRequests := make([]string, 0, len(this.Requests)) + for k := range this.Requests { + keysForRequests = append(keysForRequests, string(k)) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForRequests) + mapStringForRequests := "ResourceList{" + for _, k := range keysForRequests { + mapStringForRequests += fmt.Sprintf("%v: %v,", k, this.Requests[ResourceName(k)]) + } + mapStringForRequests += "}" + s := strings.Join([]string{`&ResourceRequirements{`, + `Limits:` + mapStringForLimits + `,`, + `Requests:` + mapStringForRequests + `,`, + `}`, + }, "") + return s +} +func (this *SELinuxOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SELinuxOptions{`, + `User:` + fmt.Sprintf("%v", this.User) + `,`, + `Role:` + fmt.Sprintf("%v", this.Role) + `,`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Level:` + fmt.Sprintf("%v", this.Level) + `,`, + `}`, + }, "") + return s +} +func (this *Secret) String() string { + if this == nil { + return "nil" + } + keysForData := make([]string, 0, len(this.Data)) + for k := range this.Data { + keysForData = append(keysForData, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForData) + mapStringForData := "map[string][]byte{" + for _, k := range keysForData { + mapStringForData += fmt.Sprintf("%v: %v,", k, this.Data[k]) + } + mapStringForData += "}" + keysForStringData := make([]string, 0, len(this.StringData)) + for k := range this.StringData { + keysForStringData = append(keysForStringData, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForStringData) + mapStringForStringData := "map[string]string{" + for _, k := range keysForStringData { + mapStringForStringData += fmt.Sprintf("%v: %v,", k, this.StringData[k]) + } + mapStringForStringData += "}" + s := strings.Join([]string{`&Secret{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Data:` + mapStringForData + `,`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `StringData:` + mapStringForStringData + `,`, + `}`, + }, "") + return s +} +func (this *SecretKeySelector) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SecretKeySelector{`, + `LocalObjectReference:` + strings.Replace(strings.Replace(this.LocalObjectReference.String(), "LocalObjectReference", "LocalObjectReference", 1), `&`, ``, 1) + `,`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `}`, + }, "") + return s +} +func (this *SecretList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SecretList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Secret", "Secret", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *SecretVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SecretVolumeSource{`, + `SecretName:` + fmt.Sprintf("%v", this.SecretName) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "KeyToPath", "KeyToPath", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *SecurityContext) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SecurityContext{`, + `Capabilities:` + strings.Replace(fmt.Sprintf("%v", this.Capabilities), "Capabilities", "Capabilities", 1) + `,`, + `Privileged:` + valueToStringGenerated(this.Privileged) + `,`, + `SELinuxOptions:` + strings.Replace(fmt.Sprintf("%v", this.SELinuxOptions), "SELinuxOptions", "SELinuxOptions", 1) + `,`, + `RunAsUser:` + valueToStringGenerated(this.RunAsUser) + `,`, + `RunAsNonRoot:` + valueToStringGenerated(this.RunAsNonRoot) + `,`, + `ReadOnlyRootFilesystem:` + valueToStringGenerated(this.ReadOnlyRootFilesystem) + `,`, + `}`, + }, "") + return s +} +func (this *SerializedReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SerializedReference{`, + `Reference:` + strings.Replace(strings.Replace(this.Reference.String(), "ObjectReference", "ObjectReference", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Service) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Service{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ServiceSpec", "ServiceSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ServiceStatus", "ServiceStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceAccount) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServiceAccount{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "ObjectMeta", 1), `&`, ``, 1) + `,`, + `Secrets:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Secrets), "ObjectReference", "ObjectReference", 1), `&`, ``, 1) + `,`, + `ImagePullSecrets:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.ImagePullSecrets), "LocalObjectReference", "LocalObjectReference", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceAccountList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServiceAccountList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ServiceAccount", "ServiceAccount", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServiceList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Service", "Service", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ServicePort) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServicePort{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`, + `Port:` + fmt.Sprintf("%v", this.Port) + `,`, + `TargetPort:` + strings.Replace(strings.Replace(this.TargetPort.String(), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1), `&`, ``, 1) + `,`, + `NodePort:` + fmt.Sprintf("%v", this.NodePort) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceProxyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServiceProxyOptions{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceSpec) String() string { + if this == nil { + return "nil" + } + keysForSelector := make([]string, 0, len(this.Selector)) + for k := range this.Selector { + keysForSelector = append(keysForSelector, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForSelector) + mapStringForSelector := "map[string]string{" + for _, k := range keysForSelector { + mapStringForSelector += fmt.Sprintf("%v: %v,", k, this.Selector[k]) + } + mapStringForSelector += "}" + s := strings.Join([]string{`&ServiceSpec{`, + `Ports:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ports), "ServicePort", "ServicePort", 1), `&`, ``, 1) + `,`, + `Selector:` + mapStringForSelector + `,`, + `ClusterIP:` + fmt.Sprintf("%v", this.ClusterIP) + `,`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `ExternalIPs:` + fmt.Sprintf("%v", this.ExternalIPs) + `,`, + `DeprecatedPublicIPs:` + fmt.Sprintf("%v", this.DeprecatedPublicIPs) + `,`, + `SessionAffinity:` + fmt.Sprintf("%v", this.SessionAffinity) + `,`, + `LoadBalancerIP:` + fmt.Sprintf("%v", this.LoadBalancerIP) + `,`, + `LoadBalancerSourceRanges:` + fmt.Sprintf("%v", this.LoadBalancerSourceRanges) + `,`, + `}`, + }, "") + return s +} +func (this *ServiceStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ServiceStatus{`, + `LoadBalancer:` + strings.Replace(strings.Replace(this.LoadBalancer.String(), "LoadBalancerStatus", "LoadBalancerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *TCPSocketAction) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TCPSocketAction{`, + `Port:` + strings.Replace(strings.Replace(this.Port.String(), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Taint) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Taint{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `Effect:` + fmt.Sprintf("%v", this.Effect) + `,`, + `}`, + }, "") + return s +} +func (this *Toleration) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Toleration{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Value:` + fmt.Sprintf("%v", this.Value) + `,`, + `Effect:` + fmt.Sprintf("%v", this.Effect) + `,`, + `}`, + }, "") + return s +} +func (this *Volume) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Volume{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `VolumeSource:` + strings.Replace(strings.Replace(this.VolumeSource.String(), "VolumeSource", "VolumeSource", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *VolumeMount) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&VolumeMount{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`, + `MountPath:` + fmt.Sprintf("%v", this.MountPath) + `,`, + `SubPath:` + fmt.Sprintf("%v", this.SubPath) + `,`, + `}`, + }, "") + return s +} +func (this *VolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&VolumeSource{`, + `HostPath:` + strings.Replace(fmt.Sprintf("%v", this.HostPath), "HostPathVolumeSource", "HostPathVolumeSource", 1) + `,`, + `EmptyDir:` + strings.Replace(fmt.Sprintf("%v", this.EmptyDir), "EmptyDirVolumeSource", "EmptyDirVolumeSource", 1) + `,`, + `GCEPersistentDisk:` + strings.Replace(fmt.Sprintf("%v", this.GCEPersistentDisk), "GCEPersistentDiskVolumeSource", "GCEPersistentDiskVolumeSource", 1) + `,`, + `AWSElasticBlockStore:` + strings.Replace(fmt.Sprintf("%v", this.AWSElasticBlockStore), "AWSElasticBlockStoreVolumeSource", "AWSElasticBlockStoreVolumeSource", 1) + `,`, + `GitRepo:` + strings.Replace(fmt.Sprintf("%v", this.GitRepo), "GitRepoVolumeSource", "GitRepoVolumeSource", 1) + `,`, + `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "SecretVolumeSource", "SecretVolumeSource", 1) + `,`, + `NFS:` + strings.Replace(fmt.Sprintf("%v", this.NFS), "NFSVolumeSource", "NFSVolumeSource", 1) + `,`, + `ISCSI:` + strings.Replace(fmt.Sprintf("%v", this.ISCSI), "ISCSIVolumeSource", "ISCSIVolumeSource", 1) + `,`, + `Glusterfs:` + strings.Replace(fmt.Sprintf("%v", this.Glusterfs), "GlusterfsVolumeSource", "GlusterfsVolumeSource", 1) + `,`, + `PersistentVolumeClaim:` + strings.Replace(fmt.Sprintf("%v", this.PersistentVolumeClaim), "PersistentVolumeClaimVolumeSource", "PersistentVolumeClaimVolumeSource", 1) + `,`, + `RBD:` + strings.Replace(fmt.Sprintf("%v", this.RBD), "RBDVolumeSource", "RBDVolumeSource", 1) + `,`, + `FlexVolume:` + strings.Replace(fmt.Sprintf("%v", this.FlexVolume), "FlexVolumeSource", "FlexVolumeSource", 1) + `,`, + `Cinder:` + strings.Replace(fmt.Sprintf("%v", this.Cinder), "CinderVolumeSource", "CinderVolumeSource", 1) + `,`, + `CephFS:` + strings.Replace(fmt.Sprintf("%v", this.CephFS), "CephFSVolumeSource", "CephFSVolumeSource", 1) + `,`, + `Flocker:` + strings.Replace(fmt.Sprintf("%v", this.Flocker), "FlockerVolumeSource", "FlockerVolumeSource", 1) + `,`, + `DownwardAPI:` + strings.Replace(fmt.Sprintf("%v", this.DownwardAPI), "DownwardAPIVolumeSource", "DownwardAPIVolumeSource", 1) + `,`, + `FC:` + strings.Replace(fmt.Sprintf("%v", this.FC), "FCVolumeSource", "FCVolumeSource", 1) + `,`, + `AzureFile:` + strings.Replace(fmt.Sprintf("%v", this.AzureFile), "AzureFileVolumeSource", "AzureFileVolumeSource", 1) + `,`, + `ConfigMap:` + strings.Replace(fmt.Sprintf("%v", this.ConfigMap), "ConfigMapVolumeSource", "ConfigMapVolumeSource", 1) + `,`, + `VsphereVolume:` + strings.Replace(fmt.Sprintf("%v", this.VsphereVolume), "VsphereVirtualDiskVolumeSource", "VsphereVirtualDiskVolumeSource", 1) + `,`, + `}`, + }, "") + return s +} +func (this *VsphereVirtualDiskVolumeSource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&VsphereVirtualDiskVolumeSource{`, + `VolumePath:` + fmt.Sprintf("%v", this.VolumePath) + `,`, + `FSType:` + fmt.Sprintf("%v", this.FSType) + `,`, + `}`, + }, "") + return s +} +func (this *WeightedPodAffinityTerm) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&WeightedPodAffinityTerm{`, + `Weight:` + fmt.Sprintf("%v", this.Weight) + `,`, + `PodAffinityTerm:` + strings.Replace(strings.Replace(this.PodAffinityTerm.String(), "PodAffinityTerm", "PodAffinityTerm", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *AWSElasticBlockStoreVolumeSource) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -10660,7 +12829,7 @@ func (m *AttachedVolume) Unmarshal(data []byte) error { } return nil } -func (m *AzureFileVolumeSource) Unmarshal(data []byte) error { +func (m *AvoidPods) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { @@ -10683,17 +12852,17 @@ func (m *AzureFileVolumeSource) Unmarshal(data []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: AzureFileVolumeSource: wiretype end group for non-group") + return fmt.Errorf("proto: AvoidPods: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: AzureFileVolumeSource: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: AvoidPods: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SecretName", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field PreferAvoidPods", wireType) } - var stringLen uint64 + var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated @@ -10703,24 +12872,105 @@ func (m *AzureFileVolumeSource) Unmarshal(data []byte) error { } b := data[iNdEx] iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift + msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if msglen < 0 { return ErrInvalidLengthGenerated } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } - m.SecretName = string(data[iNdEx:postIndex]) + m.PreferAvoidPods = append(m.PreferAvoidPods, PreferAvoidPodsEntry{}) + if err := m.PreferAvoidPods[len(m.PreferAvoidPods)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShareName", wireType) + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AzureFileVolumeSource) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AzureFileVolumeSource: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AzureFileVolumeSource: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SecretName", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SecretName = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ShareName", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -26947,6 +29197,89 @@ func (m *PodSecurityContext) Unmarshal(data []byte) error { } return nil } +func (m *PodSignature) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PodSignature: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PodSignature: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodController", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.PodController == nil { + m.PodController = &OwnerReference{} + } + if err := m.PodController.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *PodSpec) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -28348,6 +30681,174 @@ func (m *Preconditions) Unmarshal(data []byte) error { } return nil } +func (m *PreferAvoidPodsEntry) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PreferAvoidPodsEntry: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PreferAvoidPodsEntry: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PodSignature", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PodSignature.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field EvictionTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.EvictionTime.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Reason = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(data[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *PreferredSchedulingTerm) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -31125,6 +33626,117 @@ func (m *Secret) Unmarshal(data []byte) error { } m.Type = SecretType(data[iNdEx:postIndex]) iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StringData", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var keykey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + keykey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLenmapkey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey := string(data[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + var valuekey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + valuekey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var stringLenmapvalue uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLenmapvalue |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapvalue := int(stringLenmapvalue) + if intStringLenmapvalue < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapvalue := iNdEx + intStringLenmapvalue + if postStringIndexmapvalue > l { + return io.ErrUnexpectedEOF + } + mapvalue := string(data[iNdEx:postStringIndexmapvalue]) + iNdEx = postStringIndexmapvalue + if m.StringData == nil { + m.StringData = make(map[string]string) + } + m.StringData[mapkey] = mapvalue + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/generated.proto b/vendor/k8s.io/kubernetes/pkg/api/v1/generated.proto index 4a99eec8854f..cc8d1baaca0d 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,13 +37,13 @@ option go_package = "v1"; // ownership management and SELinux relabeling. message AWSElasticBlockStoreVolumeSource { // Unique ID of the persistent disk resource in AWS (Amazon EBS volume). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore optional string volumeID = 1; // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore // TODO: how do we prevent errors in the filesystem from compromising the machine optional string fsType = 2; @@ -55,7 +55,7 @@ message AWSElasticBlockStoreVolumeSource { // Specify "true" to force and set the ReadOnly property in VolumeMounts to "true". // If omitted, the default is "false". - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore optional bool readOnly = 4; } @@ -80,6 +80,15 @@ message AttachedVolume { optional string devicePath = 2; } +// AvoidPods describes pods that should avoid this node. This is the value for a +// Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and +// will eventually become a field of NodeStatus. +message AvoidPods { + // Bounded-sized list of signatures of pods that should avoid this node, sorted + // in timestamp order from oldest to newest. Size of the slice is unspecified. + repeated PreferAvoidPodsEntry preferAvoidPods = 1; +} + // AzureFile represents an Azure File Service mount on the host and bind mount to the pod. message AzureFileVolumeSource { // the name of secret that contains Azure Storage Account Name and Key @@ -97,7 +106,7 @@ message AzureFileVolumeSource { // For example, a pod is bound to a node by a scheduler. message Binding { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // The target object that you want to bind to the standard object. @@ -117,27 +126,27 @@ message Capabilities { // Cephfs volumes do not support ownership management or SELinux relabeling. message CephFSVolumeSource { // Required: Monitors is a collection of Ceph monitors - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it repeated string monitors = 1; // Optional: Used as the mounted root, rather than the full Ceph tree, default is / optional string path = 2; // Optional: User is the rados user name, default is admin - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it optional string user = 3; // Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it optional string secretFile = 4; // Optional: SecretRef is reference to the authentication secret for User, default is empty. - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it optional LocalObjectReference secretRef = 5; // Optional: Defaults to false (read/write). ReadOnly here will force // the ReadOnly setting in VolumeMounts. - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it optional bool readOnly = 6; } @@ -147,18 +156,18 @@ message CephFSVolumeSource { // Cinder volumes support ownership management and SELinux relabeling. message CinderVolumeSource { // volume id used to identify the volume in cinder - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md optional string volumeID = 1; // Filesystem type to mount. // Must be a filesystem type supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md optional string fsType = 2; // Optional: Defaults to false (read/write). ReadOnly here will force // the ReadOnly setting in VolumeMounts. - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md optional bool readOnly = 3; } @@ -184,7 +193,7 @@ message ComponentCondition { // ComponentStatus (and ComponentStatusList) holds the cluster validation info. message ComponentStatus { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // List of component conditions observed @@ -194,7 +203,7 @@ message ComponentStatus { // Status of all the conditions for the component as a list of ComponentStatus objects. message ComponentStatusList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of ComponentStatus objects. @@ -204,7 +213,7 @@ message ComponentStatusList { // ConfigMap holds configuration data for pods to consume. message ConfigMap { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Data contains the configuration data. @@ -223,7 +232,7 @@ message ConfigMapKeySelector { // ConfigMapList is a resource containing a list of ConfigMap objects. message ConfigMapList { - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of ConfigMaps. @@ -257,7 +266,7 @@ message Container { optional string name = 1; // Docker image name. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md optional string image = 2; // Entrypoint array. Not executed within a shell. @@ -267,7 +276,7 @@ message Container { // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, // regardless of whether the variable exists or not. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands repeated string command = 3; // Arguments to the entrypoint. @@ -277,7 +286,7 @@ message Container { // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, // regardless of whether the variable exists or not. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands repeated string args = 4; // Container's working directory. @@ -301,7 +310,7 @@ message Container { // Compute Resources required by this container. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources optional ResourceRequirements resources = 8; // Pod volumes to mount into the container's filesystem. @@ -311,13 +320,13 @@ message Container { // Periodic probe of container liveness. // Container will be restarted if the probe fails. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes optional Probe livenessProbe = 10; // Periodic probe of container service readiness. // Container will be removed from service endpoints if the probe fails. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes optional Probe readinessProbe = 11; // Actions that the management system should take in response to container lifecycle events. @@ -335,11 +344,11 @@ message Container { // One of Always, Never, IfNotPresent. // Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#updating-images + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#updating-images optional string imagePullPolicy = 14; // Security options the pod should run with. - // More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md + // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md optional SecurityContext securityContext = 15; // Whether this container should allocate a buffer for stdin in the container runtime. If this @@ -471,7 +480,7 @@ message ContainerStatus { optional int32 restartCount = 5; // The image the container is running. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md // TODO(dchen1107): Which image the container is running with? optional string image = 6; @@ -479,7 +488,7 @@ message ContainerStatus { optional string imageID = 7; // Container's ID in the format 'docker://'. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#container-information + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#container-information optional string containerID = 8; } @@ -532,7 +541,7 @@ message EmptyDirVolumeSource { // What type of storage medium should back this directory. // The default is "" which means to use the node's default medium. // Must be an empty string (default) or Memory. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir optional string medium = 1; } @@ -607,7 +616,7 @@ message EndpointSubset { // ] message Endpoints { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // The set of all endpoints is the union of all subsets. Addresses are placed into @@ -623,7 +632,7 @@ message Endpoints { // EndpointsList is a list of endpoints. message EndpointsList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of endpoints. @@ -669,7 +678,7 @@ message EnvVarSource { // TODO: Decide whether to store these separately or with the object they apply to. message Event { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // The object that this event is about. @@ -703,7 +712,7 @@ message Event { // EventList is a list of events. message EventList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of events @@ -800,13 +809,13 @@ message FlockerVolumeSource { // PDs support ownership management and SELinux relabeling. message GCEPersistentDiskVolumeSource { // Unique name of the PD resource in GCE. Used to identify the disk in GCE. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk optional string pdName = 1; // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk // TODO: how do we prevent errors in the filesystem from compromising the machine optional string fsType = 2; @@ -814,12 +823,12 @@ message GCEPersistentDiskVolumeSource { // If omitted, the default is to mount by volume name. // Examples: For volume /dev/sda1, you specify the partition as "1". // Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk optional int32 partition = 3; // ReadOnly here will force the ReadOnly setting in VolumeMounts. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk optional bool readOnly = 4; } @@ -844,16 +853,16 @@ message GitRepoVolumeSource { // Glusterfs volumes do not support ownership management or SELinux relabeling. message GlusterfsVolumeSource { // EndpointsName is the endpoint name that details Glusterfs topology. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod optional string endpoints = 1; // Path is the Glusterfs volume path. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod optional string path = 2; // ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod optional bool readOnly = 3; } @@ -908,7 +917,7 @@ message Handler { // Host path volumes do not support ownership management or SELinux relabeling. message HostPathVolumeSource { // Path of the directory on the host. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath optional string path = 1; } @@ -932,7 +941,7 @@ message ISCSIVolumeSource { // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#iscsi + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#iscsi // TODO: how do we prevent errors in the filesystem from compromising the machine optional string fsType = 5; @@ -960,7 +969,7 @@ message Lifecycle { // PostStart is called immediately after a container is created. If the handler fails, // the container is terminated and restarted according to its restart policy. // Other management of the container blocks until the hook completes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details optional Handler postStart = 1; // PreStop is called immediately before a container is terminated. @@ -968,18 +977,18 @@ message Lifecycle { // The reason for termination is passed to the handler. // Regardless of the outcome of the handler, the container is eventually terminated. // Other management of the container blocks until the hook completes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details optional Handler preStop = 2; } // LimitRange sets resource usage limits for each kind of resource in a Namespace. message LimitRange { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the limits enforced. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional LimitRangeSpec spec = 2; } @@ -1007,11 +1016,11 @@ message LimitRangeItem { // LimitRangeList is a list of LimitRange items. message LimitRangeList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of LimitRange objects. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_limit_range.md + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_limit_range.md repeated LimitRange items = 2; } @@ -1024,7 +1033,7 @@ message LimitRangeSpec { // List holds a list of objects, which may not be known by the server. message List { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of objects @@ -1076,7 +1085,7 @@ message LoadBalancerStatus { // referenced object inside the same namespace. message LocalObjectReference { // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names // TODO: Add other useful fields. apiVersion, kind, uid? optional string name = 1; } @@ -1085,17 +1094,17 @@ message LocalObjectReference { // NFS volumes do not support ownership management or SELinux relabeling. message NFSVolumeSource { // Server is the hostname or IP address of the NFS server. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs optional string server = 1; // Path that is exported by the NFS server. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs optional string path = 2; // ReadOnly here will force // the NFS export to be mounted with read-only permissions. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs optional bool readOnly = 3; } @@ -1103,40 +1112,40 @@ message NFSVolumeSource { // Use of multiple namespaces is optional. message Namespace { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the behavior of the Namespace. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional NamespaceSpec spec = 2; // Status describes the current status of a Namespace. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional NamespaceStatus status = 3; } // NamespaceList is a list of Namespaces. message NamespaceList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of Namespace objects in the list. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md repeated Namespace items = 2; } // NamespaceSpec describes the attributes on a Namespace. message NamespaceSpec { // Finalizers is an opaque list of values that must be empty to permanently remove object from storage. - // More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#finalizers + // More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#finalizers repeated string finalizers = 1; } // NamespaceStatus is information about the current status of a Namespace. message NamespaceStatus { // Phase is the current lifecycle phase of the namespace. - // More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#phases + // More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#phases optional string phase = 1; } @@ -1144,17 +1153,17 @@ message NamespaceStatus { // Each node will have a unique identifier in the cache (i.e. in etcd). message Node { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the behavior of a node. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional NodeSpec spec = 2; // Most recently observed status of the node. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional NodeStatus status = 3; } @@ -1218,7 +1227,7 @@ message NodeDaemonEndpoints { // NodeList is the whole list of all Nodes which have been registered with master. message NodeList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of nodes @@ -1276,14 +1285,14 @@ message NodeSpec { optional string providerID = 3; // Unschedulable controls node schedulability of new pods. By default, node is schedulable. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#manual-node-administration"` + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#manual-node-administration"` optional bool unschedulable = 4; } // NodeStatus is information about the current status of a node. message NodeStatus { // Capacity represents the total resources of a node. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity for more details. + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity for more details. map capacity = 1; // Allocatable represents the resources of a node that are available for scheduling. @@ -1291,23 +1300,23 @@ message NodeStatus { map allocatable = 2; // NodePhase is the recently observed lifecycle phase of the node. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-phase + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase optional string phase = 3; // Conditions is an array of current observed node conditions. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-condition + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition repeated NodeCondition conditions = 4; // List of addresses reachable to the node. // Queried from cloud provider, if available. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-addresses + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses repeated NodeAddress addresses = 5; // Endpoints of daemons running on the Node. optional NodeDaemonEndpoints daemonEndpoints = 6; // Set of ids/uuids to uniquely identify the node. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-info + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info optional NodeSystemInfo nodeInfo = 7; // List of container images on this node @@ -1370,7 +1379,7 @@ message ObjectMeta { // automatically. Name is primarily intended for creation idempotence and configuration // definition. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 1; // GenerateName is an optional prefix, used by the server, to generate a unique @@ -1387,7 +1396,7 @@ message ObjectMeta { // should retry (optionally after the time indicated in the Retry-After header). // // Applied only if Name is not specified. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#idempotency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency optional string generateName = 2; // Namespace defines the space within each name must be unique. An empty namespace is @@ -1397,7 +1406,7 @@ message ObjectMeta { // // Must be a DNS_LABEL. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md optional string namespace = 3; // SelfLink is a URL representing this object. @@ -1411,7 +1420,7 @@ message ObjectMeta { // // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids optional string uid = 5; // An opaque value that represents the internal version of this object that can @@ -1423,7 +1432,7 @@ message ObjectMeta { // Populated by the system. // Read-only. // Value must be treated as opaque by clients and . - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency optional string resourceVersion = 6; // A sequence number representing a specific generation of the desired state. @@ -1437,7 +1446,7 @@ message ObjectMeta { // Populated by the system. // Read-only. // Null for lists. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.Time creationTimestamp = 8; // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This @@ -1453,7 +1462,7 @@ message ObjectMeta { // // Populated by the system when a graceful deletion is requested. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.Time deletionTimestamp = 9; // Number of seconds allowed for this object to gracefully terminate before @@ -1465,14 +1474,14 @@ message ObjectMeta { // Map of string keys and values that can be used to organize and categorize // (scope and select) objects. May match selectors of replication controllers // and services. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md // TODO: replace map[string]string with labels.LabelSet type map labels = 11; // Annotations is an unstructured key value map stored with a resource that may be // set by external tools to store and retrieve arbitrary metadata. They are not // queryable and should be preserved when modifying objects. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/annotations.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/annotations.md map annotations = 12; // List of objects depended by this object. If ALL objects in the list have @@ -1491,26 +1500,26 @@ message ObjectMeta { // ObjectReference contains enough information to let you inspect or modify the referred object. message ObjectReference { // Kind of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional string kind = 1; // Namespace of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md optional string namespace = 2; // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 3; // UID of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids optional string uid = 4; // API version of the referent. optional string apiVersion = 5; // Specific resourceVersion to which this reference is made, if any. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency optional string resourceVersion = 6; // If referring to a piece of an object instead of an entire object, this string @@ -1532,15 +1541,15 @@ message OwnerReference { optional string apiVersion = 5; // Kind of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional string kind = 1; // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 3; // UID of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids optional string uid = 4; // If true, this reference points to the managing controller. @@ -1549,48 +1558,48 @@ message OwnerReference { // PersistentVolume (PV) is a storage resource provisioned by an administrator. // It is analogous to a node. -// More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md +// More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md message PersistentVolume { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines a specification of a persistent volume owned by the cluster. // Provisioned by an administrator. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes optional PersistentVolumeSpec spec = 2; // Status represents the current information/status for the persistent volume. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes optional PersistentVolumeStatus status = 3; } // PersistentVolumeClaim is a user's request for and claim to a persistent volume message PersistentVolumeClaim { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the desired characteristics of a volume requested by a pod author. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims optional PersistentVolumeClaimSpec spec = 2; // Status represents the current information/status of a persistent volume claim. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims optional PersistentVolumeClaimStatus status = 3; } // PersistentVolumeClaimList is a list of PersistentVolumeClaim items. message PersistentVolumeClaimList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // A list of persistent volume claims. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims repeated PersistentVolumeClaim items = 2; } @@ -1598,14 +1607,14 @@ message PersistentVolumeClaimList { // and allows a Source for provider-specific attributes message PersistentVolumeClaimSpec { // AccessModes contains the desired access modes the volume should have. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1 + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1 repeated string accessModes = 1; // A label query over volumes to consider for binding. optional k8s.io.kubernetes.pkg.api.unversioned.LabelSelector selector = 4; // Resources represents the minimum resources the volume should have. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources optional ResourceRequirements resources = 2; // VolumeName is the binding reference to the PersistentVolume backing this claim. @@ -1618,7 +1627,7 @@ message PersistentVolumeClaimStatus { optional string phase = 1; // AccessModes contains the actual access modes the volume backing the PVC has. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1 + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1 repeated string accessModes = 2; // Represents the actual resources of the underlying volume. @@ -1631,7 +1640,7 @@ message PersistentVolumeClaimStatus { // type of volume that is owned by someone else (the system). message PersistentVolumeClaimVolumeSource { // ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims optional string claimName = 1; // Will force the ReadOnly setting in VolumeMounts. @@ -1642,11 +1651,11 @@ message PersistentVolumeClaimVolumeSource { // PersistentVolumeList is a list of PersistentVolume items. message PersistentVolumeList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of persistent volumes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md repeated PersistentVolume items = 2; } @@ -1655,32 +1664,32 @@ message PersistentVolumeList { message PersistentVolumeSource { // GCEPersistentDisk represents a GCE Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk optional GCEPersistentDiskVolumeSource gcePersistentDisk = 1; // AWSElasticBlockStore represents an AWS Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore optional AWSElasticBlockStoreVolumeSource awsElasticBlockStore = 2; // HostPath represents a directory on the host. // Provisioned by a developer or tester. // This is useful for single-node development and testing only! // On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath optional HostPathVolumeSource hostPath = 3; // Glusterfs represents a Glusterfs volume that is attached to a host and // exposed to the pod. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md optional GlusterfsVolumeSource glusterfs = 4; // NFS represents an NFS mount on the host. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs optional NFSVolumeSource nfs = 5; // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md optional RBDVolumeSource rbd = 6; // ISCSI represents an ISCSI Disk resource that is attached to a @@ -1688,7 +1697,7 @@ message PersistentVolumeSource { optional ISCSIVolumeSource iscsi = 7; // Cinder represents a cinder volume attached and mounted on kubelets host machine - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md optional CinderVolumeSource cinder = 8; // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime @@ -1715,33 +1724,33 @@ message PersistentVolumeSource { // PersistentVolumeSpec is the specification of a persistent volume. message PersistentVolumeSpec { // A description of the persistent volume's resources and capacity. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity map capacity = 1; // The actual volume backing the persistent volume. optional PersistentVolumeSource persistentVolumeSource = 2; // AccessModes contains all ways the volume can be mounted. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes repeated string accessModes = 3; // ClaimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. // Expected to be non-nil when bound. // claim.VolumeName is the authoritative bind between PV and PVC. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#binding + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#binding optional ObjectReference claimRef = 4; // What happens to a persistent volume when released from its claim. // Valid options are Retain (default) and Recycle. // Recyling must be supported by the volume plugin underlying this persistent volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#recycling-policy + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#recycling-policy optional string persistentVolumeReclaimPolicy = 5; } // PersistentVolumeStatus is the current status of a persistent volume. message PersistentVolumeStatus { // Phase indicates if a volume is available, bound to a claim, or released by a claim. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#phase + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#phase optional string phase = 1; // A human-readable message indicating details about why the volume is in this state. @@ -1756,18 +1765,18 @@ message PersistentVolumeStatus { // by clients and scheduled onto hosts. message Pod { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional PodSpec spec = 2; // Most recently observed status of the pod. // This data may not be up to date. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional PodStatus status = 3; } @@ -1893,12 +1902,12 @@ message PodAttachOptions { message PodCondition { // Type is the type of the condition. // Currently only Ready. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions optional string type = 1; // Status is the status of the condition. // Can be True, False, Unknown. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions optional string status = 2; // Last time we probed the condition. @@ -1946,11 +1955,11 @@ message PodExecOptions { // PodList is a list of Pods. message PodList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of pods. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pods.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pods.md repeated Pod items = 2; } @@ -2040,23 +2049,30 @@ message PodSecurityContext { optional int64 fsGroup = 5; } +// Describes the class of pods that should avoid this node. +// Exactly one field should be set. +message PodSignature { + // Reference to controller whose pods should avoid this node. + optional OwnerReference podController = 1; +} + // PodSpec is a description of a pod. message PodSpec { // List of volumes that can be mounted by containers belonging to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md repeated Volume volumes = 1; // List of containers belonging to the pod. // Containers cannot currently be added or removed. // There must be at least one container in a Pod. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md repeated Container containers = 2; // Restart policy for all containers within the pod. // One of Always, OnFailure, Never. // Default to Always. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#restartpolicy + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#restartpolicy optional string restartPolicy = 3; // Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. @@ -2080,15 +2096,16 @@ message PodSpec { // NodeSelector is a selector which must be true for the pod to fit on a node. // Selector which must match a node's labels for the pod to be scheduled on that node. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/node-selection/README.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/node-selection/README.md map nodeSelector = 7; // ServiceAccountName is the name of the ServiceAccount to use to run this pod. - // More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md + // More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md optional string serviceAccountName = 8; // DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. // Deprecated: Use serviceAccountName instead. + // +k8s:conversion-gen=false optional string serviceAccount = 9; // NodeName is a request to schedule this pod onto a specific node. If it is non-empty, @@ -2099,14 +2116,17 @@ message PodSpec { // Host networking requested for this pod. Use the host's network namespace. // If this option is set, the ports that will be used must be specified. // Default to false. + // +k8s:conversion-gen=false optional bool hostNetwork = 11; // Use the host's pid namespace. // Optional: Default to false. + // +k8s:conversion-gen=false optional bool hostPID = 12; // Use the host's ipc namespace. // Optional: Default to false. + // +k8s:conversion-gen=false optional bool hostIPC = 13; // SecurityContext holds pod-level security attributes and common container settings. @@ -2116,7 +2136,7 @@ message PodSpec { // ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. // If specified, these secrets will be passed to individual puller implementations for them to use. For example, // in the case of docker, only DockerConfig type secrets are honored. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod repeated LocalObjectReference imagePullSecrets = 15; // Specifies the hostname of the Pod @@ -2132,11 +2152,11 @@ message PodSpec { // state of a system. message PodStatus { // Current condition of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-phase + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-phase optional string phase = 1; // Current service state of pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions repeated PodCondition conditions = 2; // A human readable message indicating details about why the pod is in this condition. @@ -2159,39 +2179,39 @@ message PodStatus { // The list has one entry per container in the manifest. Each entry is currently the output // of `docker inspect`. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-statuses + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-statuses repeated ContainerStatus containerStatuses = 8; } // PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded message PodStatusResult { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Most recently observed status of the pod. // This data may not be up to date. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional PodStatus status = 2; } // PodTemplate describes a template for creating copies of a predefined pod. message PodTemplate { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Template defines the pods that will be created from this pod template. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional PodTemplateSpec template = 2; } // PodTemplateList is a list of PodTemplates. message PodTemplateList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of pod templates @@ -2201,11 +2221,11 @@ message PodTemplateList { // PodTemplateSpec describes the data a pod should have when created from a template message PodTemplateSpec { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional PodSpec spec = 2; } @@ -2215,6 +2235,21 @@ message Preconditions { optional string uid = 1; } +// Describes a class of pods that should avoid this node. +message PreferAvoidPodsEntry { + // The class of pods. + optional PodSignature podSignature = 1; + + // Time at which this entry was added to the list. + optional k8s.io.kubernetes.pkg.api.unversioned.Time evictionTime = 2; + + // (brief) reason why this entry was added to the list. + optional string reason = 3; + + // Human readable message indicating why this entry was added to the list. + optional string message = 4; +} + // An empty preferred scheduling term matches all objects with implicit weight 0 // (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). message PreferredSchedulingTerm { @@ -2232,12 +2267,12 @@ message Probe { optional Handler handler = 1; // Number of seconds after the container has started before liveness probes are initiated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes optional int32 initialDelaySeconds = 2; // Number of seconds after which the probe times out. // Defaults to 1 second. Minimum value is 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes optional int32 timeoutSeconds = 3; // How often (in seconds) to perform the probe. @@ -2257,51 +2292,51 @@ message Probe { // RBD volumes support ownership management and SELinux relabeling. message RBDVolumeSource { // A collection of Ceph monitors. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it repeated string monitors = 1; // The rados image name. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it optional string image = 2; // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#rbd + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#rbd // TODO: how do we prevent errors in the filesystem from compromising the machine optional string fsType = 3; // The rados pool name. // Default is rbd. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it. + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it. optional string pool = 4; // The rados user name. // Default is admin. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it optional string user = 5; // Keyring is the path to key ring for RBDUser. // Default is /etc/ceph/keyring. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it optional string keyring = 6; // SecretRef is name of the authentication secret for RBDUser. If provided // overrides keyring. // Default is nil. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it optional LocalObjectReference secretRef = 7; // ReadOnly here will force the ReadOnly setting in VolumeMounts. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it optional bool readOnly = 8; } // RangeAllocation is not a public type. message RangeAllocation { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Range is string that identifies the range represented by 'data'. @@ -2315,29 +2350,29 @@ message RangeAllocation { message ReplicationController { // If the Labels of a ReplicationController are empty, they are defaulted to // be the same as the Pod(s) that the replication controller manages. - // Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the specification of the desired behavior of the replication controller. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ReplicationControllerSpec spec = 2; // Status is the most recently observed status of the replication controller. // This data may be out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ReplicationControllerStatus status = 3; } // ReplicationControllerList is a collection of replication controllers. message ReplicationControllerList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of replication controllers. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md repeated ReplicationController items = 2; } @@ -2346,19 +2381,19 @@ message ReplicationControllerSpec { // Replicas is the number of desired replicas. // This is a pointer to distinguish between explicit zero and unspecified. // Defaults to 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller optional int32 replicas = 1; // Selector is a label query over pods that should match the Replicas count. // If Selector is empty, it is defaulted to the labels present on the Pod template. // Label keys and values that must match in order to be controlled by this replication // controller, if empty defaulted to labels on Pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors map selector = 2; // Template is the object that describes the pod that will be created if // insufficient replicas are detected. This takes precedence over a TemplateRef. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template optional PodTemplateSpec template = 3; } @@ -2366,7 +2401,7 @@ message ReplicationControllerSpec { // controller. message ReplicationControllerStatus { // Replicas is the most recently oberved number of replicas. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller optional int32 replicas = 1; // The number of pods that have labels matching the labels of the pod template of the replication controller. @@ -2391,33 +2426,33 @@ message ResourceFieldSelector { // ResourceQuota sets aggregate quota restrictions enforced per namespace message ResourceQuota { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the desired quota. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ResourceQuotaSpec spec = 2; // Status defines the actual enforced quota and its current usage. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ResourceQuotaStatus status = 3; } // ResourceQuotaList is a list of ResourceQuota items. message ResourceQuotaList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of ResourceQuota objects. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota repeated ResourceQuota items = 2; } // ResourceQuotaSpec defines the desired hard limits to enforce for Quota. message ResourceQuotaSpec { // Hard is the set of desired hard limits for each named resource. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota map hard = 1; // A collection of filters that must match each object tracked by a quota. @@ -2428,7 +2463,7 @@ message ResourceQuotaSpec { // ResourceQuotaStatus defines the enforced hard limits and observed use. message ResourceQuotaStatus { // Hard is the set of enforced hard limits for each named resource. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota map hard = 1; // Used is the current observed total usage of the resource in the namespace. @@ -2438,13 +2473,13 @@ message ResourceQuotaStatus { // ResourceRequirements describes the compute resource requirements. message ResourceRequirements { // Limits describes the maximum amount of compute resources allowed. - // More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications + // More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications map limits = 1; // Requests describes the minimum amount of compute resources required. // If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, // otherwise to an implementation-defined value. - // More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications + // More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications map requests = 2; } @@ -2467,7 +2502,7 @@ message SELinuxOptions { // the Data field must be less than MaxSecretSize bytes. message Secret { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Data contains the secret data. Each key must be a valid DNS_SUBDOMAIN @@ -2477,6 +2512,13 @@ message Secret { // Described in https://tools.ietf.org/html/rfc4648#section-4 map data = 2; + // stringData allows specifying non-binary secret data in string form. + // It is provided as a write-only convenience method. + // All keys and values are merged into the data field on write, overwriting any existing values. + // It is never output when reading from the API. + // +k8s:conversion-gen=false + map stringData = 4; + // Used to facilitate programmatic handling of secret data. optional string type = 3; } @@ -2493,11 +2535,11 @@ message SecretKeySelector { // SecretList is a list of Secret. message SecretList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of secret objects. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md repeated Secret items = 2; } @@ -2508,7 +2550,7 @@ message SecretList { // Secret volumes support ownership management and SELinux relabeling. message SecretVolumeSource { // Name of the secret in the pod's namespace to use. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets optional string secretName = 1; // If unspecified, each key-value pair in the Data field of the referenced @@ -2570,17 +2612,17 @@ message SerializedReference { // will answer requests sent through the proxy. message Service { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Spec defines the behavior of a service. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ServiceSpec spec = 2; // Most recently observed status of the service. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ServiceStatus status = 3; } @@ -2590,35 +2632,35 @@ message Service { // * a set of secrets message ServiceAccount { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional ObjectMeta metadata = 1; // Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md repeated ObjectReference secrets = 2; // ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images // in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets // can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret repeated LocalObjectReference imagePullSecrets = 3; } // ServiceAccountList is a list of ServiceAccount objects message ServiceAccountList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of ServiceAccounts. - // More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md#service-accounts + // More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md#service-accounts repeated ServiceAccount items = 2; } // ServiceList holds a list of services. message ServiceList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of services @@ -2647,14 +2689,14 @@ message ServicePort { // of the 'port' field is used (an identity map). // This field is ignored for services with clusterIP=None, and should be // omitted or set equal to the 'port' field. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#defining-a-service + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service optional k8s.io.kubernetes.pkg.util.intstr.IntOrString targetPort = 4; // The port on each node on which this service is exposed when type=NodePort or LoadBalancer. // Usually assigned by the system. If specified, it will be allocated to the service // if unused or else creation of the service will fail. // Default is to auto-allocate a port if the ServiceType of this Service requires one. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#type--nodeport + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#type--nodeport optional int32 nodePort = 5; } @@ -2671,13 +2713,13 @@ message ServiceProxyOptions { // ServiceSpec describes the attributes that a user creates on a service. message ServiceSpec { // The list of ports that are exposed by this service. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies repeated ServicePort ports = 1; // This service will route traffic to pods having labels matching this selector. // Label keys and values that must match in order to receive traffic for this service. - // If empty, all pods are selected, if not specified, endpoints must be manually specified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#overview + // If not specified, endpoints must be manually specified and the system will not automatically manage them. + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#overview map selector = 2; // ClusterIP is usually assigned by the master and is the IP address of the service. @@ -2686,12 +2728,12 @@ message ServiceSpec { // Valid values are None, empty string (""), or a valid IP address. // 'None' can be specified for a headless service when proxying is not required. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies optional string clusterIP = 3; // Type of exposed service. Must be ClusterIP, NodePort, or LoadBalancer. // Defaults to ClusterIP. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#external-services + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#external-services optional string type = 4; // externalIPs is a list of IP addresses for which nodes in the cluster @@ -2708,14 +2750,14 @@ message ServiceSpec { // API for compatibility until at least 8/20/2016. It will be removed from // any new API revisions. If both deprecatedPublicIPs *and* externalIPs are // set, deprecatedPublicIPs is used. - // +genconversion=false + // +k8s:conversion-gen=false repeated string deprecatedPublicIPs = 6; // Supports "ClientIP" and "None". Used to maintain session affinity. // Enable client IP based session affinity. // Must be ClientIP or None. // Defaults to None. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies optional string sessionAffinity = 7; // Only applies to Service Type: LoadBalancer @@ -2728,7 +2770,7 @@ message ServiceSpec { // If specified and supported by the platform, this will restrict traffic through the cloud-provider // load-balancer will be restricted to the specified client IPs. This field will be ignored if the // cloud-provider does not support the feature." - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services-firewalls.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services-firewalls.md repeated string loadBalancerSourceRanges = 9; } @@ -2787,7 +2829,7 @@ message Toleration { message Volume { // Volume's name. // Must be a DNS_LABEL and unique within the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 1; // VolumeSource represents the location and type of the mounted volume. @@ -2821,53 +2863,53 @@ message VolumeSource { // machine that is directly exposed to the container. This is generally // used for system agents or other privileged things that are allowed // to see the host machine. Most containers will NOT need this. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath // --- // TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not // mount host directories as read/write. optional HostPathVolumeSource hostPath = 1; // EmptyDir represents a temporary directory that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir optional EmptyDirVolumeSource emptyDir = 2; // GCEPersistentDisk represents a GCE Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk optional GCEPersistentDiskVolumeSource gcePersistentDisk = 3; // AWSElasticBlockStore represents an AWS Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore optional AWSElasticBlockStoreVolumeSource awsElasticBlockStore = 4; // GitRepo represents a git repository at a particular revision. optional GitRepoVolumeSource gitRepo = 5; // Secret represents a secret that should populate this volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets optional SecretVolumeSource secret = 6; // NFS represents an NFS mount on the host that shares a pod's lifetime - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs optional NFSVolumeSource nfs = 7; // ISCSI represents an ISCSI Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/examples/iscsi/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/iscsi/README.md optional ISCSIVolumeSource iscsi = 8; // Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md optional GlusterfsVolumeSource glusterfs = 9; // PersistentVolumeClaimVolumeSource represents a reference to a // PersistentVolumeClaim in the same namespace. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims optional PersistentVolumeClaimVolumeSource persistentVolumeClaim = 10; // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md optional RBDVolumeSource rbd = 11; // FlexVolume represents a generic volume resource that is @@ -2876,7 +2918,7 @@ message VolumeSource { optional FlexVolumeSource flexVolume = 12; // Cinder represents a cinder volume attached and mounted on kubelets host machine - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md optional CinderVolumeSource cinder = 13; // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/meta.go b/vendor/k8s.io/kubernetes/pkg/api/v1/meta.go index 935bd973b702..d5ba042a2009 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/meta.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/meta.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/register.go b/vendor/k8s.io/kubernetes/pkg/api/v1/register.go index bf07189ee47d..8c625b878059 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/api/v1/types.generated.go index 1b6c236dbe9a..9891e9eb25b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37214,6 +37214,706 @@ func (x *AttachedVolume) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x *AvoidPods) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = len(x.PreferAvoidPods) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.PreferAvoidPods == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSlicePreferAvoidPodsEntry(([]PreferAvoidPodsEntry)(x.PreferAvoidPods), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("preferAvoidPods")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.PreferAvoidPods == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSlicePreferAvoidPodsEntry(([]PreferAvoidPodsEntry)(x.PreferAvoidPods), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *AvoidPods) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *AvoidPods) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "preferAvoidPods": + if r.TryDecodeAsNil() { + x.PreferAvoidPods = nil + } else { + yyv4 := &x.PreferAvoidPods + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSlicePreferAvoidPodsEntry((*[]PreferAvoidPodsEntry)(yyv4), d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *AvoidPods) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj6 int + var yyb6 bool + var yyhl6 bool = l >= 0 + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PreferAvoidPods = nil + } else { + yyv7 := &x.PreferAvoidPods + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + h.decSlicePreferAvoidPodsEntry((*[]PreferAvoidPodsEntry)(yyv7), d) + } + } + for { + yyj6++ + if yyhl6 { + yyb6 = yyj6 > l + } else { + yyb6 = r.CheckBreak() + } + if yyb6 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj6-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *PreferAvoidPodsEntry) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = true + yyq2[2] = x.Reason != "" + yyq2[3] = x.Message != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy4 := &x.PodSignature + yy4.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("podSignature")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.PodSignature + yy6.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yy9 := &x.EvictionTime + yym10 := z.EncBinary() + _ = yym10 + if false { + } else if z.HasExtensions() && z.EncExt(yy9) { + } else if yym10 { + z.EncBinaryMarshal(yy9) + } else if !yym10 && z.IsJSONHandle() { + z.EncJSONMarshal(yy9) + } else { + z.EncFallback(yy9) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("evictionTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy11 := &x.EvictionTime + yym12 := z.EncBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.EncExt(yy11) { + } else if yym12 { + z.EncBinaryMarshal(yy11) + } else if !yym12 && z.IsJSONHandle() { + z.EncJSONMarshal(yy11) + } else { + z.EncFallback(yy11) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("reason")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym17 := z.EncBinary() + _ = yym17 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("message")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym18 := z.EncBinary() + _ = yym18 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *PreferAvoidPodsEntry) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *PreferAvoidPodsEntry) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "podSignature": + if r.TryDecodeAsNil() { + x.PodSignature = PodSignature{} + } else { + yyv4 := &x.PodSignature + yyv4.CodecDecodeSelf(d) + } + case "evictionTime": + if r.TryDecodeAsNil() { + x.EvictionTime = pkg2_unversioned.Time{} + } else { + yyv5 := &x.EvictionTime + yym6 := z.DecBinary() + _ = yym6 + if false { + } else if z.HasExtensions() && z.DecExt(yyv5) { + } else if yym6 { + z.DecBinaryUnmarshal(yyv5) + } else if !yym6 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv5) + } else { + z.DecFallback(yyv5, false) + } + } + case "reason": + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + case "message": + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *PreferAvoidPodsEntry) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.PodSignature = PodSignature{} + } else { + yyv10 := &x.PodSignature + yyv10.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.EvictionTime = pkg2_unversioned.Time{} + } else { + yyv11 := &x.EvictionTime + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else if yym12 { + z.DecBinaryUnmarshal(yyv11) + } else if !yym12 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv11) + } else { + z.DecFallback(yyv11, false) + } + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *PodSignature) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [1]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = x.PodController != nil + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(1) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.PodController == nil { + r.EncodeNil() + } else { + x.PodController.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("podController")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.PodController == nil { + r.EncodeNil() + } else { + x.PodController.CodecEncodeSelf(e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *PodSignature) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *PodSignature) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "podController": + if r.TryDecodeAsNil() { + if x.PodController != nil { + x.PodController = nil + } + } else { + if x.PodController == nil { + x.PodController = new(OwnerReference) + } + x.PodController.CodecDecodeSelf(d) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *PodSignature) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj5 int + var yyb5 bool + var yyhl5 bool = l >= 0 + yyj5++ + if yyhl5 { + yyb5 = yyj5 > l + } else { + yyb5 = r.CheckBreak() + } + if yyb5 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + if x.PodController != nil { + x.PodController = nil + } + } else { + if x.PodController == nil { + x.PodController = new(OwnerReference) + } + x.PodController.CodecDecodeSelf(d) + } + for { + yyj5++ + if yyhl5 { + yyb5 = yyj5 > l + } else { + yyb5 = r.CheckBreak() + } + if yyb5 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj5-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + func (x *ContainerImage) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -49484,17 +50184,18 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [5]bool + var yyq2 [6]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = true yyq2[1] = len(x.Data) != 0 - yyq2[2] = x.Type != "" - yyq2[3] = x.Kind != "" - yyq2[4] = x.APIVersion != "" + yyq2[2] = len(x.StringData) != 0 + yyq2[3] = x.Type != "" + yyq2[4] = x.Kind != "" + yyq2[5] = x.APIVersion != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(5) + r.EncodeArrayStart(6) } else { yynn2 = 0 for _, b := range yyq2 { @@ -49558,12 +50259,45 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { + if x.StringData == nil { + r.EncodeNil() + } else { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + z.F.EncMapStringStringV(x.StringData, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("stringData")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.StringData == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + z.F.EncMapStringStringV(x.StringData, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { x.Type.CodecEncodeSelf(e) } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[2] { + if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("type")) z.EncSendContainerState(codecSelfer_containerMapValue1234) @@ -49572,9 +50306,9 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[3] { - yym15 := z.EncBinary() - _ = yym15 + if yyq2[4] { + yym18 := z.EncBinary() + _ = yym18 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -49583,12 +50317,12 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[3] { + if yyq2[4] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym16 := z.EncBinary() - _ = yym16 + yym19 := z.EncBinary() + _ = yym19 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -49597,9 +50331,9 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[4] { - yym18 := z.EncBinary() - _ = yym18 + if yyq2[5] { + yym21 := z.EncBinary() + _ = yym21 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -49608,12 +50342,12 @@ func (x *Secret) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[4] { + if yyq2[5] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym19 := z.EncBinary() - _ = yym19 + yym22 := z.EncBinary() + _ = yym22 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -49700,6 +50434,18 @@ func (x *Secret) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { h.decMapstringSliceuint8((*map[string][]uint8)(yyv5), d) } } + case "stringData": + if r.TryDecodeAsNil() { + x.StringData = nil + } else { + yyv7 := &x.StringData + yym8 := z.DecBinary() + _ = yym8 + if false { + } else { + z.F.DecMapStringStringX(yyv7, false, d) + } + } case "type": if r.TryDecodeAsNil() { x.Type = "" @@ -49729,16 +50475,16 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj10 int - var yyb10 bool - var yyhl10 bool = l >= 0 - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + var yyj12 int + var yyb12 bool + var yyhl12 bool = l >= 0 + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -49746,16 +50492,16 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.ObjectMeta = ObjectMeta{} } else { - yyv11 := &x.ObjectMeta - yyv11.CodecDecodeSelf(d) + yyv13 := &x.ObjectMeta + yyv13.CodecDecodeSelf(d) } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -49763,21 +50509,43 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { if r.TryDecodeAsNil() { x.Data = nil } else { - yyv12 := &x.Data - yym13 := z.DecBinary() - _ = yym13 + yyv14 := &x.Data + yym15 := z.DecBinary() + _ = yym15 if false { } else { - h.decMapstringSliceuint8((*map[string][]uint8)(yyv12), d) + h.decMapstringSliceuint8((*map[string][]uint8)(yyv14), d) } } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.StringData = nil + } else { + yyv16 := &x.StringData + yym17 := z.DecBinary() + _ = yym17 + if false { + } else { + z.F.DecMapStringStringX(yyv16, false, d) + } + } + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l + } else { + yyb12 = r.CheckBreak() + } + if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -49787,13 +50555,13 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } else { x.Type = SecretType(r.DecodeString()) } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -49803,13 +50571,13 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { } else { x.Kind = string(r.DecodeString()) } - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -49820,17 +50588,17 @@ func (x *Secret) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { x.APIVersion = string(r.DecodeString()) } for { - yyj10++ - if yyhl10 { - yyb10 = yyj10 > l + yyj12++ + if yyhl12 { + yyb12 = yyj12 > l } else { - yyb10 = r.CheckBreak() + yyb12 = r.CheckBreak() } - if yyb10 { + if yyb12 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj10-1, "") + z.DecStructFieldNotFound(yyj12-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -57910,6 +58678,125 @@ func (x codecSelfer1234) decSliceAttachedVolume(v *[]AttachedVolume, d *codec197 } } +func (x codecSelfer1234) encSlicePreferAvoidPodsEntry(v []PreferAvoidPodsEntry, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSlicePreferAvoidPodsEntry(v *[]PreferAvoidPodsEntry, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []PreferAvoidPodsEntry{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 64) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]PreferAvoidPodsEntry, yyrl1) + } + } else { + yyv1 = make([]PreferAvoidPodsEntry, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, PreferAvoidPodsEntry{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, PreferAvoidPodsEntry{}) // var yyz1 PreferAvoidPodsEntry + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = PreferAvoidPodsEntry{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []PreferAvoidPodsEntry{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + func (x codecSelfer1234) encResourceList(v ResourceList, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -59376,7 +60263,7 @@ func (x codecSelfer1234) decSliceSecret(v *[]Secret, d *codec1978.Decoder) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 - yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 264) + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 272) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/types.go b/vendor/k8s.io/kubernetes/pkg/api/v1/types.go index 34b9ac471ab5..42ef5808ae34 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import ( "k8s.io/kubernetes/pkg/util/intstr" ) -// The comments for the structs and fields can be used from go-resful to +// The comments for the structs and fields can be used from go-restful to // generate Swagger API documentation for its models. Please read this PR for more // information on the implementation: https://github.com/emicklei/go-restful/pull/215 // @@ -71,7 +71,7 @@ type ObjectMeta struct { // automatically. Name is primarily intended for creation idempotence and configuration // definition. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"` // GenerateName is an optional prefix, used by the server, to generate a unique @@ -88,7 +88,7 @@ type ObjectMeta struct { // should retry (optionally after the time indicated in the Retry-After header). // // Applied only if Name is not specified. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#idempotency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency GenerateName string `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"` // Namespace defines the space within each name must be unique. An empty namespace is @@ -98,7 +98,7 @@ type ObjectMeta struct { // // Must be a DNS_LABEL. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"` // SelfLink is a URL representing this object. @@ -112,7 +112,7 @@ type ObjectMeta struct { // // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids UID types.UID `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"` // An opaque value that represents the internal version of this object that can @@ -124,7 +124,7 @@ type ObjectMeta struct { // Populated by the system. // Read-only. // Value must be treated as opaque by clients and . - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"` // A sequence number representing a specific generation of the desired state. @@ -138,7 +138,7 @@ type ObjectMeta struct { // Populated by the system. // Read-only. // Null for lists. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata CreationTimestamp unversioned.Time `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"` // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This @@ -154,7 +154,7 @@ type ObjectMeta struct { // // Populated by the system when a graceful deletion is requested. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata DeletionTimestamp *unversioned.Time `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"` // Number of seconds allowed for this object to gracefully terminate before @@ -166,14 +166,14 @@ type ObjectMeta struct { // Map of string keys and values that can be used to organize and categorize // (scope and select) objects. May match selectors of replication controllers // and services. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md // TODO: replace map[string]string with labels.LabelSet type Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"` // Annotations is an unstructured key value map stored with a resource that may be // set by external tools to store and retrieve arbitrary metadata. They are not // queryable and should be preserved when modifying objects. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/annotations.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/annotations.md Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"` // List of objects depended by this object. If ALL objects in the list have @@ -200,7 +200,7 @@ const ( type Volume struct { // Volume's name. // Must be a DNS_LABEL and unique within the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // VolumeSource represents the location and type of the mounted volume. // If not specified, the Volume is implied to be an EmptyDir. @@ -215,50 +215,50 @@ type VolumeSource struct { // machine that is directly exposed to the container. This is generally // used for system agents or other privileged things that are allowed // to see the host machine. Most containers will NOT need this. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath // --- // TODO(jonesdl) We need to restrict who can use host directory mounts and who can/can not // mount host directories as read/write. HostPath *HostPathVolumeSource `json:"hostPath,omitempty" protobuf:"bytes,1,opt,name=hostPath"` // EmptyDir represents a temporary directory that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir EmptyDir *EmptyDirVolumeSource `json:"emptyDir,omitempty" protobuf:"bytes,2,opt,name=emptyDir"` // GCEPersistentDisk represents a GCE Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk GCEPersistentDisk *GCEPersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty" protobuf:"bytes,3,opt,name=gcePersistentDisk"` // AWSElasticBlockStore represents an AWS Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore AWSElasticBlockStore *AWSElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty" protobuf:"bytes,4,opt,name=awsElasticBlockStore"` // GitRepo represents a git repository at a particular revision. GitRepo *GitRepoVolumeSource `json:"gitRepo,omitempty" protobuf:"bytes,5,opt,name=gitRepo"` // Secret represents a secret that should populate this volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets Secret *SecretVolumeSource `json:"secret,omitempty" protobuf:"bytes,6,opt,name=secret"` // NFS represents an NFS mount on the host that shares a pod's lifetime - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs NFS *NFSVolumeSource `json:"nfs,omitempty" protobuf:"bytes,7,opt,name=nfs"` // ISCSI represents an ISCSI Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/examples/iscsi/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/iscsi/README.md ISCSI *ISCSIVolumeSource `json:"iscsi,omitempty" protobuf:"bytes,8,opt,name=iscsi"` // Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,9,opt,name=glusterfs"` // PersistentVolumeClaimVolumeSource represents a reference to a // PersistentVolumeClaim in the same namespace. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims PersistentVolumeClaim *PersistentVolumeClaimVolumeSource `json:"persistentVolumeClaim,omitempty" protobuf:"bytes,10,opt,name=persistentVolumeClaim"` // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md RBD *RBDVolumeSource `json:"rbd,omitempty" protobuf:"bytes,11,opt,name=rbd"` // FlexVolume represents a generic volume resource that is // provisioned/attached using a exec based plugin. This is an // alpha feature and may change in future. FlexVolume *FlexVolumeSource `json:"flexVolume,omitempty" protobuf:"bytes,12,opt,name=flexVolume"` // Cinder represents a cinder volume attached and mounted on kubelets host machine - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md Cinder *CinderVolumeSource `json:"cinder,omitempty" protobuf:"bytes,13,opt,name=cinder"` // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime @@ -285,7 +285,7 @@ type VolumeSource struct { // type of volume that is owned by someone else (the system). type PersistentVolumeClaimVolumeSource struct { // ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims ClaimName string `json:"claimName" protobuf:"bytes,1,opt,name=claimName"` // Will force the ReadOnly setting in VolumeMounts. // Default false. @@ -297,33 +297,33 @@ type PersistentVolumeClaimVolumeSource struct { type PersistentVolumeSource struct { // GCEPersistentDisk represents a GCE Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk GCEPersistentDisk *GCEPersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty" protobuf:"bytes,1,opt,name=gcePersistentDisk"` // AWSElasticBlockStore represents an AWS Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore AWSElasticBlockStore *AWSElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty" protobuf:"bytes,2,opt,name=awsElasticBlockStore"` // HostPath represents a directory on the host. // Provisioned by a developer or tester. // This is useful for single-node development and testing only! // On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath HostPath *HostPathVolumeSource `json:"hostPath,omitempty" protobuf:"bytes,3,opt,name=hostPath"` // Glusterfs represents a Glusterfs volume that is attached to a host and // exposed to the pod. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md Glusterfs *GlusterfsVolumeSource `json:"glusterfs,omitempty" protobuf:"bytes,4,opt,name=glusterfs"` // NFS represents an NFS mount on the host. Provisioned by an admin. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs NFS *NFSVolumeSource `json:"nfs,omitempty" protobuf:"bytes,5,opt,name=nfs"` // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md RBD *RBDVolumeSource `json:"rbd,omitempty" protobuf:"bytes,6,opt,name=rbd"` // ISCSI represents an ISCSI Disk resource that is attached to a // kubelet's host machine and then exposed to the pod. Provisioned by an admin. ISCSI *ISCSIVolumeSource `json:"iscsi,omitempty" protobuf:"bytes,7,opt,name=iscsi"` // Cinder represents a cinder volume attached and mounted on kubelets host machine - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md Cinder *CinderVolumeSource `json:"cinder,omitempty" protobuf:"bytes,8,opt,name=cinder"` // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime CephFS *CephFSVolumeSource `json:"cephfs,omitempty" protobuf:"bytes,9,opt,name=cephfs"` @@ -341,48 +341,49 @@ type PersistentVolumeSource struct { VsphereVolume *VsphereVirtualDiskVolumeSource `json:"vsphereVolume,omitempty" protobuf:"bytes,14,opt,name=vsphereVolume"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // PersistentVolume (PV) is a storage resource provisioned by an administrator. // It is analogous to a node. -// More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md +// More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md type PersistentVolume struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines a specification of a persistent volume owned by the cluster. // Provisioned by an administrator. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes Spec PersistentVolumeSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status represents the current information/status for the persistent volume. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes Status PersistentVolumeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // PersistentVolumeSpec is the specification of a persistent volume. type PersistentVolumeSpec struct { // A description of the persistent volume's resources and capacity. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity Capacity ResourceList `json:"capacity,omitempty" protobuf:"bytes,1,rep,name=capacity,casttype=ResourceList,castkey=ResourceName"` // The actual volume backing the persistent volume. PersistentVolumeSource `json:",inline" protobuf:"bytes,2,opt,name=persistentVolumeSource"` // AccessModes contains all ways the volume can be mounted. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty" protobuf:"bytes,3,rep,name=accessModes,casttype=PersistentVolumeAccessMode"` // ClaimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. // Expected to be non-nil when bound. // claim.VolumeName is the authoritative bind between PV and PVC. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#binding + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#binding ClaimRef *ObjectReference `json:"claimRef,omitempty" protobuf:"bytes,4,opt,name=claimRef"` // What happens to a persistent volume when released from its claim. // Valid options are Retain (default) and Recycle. // Recyling must be supported by the volume plugin underlying this persistent volume. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#recycling-policy + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#recycling-policy PersistentVolumeReclaimPolicy PersistentVolumeReclaimPolicy `json:"persistentVolumeReclaimPolicy,omitempty" protobuf:"bytes,5,opt,name=persistentVolumeReclaimPolicy,casttype=PersistentVolumeReclaimPolicy"` } @@ -404,7 +405,7 @@ const ( // PersistentVolumeStatus is the current status of a persistent volume. type PersistentVolumeStatus struct { // Phase indicates if a volume is available, bound to a claim, or released by a claim. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#phase + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#phase Phase PersistentVolumePhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=PersistentVolumePhase"` // A human-readable message indicating details about why the volume is in this state. Message string `json:"message,omitempty" protobuf:"bytes,2,opt,name=message"` @@ -417,10 +418,10 @@ type PersistentVolumeStatus struct { type PersistentVolumeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of persistent volumes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md Items []PersistentVolume `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -428,16 +429,16 @@ type PersistentVolumeList struct { type PersistentVolumeClaim struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired characteristics of a volume requested by a pod author. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Spec PersistentVolumeClaimSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status represents the current information/status of a persistent volume claim. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Status PersistentVolumeClaimStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -445,10 +446,10 @@ type PersistentVolumeClaim struct { type PersistentVolumeClaimList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // A list of persistent volume claims. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims Items []PersistentVolumeClaim `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -456,12 +457,12 @@ type PersistentVolumeClaimList struct { // and allows a Source for provider-specific attributes type PersistentVolumeClaimSpec struct { // AccessModes contains the desired access modes the volume should have. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1 + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1 AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty" protobuf:"bytes,1,rep,name=accessModes,casttype=PersistentVolumeAccessMode"` // A label query over volumes to consider for binding. Selector *unversioned.LabelSelector `json:"selector,omitempty" protobuf:"bytes,4,opt,name=selector"` // Resources represents the minimum resources the volume should have. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources Resources ResourceRequirements `json:"resources,omitempty" protobuf:"bytes,2,opt,name=resources"` // VolumeName is the binding reference to the PersistentVolume backing this claim. VolumeName string `json:"volumeName,omitempty" protobuf:"bytes,3,opt,name=volumeName"` @@ -472,7 +473,7 @@ type PersistentVolumeClaimStatus struct { // Phase represents the current phase of PersistentVolumeClaim. Phase PersistentVolumeClaimPhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=PersistentVolumeClaimPhase"` // AccessModes contains the actual access modes the volume backing the PVC has. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1 + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1 AccessModes []PersistentVolumeAccessMode `json:"accessModes,omitempty" protobuf:"bytes,2,rep,name=accessModes,casttype=PersistentVolumeAccessMode"` // Represents the actual resources of the underlying volume. Capacity ResourceList `json:"capacity,omitempty" protobuf:"bytes,3,rep,name=capacity,casttype=ResourceList,castkey=ResourceName"` @@ -524,7 +525,7 @@ const ( // Host path volumes do not support ownership management or SELinux relabeling. type HostPathVolumeSource struct { // Path of the directory on the host. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath Path string `json:"path" protobuf:"bytes,1,opt,name=path"` } @@ -534,7 +535,7 @@ type EmptyDirVolumeSource struct { // What type of storage medium should back this directory. // The default is "" which means to use the node's default medium. // Must be an empty string (default) or Memory. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir Medium StorageMedium `json:"medium,omitempty" protobuf:"bytes,1,opt,name=medium,casttype=StorageMedium"` } @@ -542,16 +543,16 @@ type EmptyDirVolumeSource struct { // Glusterfs volumes do not support ownership management or SELinux relabeling. type GlusterfsVolumeSource struct { // EndpointsName is the endpoint name that details Glusterfs topology. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod EndpointsName string `json:"endpoints" protobuf:"bytes,1,opt,name=endpoints"` // Path is the Glusterfs volume path. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod Path string `json:"path" protobuf:"bytes,2,opt,name=path"` // ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod + // More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"` } @@ -559,37 +560,37 @@ type GlusterfsVolumeSource struct { // RBD volumes support ownership management and SELinux relabeling. type RBDVolumeSource struct { // A collection of Ceph monitors. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it CephMonitors []string `json:"monitors" protobuf:"bytes,1,rep,name=monitors"` // The rados image name. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it RBDImage string `json:"image" protobuf:"bytes,2,opt,name=image"` // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#rbd + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#rbd // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty" protobuf:"bytes,3,opt,name=fsType"` // The rados pool name. // Default is rbd. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it. + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it. RBDPool string `json:"pool,omitempty" protobuf:"bytes,4,opt,name=pool"` // The rados user name. // Default is admin. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it RadosUser string `json:"user,omitempty" protobuf:"bytes,5,opt,name=user"` // Keyring is the path to key ring for RBDUser. // Default is /etc/ceph/keyring. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it Keyring string `json:"keyring,omitempty" protobuf:"bytes,6,opt,name=keyring"` // SecretRef is name of the authentication secret for RBDUser. If provided // overrides keyring. // Default is nil. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it SecretRef *LocalObjectReference `json:"secretRef,omitempty" protobuf:"bytes,7,opt,name=secretRef"` // ReadOnly here will force the ReadOnly setting in VolumeMounts. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,8,opt,name=readOnly"` } @@ -599,16 +600,16 @@ type RBDVolumeSource struct { // Cinder volumes support ownership management and SELinux relabeling. type CinderVolumeSource struct { // volume id used to identify the volume in cinder - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md VolumeID string `json:"volumeID" protobuf:"bytes,1,opt,name=volumeID"` // Filesystem type to mount. // Must be a filesystem type supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md FSType string `json:"fsType,omitempty" protobuf:"bytes,2,opt,name=fsType"` // Optional: Defaults to false (read/write). ReadOnly here will force // the ReadOnly setting in VolumeMounts. - // More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md + // More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"` } @@ -616,22 +617,22 @@ type CinderVolumeSource struct { // Cephfs volumes do not support ownership management or SELinux relabeling. type CephFSVolumeSource struct { // Required: Monitors is a collection of Ceph monitors - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it Monitors []string `json:"monitors" protobuf:"bytes,1,rep,name=monitors"` // Optional: Used as the mounted root, rather than the full Ceph tree, default is / Path string `json:"path,omitempty" protobuf:"bytes,2,opt,name=path"` // Optional: User is the rados user name, default is admin - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it User string `json:"user,omitempty" protobuf:"bytes,3,opt,name=user"` // Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it SecretFile string `json:"secretFile,omitempty" protobuf:"bytes,4,opt,name=secretFile"` // Optional: SecretRef is reference to the authentication secret for User, default is empty. - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it SecretRef *LocalObjectReference `json:"secretRef,omitempty" protobuf:"bytes,5,opt,name=secretRef"` // Optional: Defaults to false (read/write). ReadOnly here will force // the ReadOnly setting in VolumeMounts. - // More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it + // More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,6,opt,name=readOnly"` } @@ -668,23 +669,23 @@ const ( // PDs support ownership management and SELinux relabeling. type GCEPersistentDiskVolumeSource struct { // Unique name of the PD resource in GCE. Used to identify the disk in GCE. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk PDName string `json:"pdName" protobuf:"bytes,1,opt,name=pdName"` // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty" protobuf:"bytes,2,opt,name=fsType"` // The partition in the volume that you want to mount. // If omitted, the default is to mount by volume name. // Examples: For volume /dev/sda1, you specify the partition as "1". // Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk Partition int32 `json:"partition,omitempty" protobuf:"varint,3,opt,name=partition"` // ReadOnly here will force the ReadOnly setting in VolumeMounts. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,4,opt,name=readOnly"` } @@ -718,12 +719,12 @@ type FlexVolumeSource struct { // ownership management and SELinux relabeling. type AWSElasticBlockStoreVolumeSource struct { // Unique ID of the persistent disk resource in AWS (Amazon EBS volume). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore VolumeID string `json:"volumeID" protobuf:"bytes,1,opt,name=volumeID"` // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty" protobuf:"bytes,2,opt,name=fsType"` // The partition in the volume that you want to mount. @@ -733,7 +734,7 @@ type AWSElasticBlockStoreVolumeSource struct { Partition int32 `json:"partition,omitempty" protobuf:"varint,3,opt,name=partition"` // Specify "true" to force and set the ReadOnly property in VolumeMounts to "true". // If omitted, the default is "false". - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,4,opt,name=readOnly"` } @@ -759,7 +760,7 @@ type GitRepoVolumeSource struct { // Secret volumes support ownership management and SELinux relabeling. type SecretVolumeSource struct { // Name of the secret in the pod's namespace to use. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets SecretName string `json:"secretName,omitempty" protobuf:"bytes,1,opt,name=secretName"` // If unspecified, each key-value pair in the Data field of the referenced // Secret will be projected into the volume as a file whose name is the @@ -775,17 +776,17 @@ type SecretVolumeSource struct { // NFS volumes do not support ownership management or SELinux relabeling. type NFSVolumeSource struct { // Server is the hostname or IP address of the NFS server. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs Server string `json:"server" protobuf:"bytes,1,opt,name=server"` // Path that is exported by the NFS server. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs Path string `json:"path" protobuf:"bytes,2,opt,name=path"` // ReadOnly here will force // the NFS export to be mounted with read-only permissions. // Defaults to false. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs ReadOnly bool `json:"readOnly,omitempty" protobuf:"varint,3,opt,name=readOnly"` } @@ -805,7 +806,7 @@ type ISCSIVolumeSource struct { // Filesystem type of the volume that you want to mount. // Tip: Ensure that the filesystem type is supported by the host operating system. // Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#iscsi + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#iscsi // TODO: how do we prevent errors in the filesystem from compromising the machine FSType string `json:"fsType,omitempty" protobuf:"bytes,5,opt,name=fsType"` // ReadOnly here will force the ReadOnly setting in VolumeMounts. @@ -1045,11 +1046,11 @@ type Probe struct { // The action taken to determine the health of a container Handler `json:",inline" protobuf:"bytes,1,opt,name=handler"` // Number of seconds after the container has started before liveness probes are initiated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes InitialDelaySeconds int32 `json:"initialDelaySeconds,omitempty" protobuf:"varint,2,opt,name=initialDelaySeconds"` // Number of seconds after which the probe times out. // Defaults to 1 second. Minimum value is 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes TimeoutSeconds int32 `json:"timeoutSeconds,omitempty" protobuf:"varint,3,opt,name=timeoutSeconds"` // How often (in seconds) to perform the probe. // Default to 10 seconds. Minimum value is 1. @@ -1088,12 +1089,12 @@ type Capabilities struct { // ResourceRequirements describes the compute resource requirements. type ResourceRequirements struct { // Limits describes the maximum amount of compute resources allowed. - // More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications + // More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications Limits ResourceList `json:"limits,omitempty" protobuf:"bytes,1,rep,name=limits,casttype=ResourceList,castkey=ResourceName"` // Requests describes the minimum amount of compute resources required. // If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, // otherwise to an implementation-defined value. - // More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications + // More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications Requests ResourceList `json:"requests,omitempty" protobuf:"bytes,2,rep,name=requests,casttype=ResourceList,castkey=ResourceName"` } @@ -1109,7 +1110,7 @@ type Container struct { // Cannot be updated. Name string `json:"name" protobuf:"bytes,1,opt,name=name"` // Docker image name. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md Image string `json:"image,omitempty" protobuf:"bytes,2,opt,name=image"` // Entrypoint array. Not executed within a shell. // The docker image's ENTRYPOINT is used if this is not provided. @@ -1118,7 +1119,7 @@ type Container struct { // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, // regardless of whether the variable exists or not. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands Command []string `json:"command,omitempty" protobuf:"bytes,3,rep,name=command"` // Arguments to the entrypoint. // The docker image's CMD is used if this is not provided. @@ -1127,7 +1128,7 @@ type Container struct { // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, // regardless of whether the variable exists or not. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands Args []string `json:"args,omitempty" protobuf:"bytes,4,rep,name=args"` // Container's working directory. // If not specified, the container runtime's default will be used, which @@ -1147,7 +1148,7 @@ type Container struct { Env []EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=env"` // Compute Resources required by this container. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources Resources ResourceRequirements `json:"resources,omitempty" protobuf:"bytes,8,opt,name=resources"` // Pod volumes to mount into the container's filesystem. // Cannot be updated. @@ -1155,12 +1156,12 @@ type Container struct { // Periodic probe of container liveness. // Container will be restarted if the probe fails. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes LivenessProbe *Probe `json:"livenessProbe,omitempty" protobuf:"bytes,10,opt,name=livenessProbe"` // Periodic probe of container service readiness. // Container will be removed from service endpoints if the probe fails. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes ReadinessProbe *Probe `json:"readinessProbe,omitempty" protobuf:"bytes,11,opt,name=readinessProbe"` // Actions that the management system should take in response to container lifecycle events. // Cannot be updated. @@ -1175,10 +1176,10 @@ type Container struct { // One of Always, Never, IfNotPresent. // Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#updating-images + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#updating-images ImagePullPolicy PullPolicy `json:"imagePullPolicy,omitempty" protobuf:"bytes,14,opt,name=imagePullPolicy,casttype=PullPolicy"` // Security options the pod should run with. - // More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md + // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md SecurityContext *SecurityContext `json:"securityContext,omitempty" protobuf:"bytes,15,opt,name=securityContext"` // Variables for interactive containers, these have very specialized use-cases (e.g. debugging) @@ -1222,14 +1223,14 @@ type Lifecycle struct { // PostStart is called immediately after a container is created. If the handler fails, // the container is terminated and restarted according to its restart policy. // Other management of the container blocks until the hook completes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details PostStart *Handler `json:"postStart,omitempty" protobuf:"bytes,1,opt,name=postStart"` // PreStop is called immediately before a container is terminated. // The container is terminated after the handler completes. // The reason for termination is passed to the handler. // Regardless of the outcome of the handler, the container is eventually terminated. // Other management of the container blocks until the hook completes. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details PreStop *Handler `json:"preStop,omitempty" protobuf:"bytes,2,opt,name=preStop"` } @@ -1306,13 +1307,13 @@ type ContainerStatus struct { // garbage collection. This value will get capped at 5 by GC. RestartCount int32 `json:"restartCount" protobuf:"varint,5,opt,name=restartCount"` // The image the container is running. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md // TODO(dchen1107): Which image the container is running with? Image string `json:"image" protobuf:"bytes,6,opt,name=image"` // ImageID of the container's image. ImageID string `json:"imageID" protobuf:"bytes,7,opt,name=imageID"` // Container's ID in the format 'docker://'. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#container-information + // More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#container-information ContainerID string `json:"containerID,omitempty" protobuf:"bytes,8,opt,name=containerID"` } @@ -1355,11 +1356,11 @@ const ( type PodCondition struct { // Type is the type of the condition. // Currently only Ready. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions Type PodConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=PodConditionType"` // Status is the status of the condition. // Can be True, False, Unknown. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions Status ConditionStatus `json:"status" protobuf:"bytes,2,opt,name=status,casttype=ConditionStatus"` // Last time we probed the condition. LastProbeTime unversioned.Time `json:"lastProbeTime,omitempty" protobuf:"bytes,3,opt,name=lastProbeTime"` @@ -1664,7 +1665,7 @@ const ( // PodSpec is a description of a pod. type PodSpec struct { // List of volumes that can be mounted by containers belonging to the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md Volumes []Volume `json:"volumes,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,1,rep,name=volumes"` // List of initialization containers belonging to the pod. // Init containers are executed in order prior to containers being started. If any @@ -1679,18 +1680,18 @@ type PodSpec struct { // Init containers cannot currently be added or removed. // Init containers are in alpha state and may change without notice. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md InitContainers []Container `json:"-" patchStrategy:"merge" patchMergeKey:"name"` // List of containers belonging to the pod. // Containers cannot currently be added or removed. // There must be at least one container in a Pod. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md Containers []Container `json:"containers" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,2,rep,name=containers"` // Restart policy for all containers within the pod. // One of Always, OnFailure, Never. // Default to Always. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#restartpolicy + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#restartpolicy RestartPolicy RestartPolicy `json:"restartPolicy,omitempty" protobuf:"bytes,3,opt,name=restartPolicy,casttype=RestartPolicy"` // Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. // Value must be non-negative integer. The value zero indicates delete immediately. @@ -1710,14 +1711,15 @@ type PodSpec struct { DNSPolicy DNSPolicy `json:"dnsPolicy,omitempty" protobuf:"bytes,6,opt,name=dnsPolicy,casttype=DNSPolicy"` // NodeSelector is a selector which must be true for the pod to fit on a node. // Selector which must match a node's labels for the pod to be scheduled on that node. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/node-selection/README.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/node-selection/README.md NodeSelector map[string]string `json:"nodeSelector,omitempty" protobuf:"bytes,7,rep,name=nodeSelector"` // ServiceAccountName is the name of the ServiceAccount to use to run this pod. - // More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md + // More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md ServiceAccountName string `json:"serviceAccountName,omitempty" protobuf:"bytes,8,opt,name=serviceAccountName"` // DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. // Deprecated: Use serviceAccountName instead. + // +k8s:conversion-gen=false DeprecatedServiceAccount string `json:"serviceAccount,omitempty" protobuf:"bytes,9,opt,name=serviceAccount"` // NodeName is a request to schedule this pod onto a specific node. If it is non-empty, @@ -1727,12 +1729,15 @@ type PodSpec struct { // Host networking requested for this pod. Use the host's network namespace. // If this option is set, the ports that will be used must be specified. // Default to false. + // +k8s:conversion-gen=false HostNetwork bool `json:"hostNetwork,omitempty" protobuf:"varint,11,opt,name=hostNetwork"` // Use the host's pid namespace. // Optional: Default to false. + // +k8s:conversion-gen=false HostPID bool `json:"hostPID,omitempty" protobuf:"varint,12,opt,name=hostPID"` // Use the host's ipc namespace. // Optional: Default to false. + // +k8s:conversion-gen=false HostIPC bool `json:"hostIPC,omitempty" protobuf:"varint,13,opt,name=hostIPC"` // SecurityContext holds pod-level security attributes and common container settings. // Optional: Defaults to empty. See type description for default values of each field. @@ -1740,7 +1745,7 @@ type PodSpec struct { // ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. // If specified, these secrets will be passed to individual puller implementations for them to use. For example, // in the case of docker, only DockerConfig type secrets are honored. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod + // More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod ImagePullSecrets []LocalObjectReference `json:"imagePullSecrets,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,15,rep,name=imagePullSecrets"` // Specifies the hostname of the Pod // If not specified, the pod's hostname will be set to a system-defined value. @@ -1793,10 +1798,10 @@ type PodSecurityContext struct { // state of a system. type PodStatus struct { // Current condition of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-phase + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-phase Phase PodPhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=PodPhase"` // Current service state of pod. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions Conditions []PodCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,2,rep,name=conditions"` // A human readable message indicating details about why the pod is in this condition. Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` @@ -1818,11 +1823,11 @@ type PodStatus struct { // init container will have ready = true, the most recently started container will have // startTime set. // Init containers are in alpha state and may change without notice. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-statuses + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-statuses InitContainerStatuses []ContainerStatus `json:"-"` // The list has one entry per container in the manifest. Each entry is currently the output // of `docker inspect`. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-statuses + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-statuses ContainerStatuses []ContainerStatus `json:"containerStatuses,omitempty" protobuf:"bytes,8,rep,name=containerStatuses"` } @@ -1830,13 +1835,13 @@ type PodStatus struct { type PodStatusResult struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Most recently observed status of the pod. // This data may not be up to date. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status PodStatus `json:"status,omitempty" protobuf:"bytes,2,opt,name=status"` } @@ -1847,18 +1852,18 @@ type PodStatusResult struct { type Pod struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the pod. // This data may not be up to date. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status PodStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -1866,22 +1871,22 @@ type Pod struct { type PodList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of pods. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/pods.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/pods.md Items []Pod `json:"items" protobuf:"bytes,2,rep,name=items"` } // PodTemplateSpec describes the data a pod should have when created from a template type PodTemplateSpec struct { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the pod. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` } @@ -1891,11 +1896,11 @@ type PodTemplateSpec struct { type PodTemplate struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Template defines the pods that will be created from this pod template. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Template PodTemplateSpec `json:"template,omitempty" protobuf:"bytes,2,opt,name=template"` } @@ -1903,7 +1908,7 @@ type PodTemplate struct { type PodTemplateList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of pod templates @@ -1915,14 +1920,14 @@ type ReplicationControllerSpec struct { // Replicas is the number of desired replicas. // This is a pointer to distinguish between explicit zero and unspecified. // Defaults to 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Selector is a label query over pods that should match the Replicas count. // If Selector is empty, it is defaulted to the labels present on the Pod template. // Label keys and values that must match in order to be controlled by this replication // controller, if empty defaulted to labels on Pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector map[string]string `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"` // TemplateRef is a reference to an object that describes the pod that will be created if @@ -1932,7 +1937,7 @@ type ReplicationControllerSpec struct { // Template is the object that describes the pod that will be created if // insufficient replicas are detected. This takes precedence over a TemplateRef. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template Template *PodTemplateSpec `json:"template,omitempty" protobuf:"bytes,3,opt,name=template"` } @@ -1940,7 +1945,7 @@ type ReplicationControllerSpec struct { // controller. type ReplicationControllerStatus struct { // Replicas is the most recently oberved number of replicas. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // The number of pods that have labels matching the labels of the pod template of the replication controller. @@ -1958,18 +1963,18 @@ type ReplicationController struct { // If the Labels of a ReplicationController are empty, they are defaulted to // be the same as the Pod(s) that the replication controller manages. - // Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the specification of the desired behavior of the replication controller. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ReplicationControllerSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the most recently observed status of the replication controller. // This data may be out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ReplicationControllerStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -1977,11 +1982,11 @@ type ReplicationController struct { type ReplicationControllerList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of replication controllers. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md Items []ReplicationController `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -2043,13 +2048,13 @@ type LoadBalancerIngress struct { // ServiceSpec describes the attributes that a user creates on a service. type ServiceSpec struct { // The list of ports that are exposed by this service. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies Ports []ServicePort `json:"ports" patchStrategy:"merge" patchMergeKey:"port" protobuf:"bytes,1,rep,name=ports"` // This service will route traffic to pods having labels matching this selector. // Label keys and values that must match in order to receive traffic for this service. - // If empty, all pods are selected, if not specified, endpoints must be manually specified. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#overview + // If not specified, endpoints must be manually specified and the system will not automatically manage them. + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#overview Selector map[string]string `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"` // ClusterIP is usually assigned by the master and is the IP address of the service. @@ -2058,12 +2063,12 @@ type ServiceSpec struct { // Valid values are None, empty string (""), or a valid IP address. // 'None' can be specified for a headless service when proxying is not required. // Cannot be updated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies ClusterIP string `json:"clusterIP,omitempty" protobuf:"bytes,3,opt,name=clusterIP"` // Type of exposed service. Must be ClusterIP, NodePort, or LoadBalancer. // Defaults to ClusterIP. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#external-services + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#external-services Type ServiceType `json:"type,omitempty" protobuf:"bytes,4,opt,name=type,casttype=ServiceType"` // externalIPs is a list of IP addresses for which nodes in the cluster @@ -2080,14 +2085,14 @@ type ServiceSpec struct { // API for compatibility until at least 8/20/2016. It will be removed from // any new API revisions. If both deprecatedPublicIPs *and* externalIPs are // set, deprecatedPublicIPs is used. - // +genconversion=false + // +k8s:conversion-gen=false DeprecatedPublicIPs []string `json:"deprecatedPublicIPs,omitempty" protobuf:"bytes,6,rep,name=deprecatedPublicIPs"` // Supports "ClientIP" and "None". Used to maintain session affinity. // Enable client IP based session affinity. // Must be ClientIP or None. // Defaults to None. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies SessionAffinity ServiceAffinity `json:"sessionAffinity,omitempty" protobuf:"bytes,7,opt,name=sessionAffinity,casttype=ServiceAffinity"` // Only applies to Service Type: LoadBalancer @@ -2100,7 +2105,7 @@ type ServiceSpec struct { // If specified and supported by the platform, this will restrict traffic through the cloud-provider // load-balancer will be restricted to the specified client IPs. This field will be ignored if the // cloud-provider does not support the feature." - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services-firewalls.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services-firewalls.md LoadBalancerSourceRanges []string `json:"loadBalancerSourceRanges,omitempty" protobuf:"bytes,9,opt,name=loadBalancerSourceRanges"` } @@ -2126,14 +2131,14 @@ type ServicePort struct { // of the 'port' field is used (an identity map). // This field is ignored for services with clusterIP=None, and should be // omitted or set equal to the 'port' field. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#defining-a-service + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service TargetPort intstr.IntOrString `json:"targetPort,omitempty" protobuf:"bytes,4,opt,name=targetPort"` // The port on each node on which this service is exposed when type=NodePort or LoadBalancer. // Usually assigned by the system. If specified, it will be allocated to the service // if unused or else creation of the service will fail. // Default is to auto-allocate a port if the ServiceType of this Service requires one. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#type--nodeport + // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#type--nodeport NodePort int32 `json:"nodePort,omitempty" protobuf:"varint,5,opt,name=nodePort"` } @@ -2145,17 +2150,17 @@ type ServicePort struct { type Service struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the behavior of a service. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ServiceSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the service. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ServiceStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -2169,7 +2174,7 @@ const ( type ServiceList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of services @@ -2185,17 +2190,17 @@ type ServiceList struct { type ServiceAccount struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md Secrets []ObjectReference `json:"secrets,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,2,rep,name=secrets"` // ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images // in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets // can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret ImagePullSecrets []LocalObjectReference `json:"imagePullSecrets,omitempty" protobuf:"bytes,3,rep,name=imagePullSecrets"` } @@ -2203,11 +2208,11 @@ type ServiceAccount struct { type ServiceAccountList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of ServiceAccounts. - // More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md#service-accounts + // More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md#service-accounts Items []ServiceAccount `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -2228,7 +2233,7 @@ type ServiceAccountList struct { type Endpoints struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // The set of all endpoints is the union of all subsets. Addresses are placed into @@ -2298,7 +2303,7 @@ type EndpointPort struct { type EndpointsList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of endpoints. @@ -2315,7 +2320,7 @@ type NodeSpec struct { // ID of the node assigned by the cloud provider in the format: :// ProviderID string `json:"providerID,omitempty" protobuf:"bytes,3,opt,name=providerID"` // Unschedulable controls node schedulability of new pods. By default, node is schedulable. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#manual-node-administration"` + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#manual-node-administration"` Unschedulable bool `json:"unschedulable,omitempty" protobuf:"varint,4,opt,name=unschedulable"` } @@ -2364,25 +2369,25 @@ type NodeSystemInfo struct { // NodeStatus is information about the current status of a node. type NodeStatus struct { // Capacity represents the total resources of a node. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity for more details. + // More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity for more details. Capacity ResourceList `json:"capacity,omitempty" protobuf:"bytes,1,rep,name=capacity,casttype=ResourceList,castkey=ResourceName"` // Allocatable represents the resources of a node that are available for scheduling. // Defaults to Capacity. Allocatable ResourceList `json:"allocatable,omitempty" protobuf:"bytes,2,rep,name=allocatable,casttype=ResourceList,castkey=ResourceName"` // NodePhase is the recently observed lifecycle phase of the node. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-phase + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase Phase NodePhase `json:"phase,omitempty" protobuf:"bytes,3,opt,name=phase,casttype=NodePhase"` // Conditions is an array of current observed node conditions. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-condition + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition Conditions []NodeCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,4,rep,name=conditions"` // List of addresses reachable to the node. // Queried from cloud provider, if available. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-addresses + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses Addresses []NodeAddress `json:"addresses,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,5,rep,name=addresses"` // Endpoints of daemons running on the Node. DaemonEndpoints NodeDaemonEndpoints `json:"daemonEndpoints,omitempty" protobuf:"bytes,6,opt,name=daemonEndpoints"` // Set of ids/uuids to uniquely identify the node. - // More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-info + // More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info NodeInfo NodeSystemInfo `json:"nodeInfo,omitempty" protobuf:"bytes,7,opt,name=nodeInfo"` // List of container images on this node Images []ContainerImage `json:"images,omitempty" protobuf:"bytes,8,rep,name=images"` @@ -2403,6 +2408,34 @@ type AttachedVolume struct { DevicePath string `json:"devicePath" protobuf:"bytes,2,rep,name=devicePath"` } +// AvoidPods describes pods that should avoid this node. This is the value for a +// Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and +// will eventually become a field of NodeStatus. +type AvoidPods struct { + // Bounded-sized list of signatures of pods that should avoid this node, sorted + // in timestamp order from oldest to newest. Size of the slice is unspecified. + PreferAvoidPods []PreferAvoidPodsEntry `json:"preferAvoidPods,omitempty" protobuf:"bytes,1,rep,name=preferAvoidPods"` +} + +// Describes a class of pods that should avoid this node. +type PreferAvoidPodsEntry struct { + // The class of pods. + PodSignature PodSignature `json:"podSignature" protobuf:"bytes,1,opt,name=podSignature"` + // Time at which this entry was added to the list. + EvictionTime unversioned.Time `json:"evictionTime,omitempty" protobuf:"bytes,2,opt,name=evictionTime"` + // (brief) reason why this entry was added to the list. + Reason string `json:"reason,omitempty" protobuf:"bytes,3,opt,name=reason"` + // Human readable message indicating why this entry was added to the list. + Message string `json:"message,omitempty" protobuf:"bytes,4,opt,name=message"` +} + +// Describes the class of pods that should avoid this node. +// Exactly one field should be set. +type PodSignature struct { + // Reference to controller whose pods should avoid this node. + PodController *OwnerReference `json:"podController,omitempty" protobuf:"bytes,1,opt,name=podController"` +} + // Describe a container image type ContainerImage struct { // Names by which this image is known. @@ -2437,6 +2470,8 @@ const ( NodeOutOfDisk NodeConditionType = "OutOfDisk" // NodeMemoryPressure means the kubelet is under pressure due to insufficient available memory. NodeMemoryPressure NodeConditionType = "MemoryPressure" + // NodeDiskPressure means the kubelet is under pressure due to insufficient available disk. + NodeDiskPressure NodeConditionType = "DiskPressure" // NodeNetworkUnavailable means that network for the node is not correctly configured. NodeNetworkUnavailable NodeConditionType = "NetworkUnavailable" ) @@ -2497,24 +2532,25 @@ const ( // ResourceList is a set of (resource name, quantity) pairs. type ResourceList map[ResourceName]resource.Quantity -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // Node is a worker node in Kubernetes, formerly known as minion. // Each node will have a unique identifier in the cache (i.e. in etcd). type Node struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the behavior of a node. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec NodeSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the node. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status NodeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -2522,7 +2558,7 @@ type Node struct { type NodeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of nodes @@ -2539,14 +2575,14 @@ const ( // NamespaceSpec describes the attributes on a Namespace. type NamespaceSpec struct { // Finalizers is an opaque list of values that must be empty to permanently remove object from storage. - // More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#finalizers + // More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#finalizers Finalizers []FinalizerName `json:"finalizers,omitempty" protobuf:"bytes,1,rep,name=finalizers,casttype=FinalizerName"` } // NamespaceStatus is information about the current status of a Namespace. type NamespaceStatus struct { // Phase is the current lifecycle phase of the namespace. - // More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#phases + // More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#phases Phase NamespacePhase `json:"phase,omitempty" protobuf:"bytes,1,opt,name=phase,casttype=NamespacePhase"` } @@ -2560,22 +2596,23 @@ const ( NamespaceTerminating NamespacePhase = "Terminating" ) -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // Namespace provides a scope for Names. // Use of multiple namespaces is optional. type Namespace struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the behavior of the Namespace. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec NamespaceSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status describes the current status of a Namespace. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status NamespaceStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -2583,11 +2620,11 @@ type Namespace struct { type NamespaceList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Namespace objects in the list. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md Items []Namespace `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -2596,7 +2633,7 @@ type NamespaceList struct { type Binding struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // The target object that you want to bind to the standard object. @@ -2786,13 +2823,13 @@ type OwnerReference struct { // API version of the referent. APIVersion string `json:"apiVersion" protobuf:"bytes,5,opt,name=apiVersion"` // Kind of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name" protobuf:"bytes,3,opt,name=name"` // UID of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids UID types.UID `json:"uid" protobuf:"bytes,4,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"` // If true, this reference points to the managing controller. Controller *bool `json:"controller,omitempty" protobuf:"varint,6,opt,name=controller"` @@ -2801,21 +2838,21 @@ type OwnerReference struct { // ObjectReference contains enough information to let you inspect or modify the referred object. type ObjectReference struct { // Kind of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"` // Namespace of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md Namespace string `json:"namespace,omitempty" protobuf:"bytes,2,opt,name=namespace"` // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty" protobuf:"bytes,3,opt,name=name"` // UID of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids UID types.UID `json:"uid,omitempty" protobuf:"bytes,4,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"` // API version of the referent. APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,5,opt,name=apiVersion"` // Specific resourceVersion to which this reference is made, if any. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"` // If referring to a piece of an object instead of an entire object, this string @@ -2833,7 +2870,7 @@ type ObjectReference struct { // referenced object inside the same namespace. type LocalObjectReference struct { // Name of the referent. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names // TODO: Add other useful fields. apiVersion, kind, uid? Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"` } @@ -2868,7 +2905,7 @@ const ( type Event struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata" protobuf:"bytes,1,opt,name=metadata"` // The object that this event is about. @@ -2903,7 +2940,7 @@ type Event struct { type EventList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of events @@ -2914,7 +2951,7 @@ type EventList struct { type List struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of objects @@ -2959,11 +2996,11 @@ type LimitRangeSpec struct { type LimitRange struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the limits enforced. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec LimitRangeSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` } @@ -2971,11 +3008,11 @@ type LimitRange struct { type LimitRangeList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of LimitRange objects. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_limit_range.md + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_limit_range.md Items []LimitRange `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -3026,7 +3063,7 @@ const ( // ResourceQuotaSpec defines the desired hard limits to enforce for Quota. type ResourceQuotaSpec struct { // Hard is the set of desired hard limits for each named resource. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Hard ResourceList `json:"hard,omitempty" protobuf:"bytes,1,rep,name=hard,casttype=ResourceList,castkey=ResourceName"` // A collection of filters that must match each object tracked by a quota. // If not specified, the quota matches all objects. @@ -3036,7 +3073,7 @@ type ResourceQuotaSpec struct { // ResourceQuotaStatus defines the enforced hard limits and observed use. type ResourceQuotaStatus struct { // Hard is the set of enforced hard limits for each named resource. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Hard ResourceList `json:"hard,omitempty" protobuf:"bytes,1,rep,name=hard,casttype=ResourceList,castkey=ResourceName"` // Used is the current observed total usage of the resource in the namespace. Used ResourceList `json:"used,omitempty" protobuf:"bytes,2,rep,name=used,casttype=ResourceList,castkey=ResourceName"` @@ -3048,15 +3085,15 @@ type ResourceQuotaStatus struct { type ResourceQuota struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired quota. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ResourceQuotaSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status defines the actual enforced quota and its current usage. - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ResourceQuotaStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -3064,11 +3101,11 @@ type ResourceQuota struct { type ResourceQuotaList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of ResourceQuota objects. - // More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota + // More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota Items []ResourceQuota `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -3079,7 +3116,7 @@ type ResourceQuotaList struct { type Secret struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Data contains the secret data. Each key must be a valid DNS_SUBDOMAIN @@ -3089,6 +3126,13 @@ type Secret struct { // Described in https://tools.ietf.org/html/rfc4648#section-4 Data map[string][]byte `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"` + // stringData allows specifying non-binary secret data in string form. + // It is provided as a write-only convenience method. + // All keys and values are merged into the data field on write, overwriting any existing values. + // It is never output when reading from the API. + // +k8s:conversion-gen=false + StringData map[string]string `json:"stringData,omitempty" protobuf:"bytes,4,rep,name=stringData"` + // Used to facilitate programmatic handling of secret data. Type SecretType `json:"type,omitempty" protobuf:"bytes,3,opt,name=type,casttype=SecretType"` } @@ -3151,11 +3195,11 @@ const ( type SecretList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of secret objects. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md Items []Secret `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -3165,7 +3209,7 @@ type SecretList struct { type ConfigMap struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Data contains the configuration data. @@ -3177,7 +3221,7 @@ type ConfigMap struct { type ConfigMapList struct { unversioned.TypeMeta `json:",inline"` - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of ConfigMaps. @@ -3208,13 +3252,14 @@ type ComponentCondition struct { Error string `json:"error,omitempty" protobuf:"bytes,4,opt,name=error"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ComponentStatus (and ComponentStatusList) holds the cluster validation info. type ComponentStatus struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of component conditions observed @@ -3225,7 +3270,7 @@ type ComponentStatus struct { type ComponentStatusList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of ComponentStatus objects. @@ -3299,7 +3344,7 @@ type SELinuxOptions struct { type RangeAllocation struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Range is string that identifies the range represented by 'data'. diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go index 7587654aa27a..21e6b82c743f 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,10 +29,10 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE var map_AWSElasticBlockStoreVolumeSource = map[string]string{ "": "Represents a Persistent Disk resource in AWS.\n\nAn AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling.", - "volumeID": "Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore", - "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore", + "volumeID": "Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore", + "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore", "partition": "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", - "readOnly": "Specify \"true\" to force and set the ReadOnly property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore", + "readOnly": "Specify \"true\" to force and set the ReadOnly property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore", } func (AWSElasticBlockStoreVolumeSource) SwaggerDoc() map[string]string { @@ -60,6 +60,15 @@ func (AttachedVolume) SwaggerDoc() map[string]string { return map_AttachedVolume } +var map_AvoidPods = map[string]string{ + "": "AvoidPods describes pods that should avoid this node. This is the value for a Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and will eventually become a field of NodeStatus.", + "preferAvoidPods": "Bounded-sized list of signatures of pods that should avoid this node, sorted in timestamp order from oldest to newest. Size of the slice is unspecified.", +} + +func (AvoidPods) SwaggerDoc() map[string]string { + return map_AvoidPods +} + var map_AzureFileVolumeSource = map[string]string{ "": "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", "secretName": "the name of secret that contains Azure Storage Account Name and Key", @@ -73,7 +82,7 @@ func (AzureFileVolumeSource) SwaggerDoc() map[string]string { var map_Binding = map[string]string{ "": "Binding ties one object to another. For example, a pod is bound to a node by a scheduler.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "target": "The target object that you want to bind to the standard object.", } @@ -93,12 +102,12 @@ func (Capabilities) SwaggerDoc() map[string]string { var map_CephFSVolumeSource = map[string]string{ "": "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - "monitors": "Required: Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it", + "monitors": "Required: Monitors is a collection of Ceph monitors More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", "path": "Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - "user": "Optional: User is the rados user name, default is admin More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it", - "secretFile": "Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it", - "secretRef": "Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it", - "readOnly": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: http://releases.k8s.io/release-1.3/examples/cephfs/README.md#how-to-use-it", + "user": "Optional: User is the rados user name, default is admin More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + "secretFile": "Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + "secretRef": "Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", + "readOnly": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: http://releases.k8s.io/HEAD/examples/volumes/cephfs/README.md#how-to-use-it", } func (CephFSVolumeSource) SwaggerDoc() map[string]string { @@ -107,9 +116,9 @@ func (CephFSVolumeSource) SwaggerDoc() map[string]string { var map_CinderVolumeSource = map[string]string{ "": "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - "volumeID": "volume id used to identify the volume in cinder More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md", - "fsType": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md", - "readOnly": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md", + "volumeID": "volume id used to identify the volume in cinder More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + "fsType": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", + "readOnly": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", } func (CinderVolumeSource) SwaggerDoc() map[string]string { @@ -130,7 +139,7 @@ func (ComponentCondition) SwaggerDoc() map[string]string { var map_ComponentStatus = map[string]string{ "": "ComponentStatus (and ComponentStatusList) holds the cluster validation info.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "conditions": "List of component conditions observed", } @@ -140,7 +149,7 @@ func (ComponentStatus) SwaggerDoc() map[string]string { var map_ComponentStatusList = map[string]string{ "": "Status of all the conditions for the component as a list of ComponentStatus objects.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of ComponentStatus objects.", } @@ -150,7 +159,7 @@ func (ComponentStatusList) SwaggerDoc() map[string]string { var map_ConfigMap = map[string]string{ "": "ConfigMap holds configuration data for pods to consume.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "data": "Data contains the configuration data. Each key must be a valid DNS_SUBDOMAIN with an optional leading dot.", } @@ -169,7 +178,7 @@ func (ConfigMapKeySelector) SwaggerDoc() map[string]string { var map_ConfigMapList = map[string]string{ "": "ConfigMapList is a resource containing a list of ConfigMap objects.", - "metadata": "More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of ConfigMaps.", } @@ -189,20 +198,20 @@ func (ConfigMapVolumeSource) SwaggerDoc() map[string]string { var map_Container = map[string]string{ "": "A single application container that you want to run within a pod.", "name": "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - "image": "Docker image name. More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md", - "command": "Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands", - "args": "Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md#containers-and-commands", + "image": "Docker image name. More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md", + "command": "Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands", + "args": "Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md#containers-and-commands", "workingDir": "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", "ports": "List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated.", "env": "List of environment variables to set in the container. Cannot be updated.", - "resources": "Compute Resources required by this container. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources", + "resources": "Compute Resources required by this container. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources", "volumeMounts": "Pod volumes to mount into the container's filesystem. Cannot be updated.", - "livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes", - "readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes", + "livenessProbe": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes", + "readinessProbe": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes", "lifecycle": "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", "terminationMessagePath": "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Defaults to /dev/termination-log. Cannot be updated.", - "imagePullPolicy": "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#updating-images", - "securityContext": "Security options the pod should run with. More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md", + "imagePullPolicy": "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#updating-images", + "securityContext": "Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md", "stdin": "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", "stdinOnce": "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", "tty": "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", @@ -287,9 +296,9 @@ var map_ContainerStatus = map[string]string{ "lastState": "Details about the container's last termination condition.", "ready": "Specifies whether the container has passed its readiness probe.", "restartCount": "The number of times the container has been restarted, currently based on the number of dead containers that have not yet been removed. Note that this is calculated from dead containers. But those containers are subject to garbage collection. This value will get capped at 5 by GC.", - "image": "The image the container is running. More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md", + "image": "The image the container is running. More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md", "imageID": "ImageID of the container's image.", - "containerID": "Container's ID in the format 'docker://'. More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#container-information", + "containerID": "Container's ID in the format 'docker://'. More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#container-information", } func (ContainerStatus) SwaggerDoc() map[string]string { @@ -338,7 +347,7 @@ func (DownwardAPIVolumeSource) SwaggerDoc() map[string]string { var map_EmptyDirVolumeSource = map[string]string{ "": "Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling.", - "medium": "What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir", + "medium": "What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir", } func (EmptyDirVolumeSource) SwaggerDoc() map[string]string { @@ -380,7 +389,7 @@ func (EndpointSubset) SwaggerDoc() map[string]string { var map_Endpoints = map[string]string{ "": "Endpoints is a collection of endpoints that implement the actual service. Example:\n Name: \"mysvc\",\n Subsets: [\n {\n Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n },\n {\n Addresses: [{\"ip\": \"10.10.3.3\"}],\n Ports: [{\"name\": \"a\", \"port\": 93}, {\"name\": \"b\", \"port\": 76}]\n },\n ]", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "subsets": "The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service.", } @@ -390,7 +399,7 @@ func (Endpoints) SwaggerDoc() map[string]string { var map_EndpointsList = map[string]string{ "": "EndpointsList is a list of endpoints.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of endpoints.", } @@ -423,7 +432,7 @@ func (EnvVarSource) SwaggerDoc() map[string]string { var map_Event = map[string]string{ "": "Event is a report of an event somewhere in the cluster.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "involvedObject": "The object that this event is about.", "reason": "This should be a short, machine understandable string that gives the reason for the transition into the object's current status.", "message": "A human-readable description of the status of this operation.", @@ -440,7 +449,7 @@ func (Event) SwaggerDoc() map[string]string { var map_EventList = map[string]string{ "": "EventList is a list of events.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of events", } @@ -513,10 +522,10 @@ func (FlockerVolumeSource) SwaggerDoc() map[string]string { var map_GCEPersistentDiskVolumeSource = map[string]string{ "": "Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling.", - "pdName": "Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", - "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", - "partition": "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", - "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", + "pdName": "Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", + "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", + "partition": "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", + "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", } func (GCEPersistentDiskVolumeSource) SwaggerDoc() map[string]string { @@ -536,9 +545,9 @@ func (GitRepoVolumeSource) SwaggerDoc() map[string]string { var map_GlusterfsVolumeSource = map[string]string{ "": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - "endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod", - "path": "Path is the Glusterfs volume path. More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod", - "readOnly": "ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md#create-a-pod", + "endpoints": "EndpointsName is the endpoint name that details Glusterfs topology. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", + "path": "Path is the Glusterfs volume path. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", + "readOnly": "ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md#create-a-pod", } func (GlusterfsVolumeSource) SwaggerDoc() map[string]string { @@ -581,7 +590,7 @@ func (Handler) SwaggerDoc() map[string]string { var map_HostPathVolumeSource = map[string]string{ "": "Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling.", - "path": "Path of the directory on the host. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath", + "path": "Path of the directory on the host. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath", } func (HostPathVolumeSource) SwaggerDoc() map[string]string { @@ -594,7 +603,7 @@ var map_ISCSIVolumeSource = map[string]string{ "iqn": "Target iSCSI Qualified Name.", "lun": "iSCSI target lun number.", "iscsiInterface": "Optional: Defaults to 'default' (tcp). iSCSI interface name that uses an iSCSI transport.", - "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#iscsi", + "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#iscsi", "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", } @@ -614,8 +623,8 @@ func (KeyToPath) SwaggerDoc() map[string]string { var map_Lifecycle = map[string]string{ "": "Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted.", - "postStart": "PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details", - "preStop": "PreStop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: http://releases.k8s.io/release-1.3/docs/user-guide/container-environment.md#hook-details", + "postStart": "PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details", + "preStop": "PreStop is called immediately before a container is terminated. The container is terminated after the handler completes. The reason for termination is passed to the handler. Regardless of the outcome of the handler, the container is eventually terminated. Other management of the container blocks until the hook completes. More info: http://releases.k8s.io/HEAD/docs/user-guide/container-environment.md#hook-details", } func (Lifecycle) SwaggerDoc() map[string]string { @@ -624,8 +633,8 @@ func (Lifecycle) SwaggerDoc() map[string]string { var map_LimitRange = map[string]string{ "": "LimitRange sets resource usage limits for each kind of resource in a Namespace.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the limits enforced. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the limits enforced. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (LimitRange) SwaggerDoc() map[string]string { @@ -648,8 +657,8 @@ func (LimitRangeItem) SwaggerDoc() map[string]string { var map_LimitRangeList = map[string]string{ "": "LimitRangeList is a list of LimitRange items.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "Items is a list of LimitRange objects. More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_limit_range.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of LimitRange objects. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_limit_range.md", } func (LimitRangeList) SwaggerDoc() map[string]string { @@ -667,7 +676,7 @@ func (LimitRangeSpec) SwaggerDoc() map[string]string { var map_List = map[string]string{ "": "List holds a list of objects, which may not be known by the server.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of objects", } @@ -709,7 +718,7 @@ func (LoadBalancerStatus) SwaggerDoc() map[string]string { var map_LocalObjectReference = map[string]string{ "": "LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.", - "name": "Name of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", + "name": "Name of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", } func (LocalObjectReference) SwaggerDoc() map[string]string { @@ -718,9 +727,9 @@ func (LocalObjectReference) SwaggerDoc() map[string]string { var map_NFSVolumeSource = map[string]string{ "": "Represents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling.", - "server": "Server is the hostname or IP address of the NFS server. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs", - "path": "Path that is exported by the NFS server. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs", - "readOnly": "ReadOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs", + "server": "Server is the hostname or IP address of the NFS server. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs", + "path": "Path that is exported by the NFS server. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs", + "readOnly": "ReadOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs", } func (NFSVolumeSource) SwaggerDoc() map[string]string { @@ -729,9 +738,9 @@ func (NFSVolumeSource) SwaggerDoc() map[string]string { var map_Namespace = map[string]string{ "": "Namespace provides a scope for Names. Use of multiple namespaces is optional.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the behavior of the Namespace. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status describes the current status of a Namespace. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of the Namespace. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status describes the current status of a Namespace. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Namespace) SwaggerDoc() map[string]string { @@ -740,8 +749,8 @@ func (Namespace) SwaggerDoc() map[string]string { var map_NamespaceList = map[string]string{ "": "NamespaceList is a list of Namespaces.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "Items is the list of Namespace objects in the list. More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "Items is the list of Namespace objects in the list. More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md", } func (NamespaceList) SwaggerDoc() map[string]string { @@ -750,7 +759,7 @@ func (NamespaceList) SwaggerDoc() map[string]string { var map_NamespaceSpec = map[string]string{ "": "NamespaceSpec describes the attributes on a Namespace.", - "finalizers": "Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#finalizers", + "finalizers": "Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#finalizers", } func (NamespaceSpec) SwaggerDoc() map[string]string { @@ -759,7 +768,7 @@ func (NamespaceSpec) SwaggerDoc() map[string]string { var map_NamespaceStatus = map[string]string{ "": "NamespaceStatus is information about the current status of a Namespace.", - "phase": "Phase is the current lifecycle phase of the namespace. More info: http://releases.k8s.io/release-1.3/docs/design/namespaces.md#phases", + "phase": "Phase is the current lifecycle phase of the namespace. More info: http://releases.k8s.io/HEAD/docs/design/namespaces.md#phases", } func (NamespaceStatus) SwaggerDoc() map[string]string { @@ -768,9 +777,9 @@ func (NamespaceStatus) SwaggerDoc() map[string]string { var map_Node = map[string]string{ "": "Node is a worker node in Kubernetes, formerly known as minion. Each node will have a unique identifier in the cache (i.e. in etcd).", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the behavior of a node. http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Most recently observed status of the node. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of a node. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Most recently observed status of the node. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Node) SwaggerDoc() map[string]string { @@ -822,7 +831,7 @@ func (NodeDaemonEndpoints) SwaggerDoc() map[string]string { var map_NodeList = map[string]string{ "": "NodeList is the whole list of all Nodes which have been registered with master.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of nodes", } @@ -873,7 +882,7 @@ var map_NodeSpec = map[string]string{ "podCIDR": "PodCIDR represents the pod IP range assigned to the node.", "externalID": "External ID of the node assigned by some machine database (e.g. a cloud provider). Deprecated.", "providerID": "ID of the node assigned by the cloud provider in the format: ://", - "unschedulable": "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#manual-node-administration\"`", + "unschedulable": "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#manual-node-administration\"`", } func (NodeSpec) SwaggerDoc() map[string]string { @@ -882,13 +891,13 @@ func (NodeSpec) SwaggerDoc() map[string]string { var map_NodeStatus = map[string]string{ "": "NodeStatus is information about the current status of a node.", - "capacity": "Capacity represents the total resources of a node. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity for more details.", + "capacity": "Capacity represents the total resources of a node. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity for more details.", "allocatable": "Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity.", - "phase": "NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-phase", - "conditions": "Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-condition", - "addresses": "List of addresses reachable to the node. Queried from cloud provider, if available. More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-addresses", + "phase": "NodePhase is the recently observed lifecycle phase of the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-phase", + "conditions": "Conditions is an array of current observed node conditions. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-condition", + "addresses": "List of addresses reachable to the node. Queried from cloud provider, if available. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-addresses", "daemonEndpoints": "Endpoints of daemons running on the Node.", - "nodeInfo": "Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/release-1.3/docs/admin/node.md#node-info", + "nodeInfo": "Set of ids/uuids to uniquely identify the node. More info: http://releases.k8s.io/HEAD/docs/admin/node.md#node-info", "images": "List of container images on this node", "volumesInUse": "List of attachable volumes in use (mounted) by the node.", "volumesAttached": "List of volumes that are attached to the node.", @@ -928,18 +937,18 @@ func (ObjectFieldSelector) SwaggerDoc() map[string]string { var map_ObjectMeta = map[string]string{ "": "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.", - "name": "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", - "generateName": "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).\n\nApplied only if Name is not specified. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#idempotency", - "namespace": "Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md", + "name": "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", + "generateName": "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).\n\nApplied only if Name is not specified. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#idempotency", + "namespace": "Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md", "selfLink": "SelfLink is a URL representing this object. Populated by the system. Read-only.", - "uid": "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids", - "resourceVersion": "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency", + "uid": "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids", + "resourceVersion": "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency", "generation": "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.", - "creationTimestamp": "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "deletionTimestamp": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource will be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field. Once set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. Once the resource is deleted in the API, the Kubelet will send a hard termination signal to the container. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "creationTimestamp": "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "deletionTimestamp": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource will be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field. Once set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. Once the resource is deleted in the API, the Kubelet will send a hard termination signal to the container. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "deletionGracePeriodSeconds": "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.", - "labels": "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md", - "annotations": "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://releases.k8s.io/release-1.3/docs/user-guide/annotations.md", + "labels": "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md", + "annotations": "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://releases.k8s.io/HEAD/docs/user-guide/annotations.md", "ownerReferences": "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.", "finalizers": "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed.", } @@ -950,12 +959,12 @@ func (ObjectMeta) SwaggerDoc() map[string]string { var map_ObjectReference = map[string]string{ "": "ObjectReference contains enough information to let you inspect or modify the referred object.", - "kind": "Kind of the referent. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "namespace": "Namespace of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/namespaces.md", - "name": "Name of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", - "uid": "UID of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids", + "kind": "Kind of the referent. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "namespace": "Namespace of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md", + "name": "Name of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", + "uid": "UID of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids", "apiVersion": "API version of the referent.", - "resourceVersion": "Specific resourceVersion to which this reference is made, if any. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#concurrency-control-and-consistency", + "resourceVersion": "Specific resourceVersion to which this reference is made, if any. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency", "fieldPath": "If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: \"spec.containers{name}\" (where \"name\" refers to the name of the container that triggered the event) or if no container name is specified \"spec.containers[2]\" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object.", } @@ -966,9 +975,9 @@ func (ObjectReference) SwaggerDoc() map[string]string { var map_OwnerReference = map[string]string{ "": "OwnerReference contains enough information to let you identify an owning object. Currently, an owning object must be in the same namespace, so there is no namespace field.", "apiVersion": "API version of the referent.", - "kind": "Kind of the referent. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "name": "Name of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", - "uid": "UID of the referent. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#uids", + "kind": "Kind of the referent. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "name": "Name of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", + "uid": "UID of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids", "controller": "If true, this reference points to the managing controller.", } @@ -977,10 +986,10 @@ func (OwnerReference) SwaggerDoc() map[string]string { } var map_PersistentVolume = map[string]string{ - "": "PersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines a specification of a persistent volume owned by the cluster. Provisioned by an administrator. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes", - "status": "Status represents the current information/status for the persistent volume. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistent-volumes", + "": "PersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines a specification of a persistent volume owned by the cluster. Provisioned by an administrator. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes", + "status": "Status represents the current information/status for the persistent volume. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistent-volumes", } func (PersistentVolume) SwaggerDoc() map[string]string { @@ -989,9 +998,9 @@ func (PersistentVolume) SwaggerDoc() map[string]string { var map_PersistentVolumeClaim = map[string]string{ "": "PersistentVolumeClaim is a user's request for and claim to a persistent volume", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the desired characteristics of a volume requested by a pod author. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", - "status": "Status represents the current information/status of a persistent volume claim. Read-only. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the desired characteristics of a volume requested by a pod author. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", + "status": "Status represents the current information/status of a persistent volume claim. Read-only. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", } func (PersistentVolumeClaim) SwaggerDoc() map[string]string { @@ -1000,8 +1009,8 @@ func (PersistentVolumeClaim) SwaggerDoc() map[string]string { var map_PersistentVolumeClaimList = map[string]string{ "": "PersistentVolumeClaimList is a list of PersistentVolumeClaim items.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "A list of persistent volume claims. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "A list of persistent volume claims. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", } func (PersistentVolumeClaimList) SwaggerDoc() map[string]string { @@ -1010,9 +1019,9 @@ func (PersistentVolumeClaimList) SwaggerDoc() map[string]string { var map_PersistentVolumeClaimSpec = map[string]string{ "": "PersistentVolumeClaimSpec describes the common attributes of storage devices and allows a Source for provider-specific attributes", - "accessModes": "AccessModes contains the desired access modes the volume should have. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1", + "accessModes": "AccessModes contains the desired access modes the volume should have. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1", "selector": "A label query over volumes to consider for binding.", - "resources": "Resources represents the minimum resources the volume should have. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#resources", + "resources": "Resources represents the minimum resources the volume should have. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#resources", "volumeName": "VolumeName is the binding reference to the PersistentVolume backing this claim.", } @@ -1023,7 +1032,7 @@ func (PersistentVolumeClaimSpec) SwaggerDoc() map[string]string { var map_PersistentVolumeClaimStatus = map[string]string{ "": "PersistentVolumeClaimStatus is the current status of a persistent volume claim.", "phase": "Phase represents the current phase of PersistentVolumeClaim.", - "accessModes": "AccessModes contains the actual access modes the volume backing the PVC has. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes-1", + "accessModes": "AccessModes contains the actual access modes the volume backing the PVC has. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes-1", "capacity": "Represents the actual resources of the underlying volume.", } @@ -1033,7 +1042,7 @@ func (PersistentVolumeClaimStatus) SwaggerDoc() map[string]string { var map_PersistentVolumeClaimVolumeSource = map[string]string{ "": "PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. This volume finds the bound PV and mounts that volume for the pod. A PersistentVolumeClaimVolumeSource is, essentially, a wrapper around another type of volume that is owned by someone else (the system).", - "claimName": "ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", + "claimName": "ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", "readOnly": "Will force the ReadOnly setting in VolumeMounts. Default false.", } @@ -1043,8 +1052,8 @@ func (PersistentVolumeClaimVolumeSource) SwaggerDoc() map[string]string { var map_PersistentVolumeList = map[string]string{ "": "PersistentVolumeList is a list of PersistentVolume items.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "List of persistent volumes. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "List of persistent volumes. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md", } func (PersistentVolumeList) SwaggerDoc() map[string]string { @@ -1053,14 +1062,14 @@ func (PersistentVolumeList) SwaggerDoc() map[string]string { var map_PersistentVolumeSource = map[string]string{ "": "PersistentVolumeSource is similar to VolumeSource but meant for the administrator who creates PVs. Exactly one of its members must be set.", - "gcePersistentDisk": "GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", - "awsElasticBlockStore": "AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore", - "hostPath": "HostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath", - "glusterfs": "Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md", - "nfs": "NFS represents an NFS mount on the host. Provisioned by an admin. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs", - "rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md", + "gcePersistentDisk": "GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", + "awsElasticBlockStore": "AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore", + "hostPath": "HostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath", + "glusterfs": "Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md", + "nfs": "NFS represents an NFS mount on the host. Provisioned by an admin. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs", + "rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md", "iscsi": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - "cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md", + "cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", "cephfs": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime", "fc": "FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", "flocker": "Flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", @@ -1075,10 +1084,10 @@ func (PersistentVolumeSource) SwaggerDoc() map[string]string { var map_PersistentVolumeSpec = map[string]string{ "": "PersistentVolumeSpec is the specification of a persistent volume.", - "capacity": "A description of the persistent volume's resources and capacity. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#capacity", - "accessModes": "AccessModes contains all ways the volume can be mounted. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#access-modes", - "claimRef": "ClaimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#binding", - "persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default) and Recycle. Recyling must be supported by the volume plugin underlying this persistent volume. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#recycling-policy", + "capacity": "A description of the persistent volume's resources and capacity. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#capacity", + "accessModes": "AccessModes contains all ways the volume can be mounted. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#access-modes", + "claimRef": "ClaimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#binding", + "persistentVolumeReclaimPolicy": "What happens to a persistent volume when released from its claim. Valid options are Retain (default) and Recycle. Recyling must be supported by the volume plugin underlying this persistent volume. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#recycling-policy", } func (PersistentVolumeSpec) SwaggerDoc() map[string]string { @@ -1087,7 +1096,7 @@ func (PersistentVolumeSpec) SwaggerDoc() map[string]string { var map_PersistentVolumeStatus = map[string]string{ "": "PersistentVolumeStatus is the current status of a persistent volume.", - "phase": "Phase indicates if a volume is available, bound to a claim, or released by a claim. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#phase", + "phase": "Phase indicates if a volume is available, bound to a claim, or released by a claim. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#phase", "message": "A human-readable message indicating details about why the volume is in this state.", "reason": "Reason is a brief CamelCase string that describes any failure and is meant for machine parsing and tidy display in the CLI.", } @@ -1098,9 +1107,9 @@ func (PersistentVolumeStatus) SwaggerDoc() map[string]string { var map_Pod = map[string]string{ "": "Pod is a collection of containers that can run on a host. This resource is created by clients and scheduled onto hosts.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Pod) SwaggerDoc() map[string]string { @@ -1153,8 +1162,8 @@ func (PodAttachOptions) SwaggerDoc() map[string]string { var map_PodCondition = map[string]string{ "": "PodCondition contains details for the current condition of this pod.", - "type": "Type is the type of the condition. Currently only Ready. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions", - "status": "Status is the status of the condition. Can be True, False, Unknown. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions", + "type": "Type is the type of the condition. Currently only Ready. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions", + "status": "Status is the status of the condition. Can be True, False, Unknown. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions", "lastProbeTime": "Last time we probed the condition.", "lastTransitionTime": "Last time the condition transitioned from one status to another.", "reason": "Unique, one-word, CamelCase reason for the condition's last transition.", @@ -1181,8 +1190,8 @@ func (PodExecOptions) SwaggerDoc() map[string]string { var map_PodList = map[string]string{ "": "PodList is a list of Pods.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "List of pods. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pods.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "List of pods. More info: http://releases.k8s.io/HEAD/docs/user-guide/pods.md", } func (PodList) SwaggerDoc() map[string]string { @@ -1227,23 +1236,32 @@ func (PodSecurityContext) SwaggerDoc() map[string]string { return map_PodSecurityContext } +var map_PodSignature = map[string]string{ + "": "Describes the class of pods that should avoid this node. Exactly one field should be set.", + "podController": "Reference to controller whose pods should avoid this node.", +} + +func (PodSignature) SwaggerDoc() map[string]string { + return map_PodSignature +} + var map_PodSpec = map[string]string{ "": "PodSpec is a description of a pod.", - "volumes": "List of volumes that can be mounted by containers belonging to the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md", - "containers": "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/containers.md", - "restartPolicy": "Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#restartpolicy", + "volumes": "List of volumes that can be mounted by containers belonging to the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md", + "containers": "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/containers.md", + "restartPolicy": "Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#restartpolicy", "terminationGracePeriodSeconds": "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", "activeDeadlineSeconds": "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", "dnsPolicy": "Set DNS policy for containers within the pod. One of 'ClusterFirst' or 'Default'. Defaults to \"ClusterFirst\".", - "nodeSelector": "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: http://releases.k8s.io/release-1.3/docs/user-guide/node-selection/README.md", - "serviceAccountName": "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md", + "nodeSelector": "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: http://releases.k8s.io/HEAD/docs/user-guide/node-selection/README.md", + "serviceAccountName": "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md", "serviceAccount": "DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.", "nodeName": "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", "hostNetwork": "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", "hostPID": "Use the host's pid namespace. Optional: Default to false.", "hostIPC": "Use the host's ipc namespace. Optional: Default to false.", "securityContext": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", - "imagePullSecrets": "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://releases.k8s.io/release-1.3/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod", + "imagePullSecrets": "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. For example, in the case of docker, only DockerConfig type secrets are honored. More info: http://releases.k8s.io/HEAD/docs/user-guide/images.md#specifying-imagepullsecrets-on-a-pod", "hostname": "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", "subdomain": "If specified, the fully qualified Pod hostname will be \"...svc.\". If not specified, the pod will not have a domainname at all.", } @@ -1254,14 +1272,14 @@ func (PodSpec) SwaggerDoc() map[string]string { var map_PodStatus = map[string]string{ "": "PodStatus represents information about the status of a pod. Status may trail the actual state of a system.", - "phase": "Current condition of the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-phase", - "conditions": "Current service state of pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#pod-conditions", + "phase": "Current condition of the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-phase", + "conditions": "Current service state of pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#pod-conditions", "message": "A human readable message indicating details about why the pod is in this condition.", "reason": "A brief CamelCase message indicating details about why the pod is in this state. e.g. 'OutOfDisk'", "hostIP": "IP address of the host to which the pod is assigned. Empty if not yet scheduled.", "podIP": "IP address allocated to the pod. Routable at least within the cluster. Empty if not yet allocated.", "startTime": "RFC 3339 date and time at which the object was acknowledged by the Kubelet. This is before the Kubelet pulled the container image(s) for the pod.", - "containerStatuses": "The list has one entry per container in the manifest. Each entry is currently the output of `docker inspect`. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-statuses", + "containerStatuses": "The list has one entry per container in the manifest. Each entry is currently the output of `docker inspect`. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-statuses", } func (PodStatus) SwaggerDoc() map[string]string { @@ -1270,8 +1288,8 @@ func (PodStatus) SwaggerDoc() map[string]string { var map_PodStatusResult = map[string]string{ "": "PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "status": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "status": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (PodStatusResult) SwaggerDoc() map[string]string { @@ -1280,8 +1298,8 @@ func (PodStatusResult) SwaggerDoc() map[string]string { var map_PodTemplate = map[string]string{ "": "PodTemplate describes a template for creating copies of a predefined pod.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "template": "Template defines the pods that will be created from this pod template. http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "template": "Template defines the pods that will be created from this pod template. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (PodTemplate) SwaggerDoc() map[string]string { @@ -1290,7 +1308,7 @@ func (PodTemplate) SwaggerDoc() map[string]string { var map_PodTemplateList = map[string]string{ "": "PodTemplateList is a list of PodTemplates.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of pod templates", } @@ -1300,8 +1318,8 @@ func (PodTemplateList) SwaggerDoc() map[string]string { var map_PodTemplateSpec = map[string]string{ "": "PodTemplateSpec describes the data a pod should have when created from a template", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Specification of the desired behavior of the pod. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (PodTemplateSpec) SwaggerDoc() map[string]string { @@ -1317,6 +1335,18 @@ func (Preconditions) SwaggerDoc() map[string]string { return map_Preconditions } +var map_PreferAvoidPodsEntry = map[string]string{ + "": "Describes a class of pods that should avoid this node.", + "podSignature": "The class of pods.", + "evictionTime": "Time at which this entry was added to the list.", + "reason": "(brief) reason why this entry was added to the list.", + "message": "Human readable message indicating why this entry was added to the list.", +} + +func (PreferAvoidPodsEntry) SwaggerDoc() map[string]string { + return map_PreferAvoidPodsEntry +} + var map_PreferredSchedulingTerm = map[string]string{ "": "An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op).", "weight": "Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.", @@ -1329,8 +1359,8 @@ func (PreferredSchedulingTerm) SwaggerDoc() map[string]string { var map_Probe = map[string]string{ "": "Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.", - "initialDelaySeconds": "Number of seconds after the container has started before liveness probes are initiated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes", - "timeoutSeconds": "Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: http://releases.k8s.io/release-1.3/docs/user-guide/pod-states.md#container-probes", + "initialDelaySeconds": "Number of seconds after the container has started before liveness probes are initiated. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes", + "timeoutSeconds": "Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes", "periodSeconds": "How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.", "successThreshold": "Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness. Minimum value is 1.", "failureThreshold": "Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", @@ -1342,14 +1372,14 @@ func (Probe) SwaggerDoc() map[string]string { var map_RBDVolumeSource = map[string]string{ "": "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - "monitors": "A collection of Ceph monitors. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", - "image": "The rados image name. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", - "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#rbd", - "pool": "The rados pool name. Default is rbd. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it.", - "user": "The rados user name. Default is admin. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", - "keyring": "Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", - "secretRef": "SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", - "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md#how-to-use-it", + "monitors": "A collection of Ceph monitors. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + "image": "The rados image name. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + "fsType": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#rbd", + "pool": "The rados pool name. Default is rbd. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it.", + "user": "The rados user name. Default is admin. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + "keyring": "Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + "secretRef": "SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", + "readOnly": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md#how-to-use-it", } func (RBDVolumeSource) SwaggerDoc() map[string]string { @@ -1358,7 +1388,7 @@ func (RBDVolumeSource) SwaggerDoc() map[string]string { var map_RangeAllocation = map[string]string{ "": "RangeAllocation is not a public type.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "range": "Range is string that identifies the range represented by 'data'.", "data": "Data is a bit array containing all allocated addresses in the previous segment.", } @@ -1369,9 +1399,9 @@ func (RangeAllocation) SwaggerDoc() map[string]string { var map_ReplicationController = map[string]string{ "": "ReplicationController represents the configuration of a replication controller.", - "metadata": "If the Labels of a ReplicationController are empty, they are defaulted to be the same as the Pod(s) that the replication controller manages. Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the specification of the desired behavior of the replication controller. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is the most recently observed status of the replication controller. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "If the Labels of a ReplicationController are empty, they are defaulted to be the same as the Pod(s) that the replication controller manages. Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the specification of the desired behavior of the replication controller. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is the most recently observed status of the replication controller. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (ReplicationController) SwaggerDoc() map[string]string { @@ -1380,8 +1410,8 @@ func (ReplicationController) SwaggerDoc() map[string]string { var map_ReplicationControllerList = map[string]string{ "": "ReplicationControllerList is a collection of replication controllers.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "List of replication controllers. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "List of replication controllers. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md", } func (ReplicationControllerList) SwaggerDoc() map[string]string { @@ -1390,9 +1420,9 @@ func (ReplicationControllerList) SwaggerDoc() map[string]string { var map_ReplicationControllerSpec = map[string]string{ "": "ReplicationControllerSpec is the specification of a replication controller.", - "replicas": "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller", - "selector": "Selector is a label query over pods that should match the Replicas count. If Selector is empty, it is defaulted to the labels present on the Pod template. Label keys and values that must match in order to be controlled by this replication controller, if empty defaulted to labels on Pod template. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "template": "Template is the object that describes the pod that will be created if insufficient replicas are detected. This takes precedence over a TemplateRef. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template", + "replicas": "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", + "selector": "Selector is a label query over pods that should match the Replicas count. If Selector is empty, it is defaulted to the labels present on the Pod template. Label keys and values that must match in order to be controlled by this replication controller, if empty defaulted to labels on Pod template. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "template": "Template is the object that describes the pod that will be created if insufficient replicas are detected. This takes precedence over a TemplateRef. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template", } func (ReplicationControllerSpec) SwaggerDoc() map[string]string { @@ -1401,7 +1431,7 @@ func (ReplicationControllerSpec) SwaggerDoc() map[string]string { var map_ReplicationControllerStatus = map[string]string{ "": "ReplicationControllerStatus represents the current status of a replication controller.", - "replicas": "Replicas is the most recently oberved number of replicas. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller", + "replicas": "Replicas is the most recently oberved number of replicas. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", "fullyLabeledReplicas": "The number of pods that have labels matching the labels of the pod template of the replication controller.", "observedGeneration": "ObservedGeneration reflects the generation of the most recently observed replication controller.", } @@ -1423,9 +1453,9 @@ func (ResourceFieldSelector) SwaggerDoc() map[string]string { var map_ResourceQuota = map[string]string{ "": "ResourceQuota sets aggregate quota restrictions enforced per namespace", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the desired quota. http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status defines the actual enforced quota and its current usage. http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the desired quota. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status defines the actual enforced quota and its current usage. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (ResourceQuota) SwaggerDoc() map[string]string { @@ -1434,8 +1464,8 @@ func (ResourceQuota) SwaggerDoc() map[string]string { var map_ResourceQuotaList = map[string]string{ "": "ResourceQuotaList is a list of ResourceQuota items.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "Items is a list of ResourceQuota objects. More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of ResourceQuota objects. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", } func (ResourceQuotaList) SwaggerDoc() map[string]string { @@ -1444,7 +1474,7 @@ func (ResourceQuotaList) SwaggerDoc() map[string]string { var map_ResourceQuotaSpec = map[string]string{ "": "ResourceQuotaSpec defines the desired hard limits to enforce for Quota.", - "hard": "Hard is the set of desired hard limits for each named resource. More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", + "hard": "Hard is the set of desired hard limits for each named resource. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", "scopes": "A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects.", } @@ -1454,7 +1484,7 @@ func (ResourceQuotaSpec) SwaggerDoc() map[string]string { var map_ResourceQuotaStatus = map[string]string{ "": "ResourceQuotaStatus defines the enforced hard limits and observed use.", - "hard": "Hard is the set of enforced hard limits for each named resource. More info: http://releases.k8s.io/release-1.3/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", + "hard": "Hard is the set of enforced hard limits for each named resource. More info: http://releases.k8s.io/HEAD/docs/design/admission_control_resource_quota.md#admissioncontrol-plugin-resourcequota", "used": "Used is the current observed total usage of the resource in the namespace.", } @@ -1464,8 +1494,8 @@ func (ResourceQuotaStatus) SwaggerDoc() map[string]string { var map_ResourceRequirements = map[string]string{ "": "ResourceRequirements describes the compute resource requirements.", - "limits": "Limits describes the maximum amount of compute resources allowed. More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications", - "requests": "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: http://releases.k8s.io/release-1.3/docs/design/resources.md#resource-specifications", + "limits": "Limits describes the maximum amount of compute resources allowed. More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications", + "requests": "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: http://releases.k8s.io/HEAD/docs/design/resources.md#resource-specifications", } func (ResourceRequirements) SwaggerDoc() map[string]string { @@ -1485,10 +1515,11 @@ func (SELinuxOptions) SwaggerDoc() map[string]string { } var map_Secret = map[string]string{ - "": "Secret holds secret data of a certain type. The total bytes of the values in the Data field must be less than MaxSecretSize bytes.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "data": "Data contains the secret data. Each key must be a valid DNS_SUBDOMAIN or leading dot followed by valid DNS_SUBDOMAIN. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here. Described in https://tools.ietf.org/html/rfc4648#section-4", - "type": "Used to facilitate programmatic handling of secret data.", + "": "Secret holds secret data of a certain type. The total bytes of the values in the Data field must be less than MaxSecretSize bytes.", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "data": "Data contains the secret data. Each key must be a valid DNS_SUBDOMAIN or leading dot followed by valid DNS_SUBDOMAIN. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here. Described in https://tools.ietf.org/html/rfc4648#section-4", + "stringData": "stringData allows specifying non-binary secret data in string form. It is provided as a write-only convenience method. All keys and values are merged into the data field on write, overwriting any existing values. It is never output when reading from the API.", + "type": "Used to facilitate programmatic handling of secret data.", } func (Secret) SwaggerDoc() map[string]string { @@ -1506,8 +1537,8 @@ func (SecretKeySelector) SwaggerDoc() map[string]string { var map_SecretList = map[string]string{ "": "SecretList is a list of Secret.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "Items is a list of secret objects. More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "Items is a list of secret objects. More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md", } func (SecretList) SwaggerDoc() map[string]string { @@ -1516,7 +1547,7 @@ func (SecretList) SwaggerDoc() map[string]string { var map_SecretVolumeSource = map[string]string{ "": "Adapts a Secret into a volume.\n\nThe contents of the target Secret's Data field will be presented in a volume as files using the keys in the Data field as the file names. Secret volumes support ownership management and SELinux relabeling.", - "secretName": "Name of the secret in the pod's namespace to use. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets", + "secretName": "Name of the secret in the pod's namespace to use. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets", "items": "If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error. Paths must be relative and may not contain the '..' path or start with '..'.", } @@ -1549,9 +1580,9 @@ func (SerializedReference) SwaggerDoc() map[string]string { var map_Service = map[string]string{ "": "Service is a named abstraction of software service (for example, mysql) consisting of local port (for example 3306) that the proxy listens on, and the selector that determines which pods will answer requests sent through the proxy.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the behavior of a service. http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Most recently observed status of the service. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the behavior of a service. http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Most recently observed status of the service. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Service) SwaggerDoc() map[string]string { @@ -1560,9 +1591,9 @@ func (Service) SwaggerDoc() map[string]string { var map_ServiceAccount = map[string]string{ "": "ServiceAccount binds together: * a name, understood by users, and perhaps by peripheral systems, for an identity * a principal that can be authenticated and authorized * a set of secrets", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "secrets": "Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md", - "imagePullSecrets": "ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: http://releases.k8s.io/release-1.3/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "secrets": "Secrets is the list of secrets allowed to be used by pods running using this ServiceAccount. More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md", + "imagePullSecrets": "ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: http://releases.k8s.io/HEAD/docs/user-guide/secrets.md#manually-specifying-an-imagepullsecret", } func (ServiceAccount) SwaggerDoc() map[string]string { @@ -1571,8 +1602,8 @@ func (ServiceAccount) SwaggerDoc() map[string]string { var map_ServiceAccountList = map[string]string{ "": "ServiceAccountList is a list of ServiceAccount objects", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "List of ServiceAccounts. More info: http://releases.k8s.io/release-1.3/docs/design/service_accounts.md#service-accounts", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "List of ServiceAccounts. More info: http://releases.k8s.io/HEAD/docs/design/service_accounts.md#service-accounts", } func (ServiceAccountList) SwaggerDoc() map[string]string { @@ -1581,7 +1612,7 @@ func (ServiceAccountList) SwaggerDoc() map[string]string { var map_ServiceList = map[string]string{ "": "ServiceList holds a list of services.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", "items": "List of services", } @@ -1594,8 +1625,8 @@ var map_ServicePort = map[string]string{ "name": "The name of this port within the service. This must be a DNS_LABEL. All ports within a ServiceSpec must have unique names. This maps to the 'Name' field in EndpointPort objects. Optional if only one ServicePort is defined on this service.", "protocol": "The IP protocol for this port. Supports \"TCP\" and \"UDP\". Default is TCP.", "port": "The port that will be exposed by this service.", - "targetPort": "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#defining-a-service", - "nodePort": "The port on each node on which this service is exposed when type=NodePort or LoadBalancer. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the ServiceType of this Service requires one. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#type--nodeport", + "targetPort": "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service", + "nodePort": "The port on each node on which this service is exposed when type=NodePort or LoadBalancer. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the ServiceType of this Service requires one. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#type--nodeport", } func (ServicePort) SwaggerDoc() map[string]string { @@ -1613,15 +1644,15 @@ func (ServiceProxyOptions) SwaggerDoc() map[string]string { var map_ServiceSpec = map[string]string{ "": "ServiceSpec describes the attributes that a user creates on a service.", - "ports": "The list of ports that are exposed by this service. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies", - "selector": "This service will route traffic to pods having labels matching this selector. Label keys and values that must match in order to receive traffic for this service. If empty, all pods are selected, if not specified, endpoints must be manually specified. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#overview", - "clusterIP": "ClusterIP is usually assigned by the master and is the IP address of the service. If specified, it will be allocated to the service if it is unused or else creation of the service will fail. Valid values are None, empty string (\"\"), or a valid IP address. 'None' can be specified for a headless service when proxying is not required. Cannot be updated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies", - "type": "Type of exposed service. Must be ClusterIP, NodePort, or LoadBalancer. Defaults to ClusterIP. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#external-services", + "ports": "The list of ports that are exposed by this service. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies", + "selector": "This service will route traffic to pods having labels matching this selector. Label keys and values that must match in order to receive traffic for this service. If not specified, endpoints must be manually specified and the system will not automatically manage them. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#overview", + "clusterIP": "ClusterIP is usually assigned by the master and is the IP address of the service. If specified, it will be allocated to the service if it is unused or else creation of the service will fail. Valid values are None, empty string (\"\"), or a valid IP address. 'None' can be specified for a headless service when proxying is not required. Cannot be updated. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies", + "type": "Type of exposed service. Must be ClusterIP, NodePort, or LoadBalancer. Defaults to ClusterIP. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#external-services", "externalIPs": "externalIPs is a list of IP addresses for which nodes in the cluster will also accept traffic for this service. These IPs are not managed by Kubernetes. The user is responsible for ensuring that traffic arrives at a node with this IP. A common example is external load-balancers that are not part of the Kubernetes system. A previous form of this functionality exists as the deprecatedPublicIPs field. When using this field, callers should also clear the deprecatedPublicIPs field.", "deprecatedPublicIPs": "deprecatedPublicIPs is deprecated and replaced by the externalIPs field with almost the exact same semantics. This field is retained in the v1 API for compatibility until at least 8/20/2016. It will be removed from any new API revisions. If both deprecatedPublicIPs *and* externalIPs are set, deprecatedPublicIPs is used.", - "sessionAffinity": "Supports \"ClientIP\" and \"None\". Used to maintain session affinity. Enable client IP based session affinity. Must be ClientIP or None. Defaults to None. More info: http://releases.k8s.io/release-1.3/docs/user-guide/services.md#virtual-ips-and-service-proxies", + "sessionAffinity": "Supports \"ClientIP\" and \"None\". Used to maintain session affinity. Enable client IP based session affinity. Must be ClientIP or None. Defaults to None. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#virtual-ips-and-service-proxies", "loadBalancerIP": "Only applies to Service Type: LoadBalancer LoadBalancer will get created with the IP specified in this field. This feature depends on whether the underlying cloud-provider supports specifying the loadBalancerIP when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature.", - "loadBalancerSourceRanges": "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature.\" More info: http://releases.k8s.io/release-1.3/docs/user-guide/services-firewalls.md", + "loadBalancerSourceRanges": "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature.\" More info: http://releases.k8s.io/HEAD/docs/user-guide/services-firewalls.md", } func (ServiceSpec) SwaggerDoc() map[string]string { @@ -1671,7 +1702,7 @@ func (Toleration) SwaggerDoc() map[string]string { var map_Volume = map[string]string{ "": "Volume represents a named volume in a pod that may be accessed by any container in the pod.", - "name": "Volume's name. Must be a DNS_LABEL and unique within the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", + "name": "Volume's name. Must be a DNS_LABEL and unique within the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", } func (Volume) SwaggerDoc() map[string]string { @@ -1692,19 +1723,19 @@ func (VolumeMount) SwaggerDoc() map[string]string { var map_VolumeSource = map[string]string{ "": "Represents the source of a volume to mount. Only one of its members may be specified.", - "hostPath": "HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#hostpath", - "emptyDir": "EmptyDir represents a temporary directory that shares a pod's lifetime. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#emptydir", - "gcePersistentDisk": "GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#gcepersistentdisk", - "awsElasticBlockStore": "AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#awselasticblockstore", + "hostPath": "HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#hostpath", + "emptyDir": "EmptyDir represents a temporary directory that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#emptydir", + "gcePersistentDisk": "GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#gcepersistentdisk", + "awsElasticBlockStore": "AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#awselasticblockstore", "gitRepo": "GitRepo represents a git repository at a particular revision.", - "secret": "Secret represents a secret that should populate this volume. More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#secrets", - "nfs": "NFS represents an NFS mount on the host that shares a pod's lifetime More info: http://releases.k8s.io/release-1.3/docs/user-guide/volumes.md#nfs", - "iscsi": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/release-1.3/examples/iscsi/README.md", - "glusterfs": "Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/release-1.3/examples/glusterfs/README.md", - "persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: http://releases.k8s.io/release-1.3/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", - "rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/release-1.3/examples/rbd/README.md", + "secret": "Secret represents a secret that should populate this volume. More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#secrets", + "nfs": "NFS represents an NFS mount on the host that shares a pod's lifetime More info: http://releases.k8s.io/HEAD/docs/user-guide/volumes.md#nfs", + "iscsi": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: http://releases.k8s.io/HEAD/examples/volumes/iscsi/README.md", + "glusterfs": "Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md", + "persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: http://releases.k8s.io/HEAD/docs/user-guide/persistent-volumes.md#persistentvolumeclaims", + "rbd": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: http://releases.k8s.io/HEAD/examples/volumes/rbd/README.md", "flexVolume": "FlexVolume represents a generic volume resource that is provisioned/attached using a exec based plugin. This is an alpha feature and may change in future.", - "cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/release-1.3/examples/mysql-cinder-pd/README.md", + "cinder": "Cinder represents a cinder volume attached and mounted on kubelets host machine More info: http://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md", "cephfs": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime", "flocker": "Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running", "downwardAPI": "DownwardAPI represents downward API about the pod that should populate this volume", diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.conversion.go similarity index 96% rename from vendor/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.conversion.go index d3aad15522e4..8517c697789e 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import ( resource "k8s.io/kubernetes/pkg/api/resource" conversion "k8s.io/kubernetes/pkg/conversion" runtime "k8s.io/kubernetes/pkg/runtime" + types "k8s.io/kubernetes/pkg/types" ) func init() { @@ -35,6 +36,8 @@ func init() { Convert_api_Affinity_To_v1_Affinity, Convert_v1_AttachedVolume_To_api_AttachedVolume, Convert_api_AttachedVolume_To_v1_AttachedVolume, + Convert_v1_AvoidPods_To_api_AvoidPods, + Convert_api_AvoidPods_To_v1_AvoidPods, Convert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource, Convert_api_AzureFileVolumeSource_To_v1_AzureFileVolumeSource, Convert_v1_Binding_To_api_Binding, @@ -239,6 +242,8 @@ func init() { Convert_api_PodProxyOptions_To_v1_PodProxyOptions, Convert_v1_PodSecurityContext_To_api_PodSecurityContext, Convert_api_PodSecurityContext_To_v1_PodSecurityContext, + Convert_v1_PodSignature_To_api_PodSignature, + Convert_api_PodSignature_To_v1_PodSignature, Convert_v1_PodSpec_To_api_PodSpec, Convert_api_PodSpec_To_v1_PodSpec, Convert_v1_PodStatus_To_api_PodStatus, @@ -253,6 +258,8 @@ func init() { Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec, Convert_v1_Preconditions_To_api_Preconditions, Convert_api_Preconditions_To_v1_Preconditions, + Convert_v1_PreferAvoidPodsEntry_To_api_PreferAvoidPodsEntry, + Convert_api_PreferAvoidPodsEntry_To_v1_PreferAvoidPodsEntry, Convert_v1_PreferredSchedulingTerm_To_api_PreferredSchedulingTerm, Convert_api_PreferredSchedulingTerm_To_v1_PreferredSchedulingTerm, Convert_v1_Probe_To_api_Probe, @@ -447,6 +454,44 @@ func Convert_api_AttachedVolume_To_v1_AttachedVolume(in *api.AttachedVolume, out return autoConvert_api_AttachedVolume_To_v1_AttachedVolume(in, out, s) } +func autoConvert_v1_AvoidPods_To_api_AvoidPods(in *AvoidPods, out *api.AvoidPods, s conversion.Scope) error { + if in.PreferAvoidPods != nil { + in, out := &in.PreferAvoidPods, &out.PreferAvoidPods + *out = make([]api.PreferAvoidPodsEntry, len(*in)) + for i := range *in { + if err := Convert_v1_PreferAvoidPodsEntry_To_api_PreferAvoidPodsEntry(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.PreferAvoidPods = nil + } + return nil +} + +func Convert_v1_AvoidPods_To_api_AvoidPods(in *AvoidPods, out *api.AvoidPods, s conversion.Scope) error { + return autoConvert_v1_AvoidPods_To_api_AvoidPods(in, out, s) +} + +func autoConvert_api_AvoidPods_To_v1_AvoidPods(in *api.AvoidPods, out *AvoidPods, s conversion.Scope) error { + if in.PreferAvoidPods != nil { + in, out := &in.PreferAvoidPods, &out.PreferAvoidPods + *out = make([]PreferAvoidPodsEntry, len(*in)) + for i := range *in { + if err := Convert_api_PreferAvoidPodsEntry_To_v1_PreferAvoidPodsEntry(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.PreferAvoidPods = nil + } + return nil +} + +func Convert_api_AvoidPods_To_v1_AvoidPods(in *api.AvoidPods, out *AvoidPods, s conversion.Scope) error { + return autoConvert_api_AvoidPods_To_v1_AvoidPods(in, out, s) +} + func autoConvert_v1_AzureFileVolumeSource_To_api_AzureFileVolumeSource(in *AzureFileVolumeSource, out *api.AzureFileVolumeSource, s conversion.Scope) error { out.SecretName = in.SecretName out.ShareName = in.ShareName @@ -3593,7 +3638,7 @@ func autoConvert_v1_ObjectMeta_To_api_ObjectMeta(in *ObjectMeta, out *api.Object out.GenerateName = in.GenerateName out.Namespace = in.Namespace out.SelfLink = in.SelfLink - out.UID = in.UID + out.UID = types.UID(in.UID) out.ResourceVersion = in.ResourceVersion out.Generation = in.Generation if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.CreationTimestamp, &out.CreationTimestamp, s); err != nil { @@ -3627,7 +3672,7 @@ func autoConvert_api_ObjectMeta_To_v1_ObjectMeta(in *api.ObjectMeta, out *Object out.GenerateName = in.GenerateName out.Namespace = in.Namespace out.SelfLink = in.SelfLink - out.UID = in.UID + out.UID = types.UID(in.UID) out.ResourceVersion = in.ResourceVersion out.Generation = in.Generation if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.CreationTimestamp, &out.CreationTimestamp, s); err != nil { @@ -3660,7 +3705,7 @@ func autoConvert_v1_ObjectReference_To_api_ObjectReference(in *ObjectReference, out.Kind = in.Kind out.Namespace = in.Namespace out.Name = in.Name - out.UID = in.UID + out.UID = types.UID(in.UID) out.APIVersion = in.APIVersion out.ResourceVersion = in.ResourceVersion out.FieldPath = in.FieldPath @@ -3675,7 +3720,7 @@ func autoConvert_api_ObjectReference_To_v1_ObjectReference(in *api.ObjectReferen out.Kind = in.Kind out.Namespace = in.Namespace out.Name = in.Name - out.UID = in.UID + out.UID = types.UID(in.UID) out.APIVersion = in.APIVersion out.ResourceVersion = in.ResourceVersion out.FieldPath = in.FieldPath @@ -3690,7 +3735,7 @@ func autoConvert_v1_OwnerReference_To_api_OwnerReference(in *OwnerReference, out out.APIVersion = in.APIVersion out.Kind = in.Kind out.Name = in.Name - out.UID = in.UID + out.UID = types.UID(in.UID) out.Controller = in.Controller return nil } @@ -3703,7 +3748,7 @@ func autoConvert_api_OwnerReference_To_v1_OwnerReference(in *api.OwnerReference, out.APIVersion = in.APIVersion out.Kind = in.Kind out.Name = in.Name - out.UID = in.UID + out.UID = types.UID(in.UID) out.Controller = in.Controller return nil } @@ -4784,6 +4829,124 @@ func autoConvert_v1_PodSecurityContext_To_api_PodSecurityContext(in *PodSecurity return nil } +func autoConvert_api_PodSecurityContext_To_v1_PodSecurityContext(in *api.PodSecurityContext, out *PodSecurityContext, s conversion.Scope) error { + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(SELinuxOptions) + if err := Convert_api_SELinuxOptions_To_v1_SELinuxOptions(*in, *out, s); err != nil { + return err + } + } else { + out.SELinuxOptions = nil + } + out.RunAsUser = in.RunAsUser + out.RunAsNonRoot = in.RunAsNonRoot + out.SupplementalGroups = in.SupplementalGroups + out.FSGroup = in.FSGroup + return nil +} + +func autoConvert_v1_PodSignature_To_api_PodSignature(in *PodSignature, out *api.PodSignature, s conversion.Scope) error { + if in.PodController != nil { + in, out := &in.PodController, &out.PodController + *out = new(api.OwnerReference) + if err := Convert_v1_OwnerReference_To_api_OwnerReference(*in, *out, s); err != nil { + return err + } + } else { + out.PodController = nil + } + return nil +} + +func Convert_v1_PodSignature_To_api_PodSignature(in *PodSignature, out *api.PodSignature, s conversion.Scope) error { + return autoConvert_v1_PodSignature_To_api_PodSignature(in, out, s) +} + +func autoConvert_api_PodSignature_To_v1_PodSignature(in *api.PodSignature, out *PodSignature, s conversion.Scope) error { + if in.PodController != nil { + in, out := &in.PodController, &out.PodController + *out = new(OwnerReference) + if err := Convert_api_OwnerReference_To_v1_OwnerReference(*in, *out, s); err != nil { + return err + } + } else { + out.PodController = nil + } + return nil +} + +func Convert_api_PodSignature_To_v1_PodSignature(in *api.PodSignature, out *PodSignature, s conversion.Scope) error { + return autoConvert_api_PodSignature_To_v1_PodSignature(in, out, s) +} + +func autoConvert_v1_PodSpec_To_api_PodSpec(in *PodSpec, out *api.PodSpec, s conversion.Scope) error { + SetDefaults_PodSpec(in) + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]api.Volume, len(*in)) + for i := range *in { + if err := Convert_v1_Volume_To_api_Volume(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Volumes = nil + } + if in.InitContainers != nil { + in, out := &in.InitContainers, &out.InitContainers + *out = make([]api.Container, len(*in)) + for i := range *in { + if err := Convert_v1_Container_To_api_Container(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.InitContainers = nil + } + if in.Containers != nil { + in, out := &in.Containers, &out.Containers + *out = make([]api.Container, len(*in)) + for i := range *in { + if err := Convert_v1_Container_To_api_Container(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Containers = nil + } + out.RestartPolicy = api.RestartPolicy(in.RestartPolicy) + out.TerminationGracePeriodSeconds = in.TerminationGracePeriodSeconds + out.ActiveDeadlineSeconds = in.ActiveDeadlineSeconds + out.DNSPolicy = api.DNSPolicy(in.DNSPolicy) + out.NodeSelector = in.NodeSelector + out.ServiceAccountName = in.ServiceAccountName + out.NodeName = in.NodeName + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(api.PodSecurityContext) + if err := Convert_v1_PodSecurityContext_To_api_PodSecurityContext(*in, *out, s); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + if in.ImagePullSecrets != nil { + in, out := &in.ImagePullSecrets, &out.ImagePullSecrets + *out = make([]api.LocalObjectReference, len(*in)) + for i := range *in { + if err := Convert_v1_LocalObjectReference_To_api_LocalObjectReference(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.ImagePullSecrets = nil + } + out.Hostname = in.Hostname + out.Subdomain = in.Subdomain + return nil +} + func autoConvert_api_PodSpec_To_v1_PodSpec(in *api.PodSpec, out *PodSpec, s conversion.Scope) error { if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes @@ -5092,6 +5255,38 @@ func Convert_api_Preconditions_To_v1_Preconditions(in *api.Preconditions, out *P return autoConvert_api_Preconditions_To_v1_Preconditions(in, out, s) } +func autoConvert_v1_PreferAvoidPodsEntry_To_api_PreferAvoidPodsEntry(in *PreferAvoidPodsEntry, out *api.PreferAvoidPodsEntry, s conversion.Scope) error { + if err := Convert_v1_PodSignature_To_api_PodSignature(&in.PodSignature, &out.PodSignature, s); err != nil { + return err + } + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.EvictionTime, &out.EvictionTime, s); err != nil { + return err + } + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +func Convert_v1_PreferAvoidPodsEntry_To_api_PreferAvoidPodsEntry(in *PreferAvoidPodsEntry, out *api.PreferAvoidPodsEntry, s conversion.Scope) error { + return autoConvert_v1_PreferAvoidPodsEntry_To_api_PreferAvoidPodsEntry(in, out, s) +} + +func autoConvert_api_PreferAvoidPodsEntry_To_v1_PreferAvoidPodsEntry(in *api.PreferAvoidPodsEntry, out *PreferAvoidPodsEntry, s conversion.Scope) error { + if err := Convert_api_PodSignature_To_v1_PodSignature(&in.PodSignature, &out.PodSignature, s); err != nil { + return err + } + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.EvictionTime, &out.EvictionTime, s); err != nil { + return err + } + out.Reason = in.Reason + out.Message = in.Message + return nil +} + +func Convert_api_PreferAvoidPodsEntry_To_v1_PreferAvoidPodsEntry(in *api.PreferAvoidPodsEntry, out *PreferAvoidPodsEntry, s conversion.Scope) error { + return autoConvert_api_PreferAvoidPodsEntry_To_v1_PreferAvoidPodsEntry(in, out, s) +} + func autoConvert_v1_PreferredSchedulingTerm_To_api_PreferredSchedulingTerm(in *PreferredSchedulingTerm, out *api.PreferredSchedulingTerm, s conversion.Scope) error { out.Weight = in.Weight if err := Convert_v1_NodeSelectorTerm_To_api_NodeSelectorTerm(&in.Preference, &out.Preference, s); err != nil { @@ -5325,6 +5520,40 @@ func Convert_api_ReplicationControllerList_To_v1_ReplicationControllerList(in *a return autoConvert_api_ReplicationControllerList_To_v1_ReplicationControllerList(in, out, s) } +func autoConvert_v1_ReplicationControllerSpec_To_api_ReplicationControllerSpec(in *ReplicationControllerSpec, out *api.ReplicationControllerSpec, s conversion.Scope) error { + if err := api.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + out.Selector = in.Selector + if in.Template != nil { + in, out := &in.Template, &out.Template + *out = new(api.PodTemplateSpec) + if err := Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(*in, *out, s); err != nil { + return err + } + } else { + out.Template = nil + } + return nil +} + +func autoConvert_api_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *api.ReplicationControllerSpec, out *ReplicationControllerSpec, s conversion.Scope) error { + if err := api.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + out.Selector = in.Selector + if in.Template != nil { + in, out := &in.Template, &out.Template + *out = new(PodTemplateSpec) + if err := Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(*in, *out, s); err != nil { + return err + } + } else { + out.Template = nil + } + return nil +} + func autoConvert_v1_ReplicationControllerStatus_To_api_ReplicationControllerStatus(in *ReplicationControllerStatus, out *api.ReplicationControllerStatus, s conversion.Scope) error { out.Replicas = in.Replicas out.FullyLabeledReplicas = in.FullyLabeledReplicas @@ -5646,10 +5875,6 @@ func autoConvert_v1_Secret_To_api_Secret(in *Secret, out *api.Secret, s conversi return nil } -func Convert_v1_Secret_To_api_Secret(in *Secret, out *api.Secret, s conversion.Scope) error { - return autoConvert_v1_Secret_To_api_Secret(in, out, s) -} - func autoConvert_api_Secret_To_v1_Secret(in *api.Secret, out *Secret, s conversion.Scope) error { if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { return err diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..8af6eae707c2 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/api/v1/zz_generated.deepcopy.go @@ -0,0 +1,3574 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + runtime "k8s.io/kubernetes/pkg/runtime" + types "k8s.io/kubernetes/pkg/types" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_AWSElasticBlockStoreVolumeSource, InType: reflect.TypeOf(func() *AWSElasticBlockStoreVolumeSource { var x *AWSElasticBlockStoreVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Affinity, InType: reflect.TypeOf(func() *Affinity { var x *Affinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_AttachedVolume, InType: reflect.TypeOf(func() *AttachedVolume { var x *AttachedVolume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_AvoidPods, InType: reflect.TypeOf(func() *AvoidPods { var x *AvoidPods; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_AzureFileVolumeSource, InType: reflect.TypeOf(func() *AzureFileVolumeSource { var x *AzureFileVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Binding, InType: reflect.TypeOf(func() *Binding { var x *Binding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Capabilities, InType: reflect.TypeOf(func() *Capabilities { var x *Capabilities; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_CephFSVolumeSource, InType: reflect.TypeOf(func() *CephFSVolumeSource { var x *CephFSVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_CinderVolumeSource, InType: reflect.TypeOf(func() *CinderVolumeSource { var x *CinderVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ComponentCondition, InType: reflect.TypeOf(func() *ComponentCondition { var x *ComponentCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ComponentStatus, InType: reflect.TypeOf(func() *ComponentStatus { var x *ComponentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ComponentStatusList, InType: reflect.TypeOf(func() *ComponentStatusList { var x *ComponentStatusList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ConfigMap, InType: reflect.TypeOf(func() *ConfigMap { var x *ConfigMap; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ConfigMapKeySelector, InType: reflect.TypeOf(func() *ConfigMapKeySelector { var x *ConfigMapKeySelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ConfigMapList, InType: reflect.TypeOf(func() *ConfigMapList { var x *ConfigMapList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ConfigMapVolumeSource, InType: reflect.TypeOf(func() *ConfigMapVolumeSource { var x *ConfigMapVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Container, InType: reflect.TypeOf(func() *Container { var x *Container; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerImage, InType: reflect.TypeOf(func() *ContainerImage { var x *ContainerImage; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerPort, InType: reflect.TypeOf(func() *ContainerPort { var x *ContainerPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerState, InType: reflect.TypeOf(func() *ContainerState { var x *ContainerState; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerStateRunning, InType: reflect.TypeOf(func() *ContainerStateRunning { var x *ContainerStateRunning; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerStateTerminated, InType: reflect.TypeOf(func() *ContainerStateTerminated { var x *ContainerStateTerminated; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerStateWaiting, InType: reflect.TypeOf(func() *ContainerStateWaiting { var x *ContainerStateWaiting; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ContainerStatus, InType: reflect.TypeOf(func() *ContainerStatus { var x *ContainerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_DaemonEndpoint, InType: reflect.TypeOf(func() *DaemonEndpoint { var x *DaemonEndpoint; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_DeleteOptions, InType: reflect.TypeOf(func() *DeleteOptions { var x *DeleteOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_DownwardAPIVolumeFile, InType: reflect.TypeOf(func() *DownwardAPIVolumeFile { var x *DownwardAPIVolumeFile; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_DownwardAPIVolumeSource, InType: reflect.TypeOf(func() *DownwardAPIVolumeSource { var x *DownwardAPIVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EmptyDirVolumeSource, InType: reflect.TypeOf(func() *EmptyDirVolumeSource { var x *EmptyDirVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EndpointAddress, InType: reflect.TypeOf(func() *EndpointAddress { var x *EndpointAddress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EndpointPort, InType: reflect.TypeOf(func() *EndpointPort { var x *EndpointPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EndpointSubset, InType: reflect.TypeOf(func() *EndpointSubset { var x *EndpointSubset; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Endpoints, InType: reflect.TypeOf(func() *Endpoints { var x *Endpoints; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EndpointsList, InType: reflect.TypeOf(func() *EndpointsList { var x *EndpointsList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EnvVar, InType: reflect.TypeOf(func() *EnvVar { var x *EnvVar; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EnvVarSource, InType: reflect.TypeOf(func() *EnvVarSource { var x *EnvVarSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Event, InType: reflect.TypeOf(func() *Event { var x *Event; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EventList, InType: reflect.TypeOf(func() *EventList { var x *EventList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_EventSource, InType: reflect.TypeOf(func() *EventSource { var x *EventSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ExecAction, InType: reflect.TypeOf(func() *ExecAction { var x *ExecAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ExportOptions, InType: reflect.TypeOf(func() *ExportOptions { var x *ExportOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_FCVolumeSource, InType: reflect.TypeOf(func() *FCVolumeSource { var x *FCVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_FlexVolumeSource, InType: reflect.TypeOf(func() *FlexVolumeSource { var x *FlexVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_FlockerVolumeSource, InType: reflect.TypeOf(func() *FlockerVolumeSource { var x *FlockerVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_GCEPersistentDiskVolumeSource, InType: reflect.TypeOf(func() *GCEPersistentDiskVolumeSource { var x *GCEPersistentDiskVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_GitRepoVolumeSource, InType: reflect.TypeOf(func() *GitRepoVolumeSource { var x *GitRepoVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_GlusterfsVolumeSource, InType: reflect.TypeOf(func() *GlusterfsVolumeSource { var x *GlusterfsVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HTTPGetAction, InType: reflect.TypeOf(func() *HTTPGetAction { var x *HTTPGetAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HTTPHeader, InType: reflect.TypeOf(func() *HTTPHeader { var x *HTTPHeader; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Handler, InType: reflect.TypeOf(func() *Handler { var x *Handler; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HostPathVolumeSource, InType: reflect.TypeOf(func() *HostPathVolumeSource { var x *HostPathVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ISCSIVolumeSource, InType: reflect.TypeOf(func() *ISCSIVolumeSource { var x *ISCSIVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_KeyToPath, InType: reflect.TypeOf(func() *KeyToPath { var x *KeyToPath; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Lifecycle, InType: reflect.TypeOf(func() *Lifecycle { var x *Lifecycle; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LimitRange, InType: reflect.TypeOf(func() *LimitRange { var x *LimitRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LimitRangeItem, InType: reflect.TypeOf(func() *LimitRangeItem { var x *LimitRangeItem; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LimitRangeList, InType: reflect.TypeOf(func() *LimitRangeList { var x *LimitRangeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LimitRangeSpec, InType: reflect.TypeOf(func() *LimitRangeSpec { var x *LimitRangeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_List, InType: reflect.TypeOf(func() *List { var x *List; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ListOptions, InType: reflect.TypeOf(func() *ListOptions { var x *ListOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LoadBalancerIngress, InType: reflect.TypeOf(func() *LoadBalancerIngress { var x *LoadBalancerIngress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LoadBalancerStatus, InType: reflect.TypeOf(func() *LoadBalancerStatus { var x *LoadBalancerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LocalObjectReference, InType: reflect.TypeOf(func() *LocalObjectReference { var x *LocalObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NFSVolumeSource, InType: reflect.TypeOf(func() *NFSVolumeSource { var x *NFSVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Namespace, InType: reflect.TypeOf(func() *Namespace { var x *Namespace; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NamespaceList, InType: reflect.TypeOf(func() *NamespaceList { var x *NamespaceList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NamespaceSpec, InType: reflect.TypeOf(func() *NamespaceSpec { var x *NamespaceSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NamespaceStatus, InType: reflect.TypeOf(func() *NamespaceStatus { var x *NamespaceStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Node, InType: reflect.TypeOf(func() *Node { var x *Node; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeAddress, InType: reflect.TypeOf(func() *NodeAddress { var x *NodeAddress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeAffinity, InType: reflect.TypeOf(func() *NodeAffinity { var x *NodeAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeCondition, InType: reflect.TypeOf(func() *NodeCondition { var x *NodeCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeDaemonEndpoints, InType: reflect.TypeOf(func() *NodeDaemonEndpoints { var x *NodeDaemonEndpoints; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeList, InType: reflect.TypeOf(func() *NodeList { var x *NodeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeProxyOptions, InType: reflect.TypeOf(func() *NodeProxyOptions { var x *NodeProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelector, InType: reflect.TypeOf(func() *NodeSelector { var x *NodeSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelectorRequirement, InType: reflect.TypeOf(func() *NodeSelectorRequirement { var x *NodeSelectorRequirement; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSelectorTerm, InType: reflect.TypeOf(func() *NodeSelectorTerm { var x *NodeSelectorTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSpec, InType: reflect.TypeOf(func() *NodeSpec { var x *NodeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeStatus, InType: reflect.TypeOf(func() *NodeStatus { var x *NodeStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_NodeSystemInfo, InType: reflect.TypeOf(func() *NodeSystemInfo { var x *NodeSystemInfo; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ObjectFieldSelector, InType: reflect.TypeOf(func() *ObjectFieldSelector { var x *ObjectFieldSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ObjectMeta, InType: reflect.TypeOf(func() *ObjectMeta { var x *ObjectMeta; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ObjectReference, InType: reflect.TypeOf(func() *ObjectReference { var x *ObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_OwnerReference, InType: reflect.TypeOf(func() *OwnerReference { var x *OwnerReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolume, InType: reflect.TypeOf(func() *PersistentVolume { var x *PersistentVolume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeClaim, InType: reflect.TypeOf(func() *PersistentVolumeClaim { var x *PersistentVolumeClaim; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeClaimList, InType: reflect.TypeOf(func() *PersistentVolumeClaimList { var x *PersistentVolumeClaimList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeClaimSpec, InType: reflect.TypeOf(func() *PersistentVolumeClaimSpec { var x *PersistentVolumeClaimSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeClaimStatus, InType: reflect.TypeOf(func() *PersistentVolumeClaimStatus { var x *PersistentVolumeClaimStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeClaimVolumeSource, InType: reflect.TypeOf(func() *PersistentVolumeClaimVolumeSource { var x *PersistentVolumeClaimVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeList, InType: reflect.TypeOf(func() *PersistentVolumeList { var x *PersistentVolumeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeSource, InType: reflect.TypeOf(func() *PersistentVolumeSource { var x *PersistentVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeSpec, InType: reflect.TypeOf(func() *PersistentVolumeSpec { var x *PersistentVolumeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PersistentVolumeStatus, InType: reflect.TypeOf(func() *PersistentVolumeStatus { var x *PersistentVolumeStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Pod, InType: reflect.TypeOf(func() *Pod { var x *Pod; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodAffinity, InType: reflect.TypeOf(func() *PodAffinity { var x *PodAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodAffinityTerm, InType: reflect.TypeOf(func() *PodAffinityTerm { var x *PodAffinityTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodAntiAffinity, InType: reflect.TypeOf(func() *PodAntiAffinity { var x *PodAntiAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodAttachOptions, InType: reflect.TypeOf(func() *PodAttachOptions { var x *PodAttachOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodCondition, InType: reflect.TypeOf(func() *PodCondition { var x *PodCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodExecOptions, InType: reflect.TypeOf(func() *PodExecOptions { var x *PodExecOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodList, InType: reflect.TypeOf(func() *PodList { var x *PodList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodLogOptions, InType: reflect.TypeOf(func() *PodLogOptions { var x *PodLogOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodProxyOptions, InType: reflect.TypeOf(func() *PodProxyOptions { var x *PodProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodSecurityContext, InType: reflect.TypeOf(func() *PodSecurityContext { var x *PodSecurityContext; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodSignature, InType: reflect.TypeOf(func() *PodSignature { var x *PodSignature; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodSpec, InType: reflect.TypeOf(func() *PodSpec { var x *PodSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodStatus, InType: reflect.TypeOf(func() *PodStatus { var x *PodStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodStatusResult, InType: reflect.TypeOf(func() *PodStatusResult { var x *PodStatusResult; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodTemplate, InType: reflect.TypeOf(func() *PodTemplate { var x *PodTemplate; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodTemplateList, InType: reflect.TypeOf(func() *PodTemplateList { var x *PodTemplateList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PodTemplateSpec, InType: reflect.TypeOf(func() *PodTemplateSpec { var x *PodTemplateSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Preconditions, InType: reflect.TypeOf(func() *Preconditions { var x *Preconditions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PreferAvoidPodsEntry, InType: reflect.TypeOf(func() *PreferAvoidPodsEntry { var x *PreferAvoidPodsEntry; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_PreferredSchedulingTerm, InType: reflect.TypeOf(func() *PreferredSchedulingTerm { var x *PreferredSchedulingTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Probe, InType: reflect.TypeOf(func() *Probe { var x *Probe; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_RBDVolumeSource, InType: reflect.TypeOf(func() *RBDVolumeSource { var x *RBDVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_RangeAllocation, InType: reflect.TypeOf(func() *RangeAllocation { var x *RangeAllocation; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ReplicationController, InType: reflect.TypeOf(func() *ReplicationController { var x *ReplicationController; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ReplicationControllerList, InType: reflect.TypeOf(func() *ReplicationControllerList { var x *ReplicationControllerList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ReplicationControllerSpec, InType: reflect.TypeOf(func() *ReplicationControllerSpec { var x *ReplicationControllerSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ReplicationControllerStatus, InType: reflect.TypeOf(func() *ReplicationControllerStatus { var x *ReplicationControllerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceFieldSelector, InType: reflect.TypeOf(func() *ResourceFieldSelector { var x *ResourceFieldSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceQuota, InType: reflect.TypeOf(func() *ResourceQuota { var x *ResourceQuota; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceQuotaList, InType: reflect.TypeOf(func() *ResourceQuotaList { var x *ResourceQuotaList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceQuotaSpec, InType: reflect.TypeOf(func() *ResourceQuotaSpec { var x *ResourceQuotaSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceQuotaStatus, InType: reflect.TypeOf(func() *ResourceQuotaStatus { var x *ResourceQuotaStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ResourceRequirements, InType: reflect.TypeOf(func() *ResourceRequirements { var x *ResourceRequirements; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SELinuxOptions, InType: reflect.TypeOf(func() *SELinuxOptions { var x *SELinuxOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Secret, InType: reflect.TypeOf(func() *Secret { var x *Secret; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SecretKeySelector, InType: reflect.TypeOf(func() *SecretKeySelector { var x *SecretKeySelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SecretList, InType: reflect.TypeOf(func() *SecretList { var x *SecretList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SecretVolumeSource, InType: reflect.TypeOf(func() *SecretVolumeSource { var x *SecretVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SecurityContext, InType: reflect.TypeOf(func() *SecurityContext { var x *SecurityContext; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_SerializedReference, InType: reflect.TypeOf(func() *SerializedReference { var x *SerializedReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Service, InType: reflect.TypeOf(func() *Service { var x *Service; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceAccount, InType: reflect.TypeOf(func() *ServiceAccount { var x *ServiceAccount; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceAccountList, InType: reflect.TypeOf(func() *ServiceAccountList { var x *ServiceAccountList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceList, InType: reflect.TypeOf(func() *ServiceList { var x *ServiceList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServicePort, InType: reflect.TypeOf(func() *ServicePort { var x *ServicePort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceProxyOptions, InType: reflect.TypeOf(func() *ServiceProxyOptions { var x *ServiceProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceSpec, InType: reflect.TypeOf(func() *ServiceSpec { var x *ServiceSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ServiceStatus, InType: reflect.TypeOf(func() *ServiceStatus { var x *ServiceStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_TCPSocketAction, InType: reflect.TypeOf(func() *TCPSocketAction { var x *TCPSocketAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Taint, InType: reflect.TypeOf(func() *Taint { var x *Taint; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Toleration, InType: reflect.TypeOf(func() *Toleration { var x *Toleration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Volume, InType: reflect.TypeOf(func() *Volume { var x *Volume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_VolumeMount, InType: reflect.TypeOf(func() *VolumeMount { var x *VolumeMount; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_VolumeSource, InType: reflect.TypeOf(func() *VolumeSource { var x *VolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_VsphereVirtualDiskVolumeSource, InType: reflect.TypeOf(func() *VsphereVirtualDiskVolumeSource { var x *VsphereVirtualDiskVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_WeightedPodAffinityTerm, InType: reflect.TypeOf(func() *WeightedPodAffinityTerm { var x *WeightedPodAffinityTerm; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1_AWSElasticBlockStoreVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AWSElasticBlockStoreVolumeSource) + out := out.(*AWSElasticBlockStoreVolumeSource) + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.Partition = in.Partition + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_Affinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Affinity) + out := out.(*Affinity) + if in.NodeAffinity != nil { + in, out := &in.NodeAffinity, &out.NodeAffinity + *out = new(NodeAffinity) + if err := DeepCopy_v1_NodeAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.NodeAffinity = nil + } + if in.PodAffinity != nil { + in, out := &in.PodAffinity, &out.PodAffinity + *out = new(PodAffinity) + if err := DeepCopy_v1_PodAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.PodAffinity = nil + } + if in.PodAntiAffinity != nil { + in, out := &in.PodAntiAffinity, &out.PodAntiAffinity + *out = new(PodAntiAffinity) + if err := DeepCopy_v1_PodAntiAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.PodAntiAffinity = nil + } + return nil + } +} + +func DeepCopy_v1_AttachedVolume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AttachedVolume) + out := out.(*AttachedVolume) + out.Name = in.Name + out.DevicePath = in.DevicePath + return nil + } +} + +func DeepCopy_v1_AvoidPods(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AvoidPods) + out := out.(*AvoidPods) + if in.PreferAvoidPods != nil { + in, out := &in.PreferAvoidPods, &out.PreferAvoidPods + *out = make([]PreferAvoidPodsEntry, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PreferAvoidPodsEntry(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferAvoidPods = nil + } + return nil + } +} + +func DeepCopy_v1_AzureFileVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AzureFileVolumeSource) + out := out.(*AzureFileVolumeSource) + out.SecretName = in.SecretName + out.ShareName = in.ShareName + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_Binding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Binding) + out := out.(*Binding) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Target = in.Target + return nil + } +} + +func DeepCopy_v1_Capabilities(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Capabilities) + out := out.(*Capabilities) + if in.Add != nil { + in, out := &in.Add, &out.Add + *out = make([]Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Add = nil + } + if in.Drop != nil { + in, out := &in.Drop, &out.Drop + *out = make([]Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Drop = nil + } + return nil + } +} + +func DeepCopy_v1_CephFSVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CephFSVolumeSource) + out := out.(*CephFSVolumeSource) + if in.Monitors != nil { + in, out := &in.Monitors, &out.Monitors + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Monitors = nil + } + out.Path = in.Path + out.User = in.User + out.SecretFile = in.SecretFile + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_CinderVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CinderVolumeSource) + out := out.(*CinderVolumeSource) + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_ComponentCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentCondition) + out := out.(*ComponentCondition) + out.Type = in.Type + out.Status = in.Status + out.Message = in.Message + out.Error = in.Error + return nil + } +} + +func DeepCopy_v1_ComponentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentStatus) + out := out.(*ComponentStatus) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]ComponentCondition, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Conditions = nil + } + return nil + } +} + +func DeepCopy_v1_ComponentStatusList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentStatusList) + out := out.(*ComponentStatusList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ComponentStatus, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ComponentStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ConfigMap(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMap) + out := out.(*ConfigMap) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_v1_ConfigMapKeySelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapKeySelector) + out := out.(*ConfigMapKeySelector) + out.LocalObjectReference = in.LocalObjectReference + out.Key = in.Key + return nil + } +} + +func DeepCopy_v1_ConfigMapList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapList) + out := out.(*ConfigMapList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConfigMap, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ConfigMap(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ConfigMapVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapVolumeSource) + out := out.(*ConfigMapVolumeSource) + out.LocalObjectReference = in.LocalObjectReference + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KeyToPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_Container(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Container) + out := out.(*Container) + out.Name = in.Name + out.Image = in.Image + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + if in.Args != nil { + in, out := &in.Args, &out.Args + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Args = nil + } + out.WorkingDir = in.WorkingDir + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]ContainerPort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]EnvVar, len(*in)) + for i := range *in { + if err := DeepCopy_v1_EnvVar(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Env = nil + } + if err := DeepCopy_v1_ResourceRequirements(&in.Resources, &out.Resources, c); err != nil { + return err + } + if in.VolumeMounts != nil { + in, out := &in.VolumeMounts, &out.VolumeMounts + *out = make([]VolumeMount, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumeMounts = nil + } + if in.LivenessProbe != nil { + in, out := &in.LivenessProbe, &out.LivenessProbe + *out = new(Probe) + if err := DeepCopy_v1_Probe(*in, *out, c); err != nil { + return err + } + } else { + out.LivenessProbe = nil + } + if in.ReadinessProbe != nil { + in, out := &in.ReadinessProbe, &out.ReadinessProbe + *out = new(Probe) + if err := DeepCopy_v1_Probe(*in, *out, c); err != nil { + return err + } + } else { + out.ReadinessProbe = nil + } + if in.Lifecycle != nil { + in, out := &in.Lifecycle, &out.Lifecycle + *out = new(Lifecycle) + if err := DeepCopy_v1_Lifecycle(*in, *out, c); err != nil { + return err + } + } else { + out.Lifecycle = nil + } + out.TerminationMessagePath = in.TerminationMessagePath + out.ImagePullPolicy = in.ImagePullPolicy + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(SecurityContext) + if err := DeepCopy_v1_SecurityContext(*in, *out, c); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + out.Stdin = in.Stdin + out.StdinOnce = in.StdinOnce + out.TTY = in.TTY + return nil + } +} + +func DeepCopy_v1_ContainerImage(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerImage) + out := out.(*ContainerImage) + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Names = nil + } + out.SizeBytes = in.SizeBytes + return nil + } +} + +func DeepCopy_v1_ContainerPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerPort) + out := out.(*ContainerPort) + out.Name = in.Name + out.HostPort = in.HostPort + out.ContainerPort = in.ContainerPort + out.Protocol = in.Protocol + out.HostIP = in.HostIP + return nil + } +} + +func DeepCopy_v1_ContainerState(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerState) + out := out.(*ContainerState) + if in.Waiting != nil { + in, out := &in.Waiting, &out.Waiting + *out = new(ContainerStateWaiting) + **out = **in + } else { + out.Waiting = nil + } + if in.Running != nil { + in, out := &in.Running, &out.Running + *out = new(ContainerStateRunning) + if err := DeepCopy_v1_ContainerStateRunning(*in, *out, c); err != nil { + return err + } + } else { + out.Running = nil + } + if in.Terminated != nil { + in, out := &in.Terminated, &out.Terminated + *out = new(ContainerStateTerminated) + if err := DeepCopy_v1_ContainerStateTerminated(*in, *out, c); err != nil { + return err + } + } else { + out.Terminated = nil + } + return nil + } +} + +func DeepCopy_v1_ContainerStateRunning(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateRunning) + out := out.(*ContainerStateRunning) + out.StartedAt = in.StartedAt.DeepCopy() + return nil + } +} + +func DeepCopy_v1_ContainerStateTerminated(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateTerminated) + out := out.(*ContainerStateTerminated) + out.ExitCode = in.ExitCode + out.Signal = in.Signal + out.Reason = in.Reason + out.Message = in.Message + out.StartedAt = in.StartedAt.DeepCopy() + out.FinishedAt = in.FinishedAt.DeepCopy() + out.ContainerID = in.ContainerID + return nil + } +} + +func DeepCopy_v1_ContainerStateWaiting(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateWaiting) + out := out.(*ContainerStateWaiting) + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1_ContainerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStatus) + out := out.(*ContainerStatus) + out.Name = in.Name + if err := DeepCopy_v1_ContainerState(&in.State, &out.State, c); err != nil { + return err + } + if err := DeepCopy_v1_ContainerState(&in.LastTerminationState, &out.LastTerminationState, c); err != nil { + return err + } + out.Ready = in.Ready + out.RestartCount = in.RestartCount + out.Image = in.Image + out.ImageID = in.ImageID + out.ContainerID = in.ContainerID + return nil + } +} + +func DeepCopy_v1_DaemonEndpoint(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonEndpoint) + out := out.(*DaemonEndpoint) + out.Port = in.Port + return nil + } +} + +func DeepCopy_v1_DeleteOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeleteOptions) + out := out.(*DeleteOptions) + out.TypeMeta = in.TypeMeta + if in.GracePeriodSeconds != nil { + in, out := &in.GracePeriodSeconds, &out.GracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.GracePeriodSeconds = nil + } + if in.Preconditions != nil { + in, out := &in.Preconditions, &out.Preconditions + *out = new(Preconditions) + if err := DeepCopy_v1_Preconditions(*in, *out, c); err != nil { + return err + } + } else { + out.Preconditions = nil + } + if in.OrphanDependents != nil { + in, out := &in.OrphanDependents, &out.OrphanDependents + *out = new(bool) + **out = **in + } else { + out.OrphanDependents = nil + } + return nil + } +} + +func DeepCopy_v1_DownwardAPIVolumeFile(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DownwardAPIVolumeFile) + out := out.(*DownwardAPIVolumeFile) + out.Path = in.Path + if in.FieldRef != nil { + in, out := &in.FieldRef, &out.FieldRef + *out = new(ObjectFieldSelector) + **out = **in + } else { + out.FieldRef = nil + } + if in.ResourceFieldRef != nil { + in, out := &in.ResourceFieldRef, &out.ResourceFieldRef + *out = new(ResourceFieldSelector) + if err := DeepCopy_v1_ResourceFieldSelector(*in, *out, c); err != nil { + return err + } + } else { + out.ResourceFieldRef = nil + } + return nil + } +} + +func DeepCopy_v1_DownwardAPIVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DownwardAPIVolumeSource) + out := out.(*DownwardAPIVolumeSource) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DownwardAPIVolumeFile, len(*in)) + for i := range *in { + if err := DeepCopy_v1_DownwardAPIVolumeFile(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_EmptyDirVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EmptyDirVolumeSource) + out := out.(*EmptyDirVolumeSource) + out.Medium = in.Medium + return nil + } +} + +func DeepCopy_v1_EndpointAddress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointAddress) + out := out.(*EndpointAddress) + out.IP = in.IP + out.Hostname = in.Hostname + if in.TargetRef != nil { + in, out := &in.TargetRef, &out.TargetRef + *out = new(ObjectReference) + **out = **in + } else { + out.TargetRef = nil + } + return nil + } +} + +func DeepCopy_v1_EndpointPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointPort) + out := out.(*EndpointPort) + out.Name = in.Name + out.Port = in.Port + out.Protocol = in.Protocol + return nil + } +} + +func DeepCopy_v1_EndpointSubset(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointSubset) + out := out.(*EndpointSubset) + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]EndpointAddress, len(*in)) + for i := range *in { + if err := DeepCopy_v1_EndpointAddress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Addresses = nil + } + if in.NotReadyAddresses != nil { + in, out := &in.NotReadyAddresses, &out.NotReadyAddresses + *out = make([]EndpointAddress, len(*in)) + for i := range *in { + if err := DeepCopy_v1_EndpointAddress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.NotReadyAddresses = nil + } + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]EndpointPort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + return nil + } +} + +func DeepCopy_v1_Endpoints(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Endpoints) + out := out.(*Endpoints) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subsets != nil { + in, out := &in.Subsets, &out.Subsets + *out = make([]EndpointSubset, len(*in)) + for i := range *in { + if err := DeepCopy_v1_EndpointSubset(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Subsets = nil + } + return nil + } +} + +func DeepCopy_v1_EndpointsList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointsList) + out := out.(*EndpointsList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Endpoints, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Endpoints(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_EnvVar(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EnvVar) + out := out.(*EnvVar) + out.Name = in.Name + out.Value = in.Value + if in.ValueFrom != nil { + in, out := &in.ValueFrom, &out.ValueFrom + *out = new(EnvVarSource) + if err := DeepCopy_v1_EnvVarSource(*in, *out, c); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil + } +} + +func DeepCopy_v1_EnvVarSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EnvVarSource) + out := out.(*EnvVarSource) + if in.FieldRef != nil { + in, out := &in.FieldRef, &out.FieldRef + *out = new(ObjectFieldSelector) + **out = **in + } else { + out.FieldRef = nil + } + if in.ResourceFieldRef != nil { + in, out := &in.ResourceFieldRef, &out.ResourceFieldRef + *out = new(ResourceFieldSelector) + if err := DeepCopy_v1_ResourceFieldSelector(*in, *out, c); err != nil { + return err + } + } else { + out.ResourceFieldRef = nil + } + if in.ConfigMapKeyRef != nil { + in, out := &in.ConfigMapKeyRef, &out.ConfigMapKeyRef + *out = new(ConfigMapKeySelector) + **out = **in + } else { + out.ConfigMapKeyRef = nil + } + if in.SecretKeyRef != nil { + in, out := &in.SecretKeyRef, &out.SecretKeyRef + *out = new(SecretKeySelector) + **out = **in + } else { + out.SecretKeyRef = nil + } + return nil + } +} + +func DeepCopy_v1_Event(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Event) + out := out.(*Event) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.InvolvedObject = in.InvolvedObject + out.Reason = in.Reason + out.Message = in.Message + out.Source = in.Source + out.FirstTimestamp = in.FirstTimestamp.DeepCopy() + out.LastTimestamp = in.LastTimestamp.DeepCopy() + out.Count = in.Count + out.Type = in.Type + return nil + } +} + +func DeepCopy_v1_EventList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EventList) + out := out.(*EventList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Event, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Event(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_EventSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EventSource) + out := out.(*EventSource) + out.Component = in.Component + out.Host = in.Host + return nil + } +} + +func DeepCopy_v1_ExecAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExecAction) + out := out.(*ExecAction) + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + return nil + } +} + +func DeepCopy_v1_ExportOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExportOptions) + out := out.(*ExportOptions) + out.TypeMeta = in.TypeMeta + out.Export = in.Export + out.Exact = in.Exact + return nil + } +} + +func DeepCopy_v1_FCVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FCVolumeSource) + out := out.(*FCVolumeSource) + if in.TargetWWNs != nil { + in, out := &in.TargetWWNs, &out.TargetWWNs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.TargetWWNs = nil + } + if in.Lun != nil { + in, out := &in.Lun, &out.Lun + *out = new(int32) + **out = **in + } else { + out.Lun = nil + } + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_FlexVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FlexVolumeSource) + out := out.(*FlexVolumeSource) + out.Driver = in.Driver + out.FSType = in.FSType + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + if in.Options != nil { + in, out := &in.Options, &out.Options + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Options = nil + } + return nil + } +} + +func DeepCopy_v1_FlockerVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FlockerVolumeSource) + out := out.(*FlockerVolumeSource) + out.DatasetName = in.DatasetName + return nil + } +} + +func DeepCopy_v1_GCEPersistentDiskVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GCEPersistentDiskVolumeSource) + out := out.(*GCEPersistentDiskVolumeSource) + out.PDName = in.PDName + out.FSType = in.FSType + out.Partition = in.Partition + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_GitRepoVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GitRepoVolumeSource) + out := out.(*GitRepoVolumeSource) + out.Repository = in.Repository + out.Revision = in.Revision + out.Directory = in.Directory + return nil + } +} + +func DeepCopy_v1_GlusterfsVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GlusterfsVolumeSource) + out := out.(*GlusterfsVolumeSource) + out.EndpointsName = in.EndpointsName + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_HTTPGetAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPGetAction) + out := out.(*HTTPGetAction) + out.Path = in.Path + out.Port = in.Port + out.Host = in.Host + out.Scheme = in.Scheme + if in.HTTPHeaders != nil { + in, out := &in.HTTPHeaders, &out.HTTPHeaders + *out = make([]HTTPHeader, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.HTTPHeaders = nil + } + return nil + } +} + +func DeepCopy_v1_HTTPHeader(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPHeader) + out := out.(*HTTPHeader) + out.Name = in.Name + out.Value = in.Value + return nil + } +} + +func DeepCopy_v1_Handler(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Handler) + out := out.(*Handler) + if in.Exec != nil { + in, out := &in.Exec, &out.Exec + *out = new(ExecAction) + if err := DeepCopy_v1_ExecAction(*in, *out, c); err != nil { + return err + } + } else { + out.Exec = nil + } + if in.HTTPGet != nil { + in, out := &in.HTTPGet, &out.HTTPGet + *out = new(HTTPGetAction) + if err := DeepCopy_v1_HTTPGetAction(*in, *out, c); err != nil { + return err + } + } else { + out.HTTPGet = nil + } + if in.TCPSocket != nil { + in, out := &in.TCPSocket, &out.TCPSocket + *out = new(TCPSocketAction) + **out = **in + } else { + out.TCPSocket = nil + } + return nil + } +} + +func DeepCopy_v1_HostPathVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HostPathVolumeSource) + out := out.(*HostPathVolumeSource) + out.Path = in.Path + return nil + } +} + +func DeepCopy_v1_ISCSIVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ISCSIVolumeSource) + out := out.(*ISCSIVolumeSource) + out.TargetPortal = in.TargetPortal + out.IQN = in.IQN + out.Lun = in.Lun + out.ISCSIInterface = in.ISCSIInterface + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_KeyToPath(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KeyToPath) + out := out.(*KeyToPath) + out.Key = in.Key + out.Path = in.Path + return nil + } +} + +func DeepCopy_v1_Lifecycle(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Lifecycle) + out := out.(*Lifecycle) + if in.PostStart != nil { + in, out := &in.PostStart, &out.PostStart + *out = new(Handler) + if err := DeepCopy_v1_Handler(*in, *out, c); err != nil { + return err + } + } else { + out.PostStart = nil + } + if in.PreStop != nil { + in, out := &in.PreStop, &out.PreStop + *out = new(Handler) + if err := DeepCopy_v1_Handler(*in, *out, c); err != nil { + return err + } + } else { + out.PreStop = nil + } + return nil + } +} + +func DeepCopy_v1_LimitRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRange) + out := out.(*LimitRange) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_LimitRangeSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_LimitRangeItem(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeItem) + out := out.(*LimitRangeItem) + out.Type = in.Type + if in.Max != nil { + in, out := &in.Max, &out.Max + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Max = nil + } + if in.Min != nil { + in, out := &in.Min, &out.Min + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Min = nil + } + if in.Default != nil { + in, out := &in.Default, &out.Default + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Default = nil + } + if in.DefaultRequest != nil { + in, out := &in.DefaultRequest, &out.DefaultRequest + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.DefaultRequest = nil + } + if in.MaxLimitRequestRatio != nil { + in, out := &in.MaxLimitRequestRatio, &out.MaxLimitRequestRatio + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.MaxLimitRequestRatio = nil + } + return nil + } +} + +func DeepCopy_v1_LimitRangeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeList) + out := out.(*LimitRangeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]LimitRange, len(*in)) + for i := range *in { + if err := DeepCopy_v1_LimitRange(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_LimitRangeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeSpec) + out := out.(*LimitRangeSpec) + if in.Limits != nil { + in, out := &in.Limits, &out.Limits + *out = make([]LimitRangeItem, len(*in)) + for i := range *in { + if err := DeepCopy_v1_LimitRangeItem(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Limits = nil + } + return nil + } +} + +func DeepCopy_v1_List(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*List) + out := out.(*List) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]runtime.RawExtension, len(*in)) + for i := range *in { + if err := runtime.DeepCopy_runtime_RawExtension(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ListOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ListOptions) + out := out.(*ListOptions) + out.TypeMeta = in.TypeMeta + out.LabelSelector = in.LabelSelector + out.FieldSelector = in.FieldSelector + out.Watch = in.Watch + out.ResourceVersion = in.ResourceVersion + if in.TimeoutSeconds != nil { + in, out := &in.TimeoutSeconds, &out.TimeoutSeconds + *out = new(int64) + **out = **in + } else { + out.TimeoutSeconds = nil + } + return nil + } +} + +func DeepCopy_v1_LoadBalancerIngress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LoadBalancerIngress) + out := out.(*LoadBalancerIngress) + out.IP = in.IP + out.Hostname = in.Hostname + return nil + } +} + +func DeepCopy_v1_LoadBalancerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LoadBalancerStatus) + out := out.(*LoadBalancerStatus) + if in.Ingress != nil { + in, out := &in.Ingress, &out.Ingress + *out = make([]LoadBalancerIngress, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ingress = nil + } + return nil + } +} + +func DeepCopy_v1_LocalObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LocalObjectReference) + out := out.(*LocalObjectReference) + out.Name = in.Name + return nil + } +} + +func DeepCopy_v1_NFSVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NFSVolumeSource) + out := out.(*NFSVolumeSource) + out.Server = in.Server + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_Namespace(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Namespace) + out := out.(*Namespace) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_NamespaceSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1_NamespaceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceList) + out := out.(*NamespaceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Namespace, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Namespace(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_NamespaceSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceSpec) + out := out.(*NamespaceSpec) + if in.Finalizers != nil { + in, out := &in.Finalizers, &out.Finalizers + *out = make([]FinalizerName, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Finalizers = nil + } + return nil + } +} + +func DeepCopy_v1_NamespaceStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceStatus) + out := out.(*NamespaceStatus) + out.Phase = in.Phase + return nil + } +} + +func DeepCopy_v1_Node(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Node) + out := out.(*Node) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + if err := DeepCopy_v1_NodeStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_NodeAddress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeAddress) + out := out.(*NodeAddress) + out.Type = in.Type + out.Address = in.Address + return nil + } +} + +func DeepCopy_v1_NodeAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeAffinity) + out := out.(*NodeAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = new(NodeSelector) + if err := DeepCopy_v1_NodeSelector(*in, *out, c); err != nil { + return err + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]PreferredSchedulingTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PreferredSchedulingTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_v1_NodeCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeCondition) + out := out.(*NodeCondition) + out.Type = in.Type + out.Status = in.Status + out.LastHeartbeatTime = in.LastHeartbeatTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1_NodeDaemonEndpoints(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeDaemonEndpoints) + out := out.(*NodeDaemonEndpoints) + out.KubeletEndpoint = in.KubeletEndpoint + return nil + } +} + +func DeepCopy_v1_NodeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeList) + out := out.(*NodeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Node, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Node(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_NodeProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeProxyOptions) + out := out.(*NodeProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_v1_NodeSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelector) + out := out.(*NodeSelector) + if in.NodeSelectorTerms != nil { + in, out := &in.NodeSelectorTerms, &out.NodeSelectorTerms + *out = make([]NodeSelectorTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_NodeSelectorTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.NodeSelectorTerms = nil + } + return nil + } +} + +func DeepCopy_v1_NodeSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelectorRequirement) + out := out.(*NodeSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} + +func DeepCopy_v1_NodeSelectorTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelectorTerm) + out := out.(*NodeSelectorTerm) + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]NodeSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_v1_NodeSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_v1_NodeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSpec) + out := out.(*NodeSpec) + out.PodCIDR = in.PodCIDR + out.ExternalID = in.ExternalID + out.ProviderID = in.ProviderID + out.Unschedulable = in.Unschedulable + return nil + } +} + +func DeepCopy_v1_NodeStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeStatus) + out := out.(*NodeStatus) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + if in.Allocatable != nil { + in, out := &in.Allocatable, &out.Allocatable + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Allocatable = nil + } + out.Phase = in.Phase + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]NodeCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v1_NodeCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]NodeAddress, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Addresses = nil + } + out.DaemonEndpoints = in.DaemonEndpoints + out.NodeInfo = in.NodeInfo + if in.Images != nil { + in, out := &in.Images, &out.Images + *out = make([]ContainerImage, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ContainerImage(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Images = nil + } + if in.VolumesInUse != nil { + in, out := &in.VolumesInUse, &out.VolumesInUse + *out = make([]UniqueVolumeName, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumesInUse = nil + } + if in.VolumesAttached != nil { + in, out := &in.VolumesAttached, &out.VolumesAttached + *out = make([]AttachedVolume, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumesAttached = nil + } + return nil + } +} + +func DeepCopy_v1_NodeSystemInfo(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSystemInfo) + out := out.(*NodeSystemInfo) + out.MachineID = in.MachineID + out.SystemUUID = in.SystemUUID + out.BootID = in.BootID + out.KernelVersion = in.KernelVersion + out.OSImage = in.OSImage + out.ContainerRuntimeVersion = in.ContainerRuntimeVersion + out.KubeletVersion = in.KubeletVersion + out.KubeProxyVersion = in.KubeProxyVersion + out.OperatingSystem = in.OperatingSystem + out.Architecture = in.Architecture + return nil + } +} + +func DeepCopy_v1_ObjectFieldSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectFieldSelector) + out := out.(*ObjectFieldSelector) + out.APIVersion = in.APIVersion + out.FieldPath = in.FieldPath + return nil + } +} + +func DeepCopy_v1_ObjectMeta(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectMeta) + out := out.(*ObjectMeta) + out.Name = in.Name + out.GenerateName = in.GenerateName + out.Namespace = in.Namespace + out.SelfLink = in.SelfLink + out.UID = in.UID + out.ResourceVersion = in.ResourceVersion + out.Generation = in.Generation + out.CreationTimestamp = in.CreationTimestamp.DeepCopy() + if in.DeletionTimestamp != nil { + in, out := &in.DeletionTimestamp, &out.DeletionTimestamp + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.DeletionTimestamp = nil + } + if in.DeletionGracePeriodSeconds != nil { + in, out := &in.DeletionGracePeriodSeconds, &out.DeletionGracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.DeletionGracePeriodSeconds = nil + } + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Labels = nil + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Annotations = nil + } + if in.OwnerReferences != nil { + in, out := &in.OwnerReferences, &out.OwnerReferences + *out = make([]OwnerReference, len(*in)) + for i := range *in { + if err := DeepCopy_v1_OwnerReference(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.OwnerReferences = nil + } + if in.Finalizers != nil { + in, out := &in.Finalizers, &out.Finalizers + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Finalizers = nil + } + return nil + } +} + +func DeepCopy_v1_ObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectReference) + out := out.(*ObjectReference) + out.Kind = in.Kind + out.Namespace = in.Namespace + out.Name = in.Name + out.UID = in.UID + out.APIVersion = in.APIVersion + out.ResourceVersion = in.ResourceVersion + out.FieldPath = in.FieldPath + return nil + } +} + +func DeepCopy_v1_OwnerReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*OwnerReference) + out := out.(*OwnerReference) + out.APIVersion = in.APIVersion + out.Kind = in.Kind + out.Name = in.Name + out.UID = in.UID + if in.Controller != nil { + in, out := &in.Controller, &out.Controller + *out = new(bool) + **out = **in + } else { + out.Controller = nil + } + return nil + } +} + +func DeepCopy_v1_PersistentVolume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolume) + out := out.(*PersistentVolume) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PersistentVolumeSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1_PersistentVolumeClaim(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaim) + out := out.(*PersistentVolumeClaim) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PersistentVolumeClaimSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_PersistentVolumeClaimStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_PersistentVolumeClaimList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimList) + out := out.(*PersistentVolumeClaimList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PersistentVolumeClaim, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PersistentVolumeClaim(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_PersistentVolumeClaimSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimSpec) + out := out.(*PersistentVolumeClaimSpec) + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := DeepCopy_v1_ResourceRequirements(&in.Resources, &out.Resources, c); err != nil { + return err + } + out.VolumeName = in.VolumeName + return nil + } +} + +func DeepCopy_v1_PersistentVolumeClaimStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimStatus) + out := out.(*PersistentVolumeClaimStatus) + out.Phase = in.Phase + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + return nil + } +} + +func DeepCopy_v1_PersistentVolumeClaimVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimVolumeSource) + out := out.(*PersistentVolumeClaimVolumeSource) + out.ClaimName = in.ClaimName + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_PersistentVolumeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeList) + out := out.(*PersistentVolumeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PersistentVolume, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PersistentVolume(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_PersistentVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeSource) + out := out.(*PersistentVolumeSource) + if in.GCEPersistentDisk != nil { + in, out := &in.GCEPersistentDisk, &out.GCEPersistentDisk + *out = new(GCEPersistentDiskVolumeSource) + **out = **in + } else { + out.GCEPersistentDisk = nil + } + if in.AWSElasticBlockStore != nil { + in, out := &in.AWSElasticBlockStore, &out.AWSElasticBlockStore + *out = new(AWSElasticBlockStoreVolumeSource) + **out = **in + } else { + out.AWSElasticBlockStore = nil + } + if in.HostPath != nil { + in, out := &in.HostPath, &out.HostPath + *out = new(HostPathVolumeSource) + **out = **in + } else { + out.HostPath = nil + } + if in.Glusterfs != nil { + in, out := &in.Glusterfs, &out.Glusterfs + *out = new(GlusterfsVolumeSource) + **out = **in + } else { + out.Glusterfs = nil + } + if in.NFS != nil { + in, out := &in.NFS, &out.NFS + *out = new(NFSVolumeSource) + **out = **in + } else { + out.NFS = nil + } + if in.RBD != nil { + in, out := &in.RBD, &out.RBD + *out = new(RBDVolumeSource) + if err := DeepCopy_v1_RBDVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.RBD = nil + } + if in.ISCSI != nil { + in, out := &in.ISCSI, &out.ISCSI + *out = new(ISCSIVolumeSource) + **out = **in + } else { + out.ISCSI = nil + } + if in.Cinder != nil { + in, out := &in.Cinder, &out.Cinder + *out = new(CinderVolumeSource) + **out = **in + } else { + out.Cinder = nil + } + if in.CephFS != nil { + in, out := &in.CephFS, &out.CephFS + *out = new(CephFSVolumeSource) + if err := DeepCopy_v1_CephFSVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.CephFS = nil + } + if in.FC != nil { + in, out := &in.FC, &out.FC + *out = new(FCVolumeSource) + if err := DeepCopy_v1_FCVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FC = nil + } + if in.Flocker != nil { + in, out := &in.Flocker, &out.Flocker + *out = new(FlockerVolumeSource) + **out = **in + } else { + out.Flocker = nil + } + if in.FlexVolume != nil { + in, out := &in.FlexVolume, &out.FlexVolume + *out = new(FlexVolumeSource) + if err := DeepCopy_v1_FlexVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + if in.AzureFile != nil { + in, out := &in.AzureFile, &out.AzureFile + *out = new(AzureFileVolumeSource) + **out = **in + } else { + out.AzureFile = nil + } + if in.VsphereVolume != nil { + in, out := &in.VsphereVolume, &out.VsphereVolume + *out = new(VsphereVirtualDiskVolumeSource) + **out = **in + } else { + out.VsphereVolume = nil + } + return nil + } +} + +func DeepCopy_v1_PersistentVolumeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeSpec) + out := out.(*PersistentVolumeSpec) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + if err := DeepCopy_v1_PersistentVolumeSource(&in.PersistentVolumeSource, &out.PersistentVolumeSource, c); err != nil { + return err + } + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.ClaimRef != nil { + in, out := &in.ClaimRef, &out.ClaimRef + *out = new(ObjectReference) + **out = **in + } else { + out.ClaimRef = nil + } + out.PersistentVolumeReclaimPolicy = in.PersistentVolumeReclaimPolicy + return nil + } +} + +func DeepCopy_v1_PersistentVolumeStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeStatus) + out := out.(*PersistentVolumeStatus) + out.Phase = in.Phase + out.Message = in.Message + out.Reason = in.Reason + return nil + } +} + +func DeepCopy_v1_Pod(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Pod) + out := out.(*Pod) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PodSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_PodStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_PodAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAffinity) + out := out.(*PodAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = make([]PodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]WeightedPodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_WeightedPodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_v1_PodAffinityTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAffinityTerm) + out := out.(*PodAffinityTerm) + if in.LabelSelector != nil { + in, out := &in.LabelSelector, &out.LabelSelector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.LabelSelector = nil + } + if in.Namespaces != nil { + in, out := &in.Namespaces, &out.Namespaces + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Namespaces = nil + } + out.TopologyKey = in.TopologyKey + return nil + } +} + +func DeepCopy_v1_PodAntiAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAntiAffinity) + out := out.(*PodAntiAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = make([]PodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]WeightedPodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_v1_WeightedPodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_v1_PodAttachOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAttachOptions) + out := out.(*PodAttachOptions) + out.TypeMeta = in.TypeMeta + out.Stdin = in.Stdin + out.Stdout = in.Stdout + out.Stderr = in.Stderr + out.TTY = in.TTY + out.Container = in.Container + return nil + } +} + +func DeepCopy_v1_PodCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodCondition) + out := out.(*PodCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1_PodExecOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodExecOptions) + out := out.(*PodExecOptions) + out.TypeMeta = in.TypeMeta + out.Stdin = in.Stdin + out.Stdout = in.Stdout + out.Stderr = in.Stderr + out.TTY = in.TTY + out.Container = in.Container + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + return nil + } +} + +func DeepCopy_v1_PodList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodList) + out := out.(*PodList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Pod, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Pod(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_PodLogOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodLogOptions) + out := out.(*PodLogOptions) + out.TypeMeta = in.TypeMeta + out.Container = in.Container + out.Follow = in.Follow + out.Previous = in.Previous + if in.SinceSeconds != nil { + in, out := &in.SinceSeconds, &out.SinceSeconds + *out = new(int64) + **out = **in + } else { + out.SinceSeconds = nil + } + if in.SinceTime != nil { + in, out := &in.SinceTime, &out.SinceTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.SinceTime = nil + } + out.Timestamps = in.Timestamps + if in.TailLines != nil { + in, out := &in.TailLines, &out.TailLines + *out = new(int64) + **out = **in + } else { + out.TailLines = nil + } + if in.LimitBytes != nil { + in, out := &in.LimitBytes, &out.LimitBytes + *out = new(int64) + **out = **in + } else { + out.LimitBytes = nil + } + return nil + } +} + +func DeepCopy_v1_PodProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodProxyOptions) + out := out.(*PodProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_v1_PodSecurityContext(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityContext) + out := out.(*PodSecurityContext) + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + in, out := &in.RunAsUser, &out.RunAsUser + *out = new(int64) + **out = **in + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + in, out := &in.RunAsNonRoot, &out.RunAsNonRoot + *out = new(bool) + **out = **in + } else { + out.RunAsNonRoot = nil + } + if in.SupplementalGroups != nil { + in, out := &in.SupplementalGroups, &out.SupplementalGroups + *out = make([]int64, len(*in)) + copy(*out, *in) + } else { + out.SupplementalGroups = nil + } + if in.FSGroup != nil { + in, out := &in.FSGroup, &out.FSGroup + *out = new(int64) + **out = **in + } else { + out.FSGroup = nil + } + return nil + } +} + +func DeepCopy_v1_PodSignature(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSignature) + out := out.(*PodSignature) + if in.PodController != nil { + in, out := &in.PodController, &out.PodController + *out = new(OwnerReference) + if err := DeepCopy_v1_OwnerReference(*in, *out, c); err != nil { + return err + } + } else { + out.PodController = nil + } + return nil + } +} + +func DeepCopy_v1_PodSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSpec) + out := out.(*PodSpec) + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]Volume, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Volume(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Volumes = nil + } + if in.InitContainers != nil { + in, out := &in.InitContainers, &out.InitContainers + *out = make([]Container, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Container(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.InitContainers = nil + } + if in.Containers != nil { + in, out := &in.Containers, &out.Containers + *out = make([]Container, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Container(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Containers = nil + } + out.RestartPolicy = in.RestartPolicy + if in.TerminationGracePeriodSeconds != nil { + in, out := &in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.TerminationGracePeriodSeconds = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + out.DNSPolicy = in.DNSPolicy + if in.NodeSelector != nil { + in, out := &in.NodeSelector, &out.NodeSelector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.NodeSelector = nil + } + out.ServiceAccountName = in.ServiceAccountName + out.DeprecatedServiceAccount = in.DeprecatedServiceAccount + out.NodeName = in.NodeName + out.HostNetwork = in.HostNetwork + out.HostPID = in.HostPID + out.HostIPC = in.HostIPC + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(PodSecurityContext) + if err := DeepCopy_v1_PodSecurityContext(*in, *out, c); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + if in.ImagePullSecrets != nil { + in, out := &in.ImagePullSecrets, &out.ImagePullSecrets + *out = make([]LocalObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ImagePullSecrets = nil + } + out.Hostname = in.Hostname + out.Subdomain = in.Subdomain + return nil + } +} + +func DeepCopy_v1_PodStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodStatus) + out := out.(*PodStatus) + out.Phase = in.Phase + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]PodCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PodCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.Message = in.Message + out.Reason = in.Reason + out.HostIP = in.HostIP + out.PodIP = in.PodIP + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.InitContainerStatuses != nil { + in, out := &in.InitContainerStatuses, &out.InitContainerStatuses + *out = make([]ContainerStatus, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ContainerStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.InitContainerStatuses = nil + } + if in.ContainerStatuses != nil { + in, out := &in.ContainerStatuses, &out.ContainerStatuses + *out = make([]ContainerStatus, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ContainerStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.ContainerStatuses = nil + } + return nil + } +} + +func DeepCopy_v1_PodStatusResult(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodStatusResult) + out := out.(*PodStatusResult) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PodStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_PodTemplate(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplate) + out := out.(*PodTemplate) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_PodTemplateList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplateList) + out := out.(*PodTemplateList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodTemplate, len(*in)) + for i := range *in { + if err := DeepCopy_v1_PodTemplate(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_PodTemplateSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplateSpec) + out := out.(*PodTemplateSpec) + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_PodSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_Preconditions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Preconditions) + out := out.(*Preconditions) + if in.UID != nil { + in, out := &in.UID, &out.UID + *out = new(types.UID) + **out = **in + } else { + out.UID = nil + } + return nil + } +} + +func DeepCopy_v1_PreferAvoidPodsEntry(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PreferAvoidPodsEntry) + out := out.(*PreferAvoidPodsEntry) + if err := DeepCopy_v1_PodSignature(&in.PodSignature, &out.PodSignature, c); err != nil { + return err + } + out.EvictionTime = in.EvictionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1_PreferredSchedulingTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PreferredSchedulingTerm) + out := out.(*PreferredSchedulingTerm) + out.Weight = in.Weight + if err := DeepCopy_v1_NodeSelectorTerm(&in.Preference, &out.Preference, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_Probe(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Probe) + out := out.(*Probe) + if err := DeepCopy_v1_Handler(&in.Handler, &out.Handler, c); err != nil { + return err + } + out.InitialDelaySeconds = in.InitialDelaySeconds + out.TimeoutSeconds = in.TimeoutSeconds + out.PeriodSeconds = in.PeriodSeconds + out.SuccessThreshold = in.SuccessThreshold + out.FailureThreshold = in.FailureThreshold + return nil + } +} + +func DeepCopy_v1_RBDVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RBDVolumeSource) + out := out.(*RBDVolumeSource) + if in.CephMonitors != nil { + in, out := &in.CephMonitors, &out.CephMonitors + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.CephMonitors = nil + } + out.RBDImage = in.RBDImage + out.FSType = in.FSType + out.RBDPool = in.RBDPool + out.RadosUser = in.RadosUser + out.Keyring = in.Keyring + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_v1_RangeAllocation(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RangeAllocation) + out := out.(*RangeAllocation) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Range = in.Range + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_v1_ReplicationController(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationController) + out := out.(*ReplicationController) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_ReplicationControllerSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1_ReplicationControllerList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerList) + out := out.(*ReplicationControllerList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ReplicationController, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ReplicationController(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ReplicationControllerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerSpec) + out := out.(*ReplicationControllerSpec) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } else { + out.Replicas = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Selector = nil + } + if in.Template != nil { + in, out := &in.Template, &out.Template + *out = new(PodTemplateSpec) + if err := DeepCopy_v1_PodTemplateSpec(*in, *out, c); err != nil { + return err + } + } else { + out.Template = nil + } + return nil + } +} + +func DeepCopy_v1_ReplicationControllerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerStatus) + out := out.(*ReplicationControllerStatus) + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil + } +} + +func DeepCopy_v1_ResourceFieldSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceFieldSelector) + out := out.(*ResourceFieldSelector) + out.ContainerName = in.ContainerName + out.Resource = in.Resource + out.Divisor = in.Divisor.DeepCopy() + return nil + } +} + +func DeepCopy_v1_ResourceQuota(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuota) + out := out.(*ResourceQuota) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_ResourceQuotaSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_ResourceQuotaStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_ResourceQuotaList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaList) + out := out.(*ResourceQuotaList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ResourceQuota, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ResourceQuota(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ResourceQuotaSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaSpec) + out := out.(*ResourceQuotaSpec) + if in.Hard != nil { + in, out := &in.Hard, &out.Hard + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Hard = nil + } + if in.Scopes != nil { + in, out := &in.Scopes, &out.Scopes + *out = make([]ResourceQuotaScope, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Scopes = nil + } + return nil + } +} + +func DeepCopy_v1_ResourceQuotaStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaStatus) + out := out.(*ResourceQuotaStatus) + if in.Hard != nil { + in, out := &in.Hard, &out.Hard + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Hard = nil + } + if in.Used != nil { + in, out := &in.Used, &out.Used + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Used = nil + } + return nil + } +} + +func DeepCopy_v1_ResourceRequirements(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceRequirements) + out := out.(*ResourceRequirements) + if in.Limits != nil { + in, out := &in.Limits, &out.Limits + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Limits = nil + } + if in.Requests != nil { + in, out := &in.Requests, &out.Requests + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Requests = nil + } + return nil + } +} + +func DeepCopy_v1_SELinuxOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SELinuxOptions) + out := out.(*SELinuxOptions) + out.User = in.User + out.Role = in.Role + out.Type = in.Type + out.Level = in.Level + return nil + } +} + +func DeepCopy_v1_Secret(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Secret) + out := out.(*Secret) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string][]byte) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]byte) + } + } + } else { + out.Data = nil + } + if in.StringData != nil { + in, out := &in.StringData, &out.StringData + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.StringData = nil + } + out.Type = in.Type + return nil + } +} + +func DeepCopy_v1_SecretKeySelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretKeySelector) + out := out.(*SecretKeySelector) + out.LocalObjectReference = in.LocalObjectReference + out.Key = in.Key + return nil + } +} + +func DeepCopy_v1_SecretList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretList) + out := out.(*SecretList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Secret, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Secret(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_SecretVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretVolumeSource) + out := out.(*SecretVolumeSource) + out.SecretName = in.SecretName + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KeyToPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_SecurityContext(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecurityContext) + out := out.(*SecurityContext) + if in.Capabilities != nil { + in, out := &in.Capabilities, &out.Capabilities + *out = new(Capabilities) + if err := DeepCopy_v1_Capabilities(*in, *out, c); err != nil { + return err + } + } else { + out.Capabilities = nil + } + if in.Privileged != nil { + in, out := &in.Privileged, &out.Privileged + *out = new(bool) + **out = **in + } else { + out.Privileged = nil + } + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + in, out := &in.RunAsUser, &out.RunAsUser + *out = new(int64) + **out = **in + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + in, out := &in.RunAsNonRoot, &out.RunAsNonRoot + *out = new(bool) + **out = **in + } else { + out.RunAsNonRoot = nil + } + if in.ReadOnlyRootFilesystem != nil { + in, out := &in.ReadOnlyRootFilesystem, &out.ReadOnlyRootFilesystem + *out = new(bool) + **out = **in + } else { + out.ReadOnlyRootFilesystem = nil + } + return nil + } +} + +func DeepCopy_v1_SerializedReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SerializedReference) + out := out.(*SerializedReference) + out.TypeMeta = in.TypeMeta + out.Reference = in.Reference + return nil + } +} + +func DeepCopy_v1_Service(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Service) + out := out.(*Service) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_ServiceSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_ServiceStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_ServiceAccount(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceAccount) + out := out.(*ServiceAccount) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Secrets != nil { + in, out := &in.Secrets, &out.Secrets + *out = make([]ObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Secrets = nil + } + if in.ImagePullSecrets != nil { + in, out := &in.ImagePullSecrets, &out.ImagePullSecrets + *out = make([]LocalObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ImagePullSecrets = nil + } + return nil + } +} + +func DeepCopy_v1_ServiceAccountList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceAccountList) + out := out.(*ServiceAccountList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ServiceAccount, len(*in)) + for i := range *in { + if err := DeepCopy_v1_ServiceAccount(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ServiceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceList) + out := out.(*ServiceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Service, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Service(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_ServicePort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServicePort) + out := out.(*ServicePort) + out.Name = in.Name + out.Protocol = in.Protocol + out.Port = in.Port + out.TargetPort = in.TargetPort + out.NodePort = in.NodePort + return nil + } +} + +func DeepCopy_v1_ServiceProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceProxyOptions) + out := out.(*ServiceProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_v1_ServiceSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceSpec) + out := out.(*ServiceSpec) + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]ServicePort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Selector = nil + } + out.ClusterIP = in.ClusterIP + out.Type = in.Type + if in.ExternalIPs != nil { + in, out := &in.ExternalIPs, &out.ExternalIPs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.ExternalIPs = nil + } + if in.DeprecatedPublicIPs != nil { + in, out := &in.DeprecatedPublicIPs, &out.DeprecatedPublicIPs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.DeprecatedPublicIPs = nil + } + out.SessionAffinity = in.SessionAffinity + out.LoadBalancerIP = in.LoadBalancerIP + if in.LoadBalancerSourceRanges != nil { + in, out := &in.LoadBalancerSourceRanges, &out.LoadBalancerSourceRanges + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.LoadBalancerSourceRanges = nil + } + return nil + } +} + +func DeepCopy_v1_ServiceStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceStatus) + out := out.(*ServiceStatus) + if err := DeepCopy_v1_LoadBalancerStatus(&in.LoadBalancer, &out.LoadBalancer, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_TCPSocketAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TCPSocketAction) + out := out.(*TCPSocketAction) + out.Port = in.Port + return nil + } +} + +func DeepCopy_v1_Taint(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Taint) + out := out.(*Taint) + out.Key = in.Key + out.Value = in.Value + out.Effect = in.Effect + return nil + } +} + +func DeepCopy_v1_Toleration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Toleration) + out := out.(*Toleration) + out.Key = in.Key + out.Operator = in.Operator + out.Value = in.Value + out.Effect = in.Effect + return nil + } +} + +func DeepCopy_v1_Volume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Volume) + out := out.(*Volume) + out.Name = in.Name + if err := DeepCopy_v1_VolumeSource(&in.VolumeSource, &out.VolumeSource, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_VolumeMount(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VolumeMount) + out := out.(*VolumeMount) + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + out.SubPath = in.SubPath + return nil + } +} + +func DeepCopy_v1_VolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VolumeSource) + out := out.(*VolumeSource) + if in.HostPath != nil { + in, out := &in.HostPath, &out.HostPath + *out = new(HostPathVolumeSource) + **out = **in + } else { + out.HostPath = nil + } + if in.EmptyDir != nil { + in, out := &in.EmptyDir, &out.EmptyDir + *out = new(EmptyDirVolumeSource) + **out = **in + } else { + out.EmptyDir = nil + } + if in.GCEPersistentDisk != nil { + in, out := &in.GCEPersistentDisk, &out.GCEPersistentDisk + *out = new(GCEPersistentDiskVolumeSource) + **out = **in + } else { + out.GCEPersistentDisk = nil + } + if in.AWSElasticBlockStore != nil { + in, out := &in.AWSElasticBlockStore, &out.AWSElasticBlockStore + *out = new(AWSElasticBlockStoreVolumeSource) + **out = **in + } else { + out.AWSElasticBlockStore = nil + } + if in.GitRepo != nil { + in, out := &in.GitRepo, &out.GitRepo + *out = new(GitRepoVolumeSource) + **out = **in + } else { + out.GitRepo = nil + } + if in.Secret != nil { + in, out := &in.Secret, &out.Secret + *out = new(SecretVolumeSource) + if err := DeepCopy_v1_SecretVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.Secret = nil + } + if in.NFS != nil { + in, out := &in.NFS, &out.NFS + *out = new(NFSVolumeSource) + **out = **in + } else { + out.NFS = nil + } + if in.ISCSI != nil { + in, out := &in.ISCSI, &out.ISCSI + *out = new(ISCSIVolumeSource) + **out = **in + } else { + out.ISCSI = nil + } + if in.Glusterfs != nil { + in, out := &in.Glusterfs, &out.Glusterfs + *out = new(GlusterfsVolumeSource) + **out = **in + } else { + out.Glusterfs = nil + } + if in.PersistentVolumeClaim != nil { + in, out := &in.PersistentVolumeClaim, &out.PersistentVolumeClaim + *out = new(PersistentVolumeClaimVolumeSource) + **out = **in + } else { + out.PersistentVolumeClaim = nil + } + if in.RBD != nil { + in, out := &in.RBD, &out.RBD + *out = new(RBDVolumeSource) + if err := DeepCopy_v1_RBDVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.RBD = nil + } + if in.FlexVolume != nil { + in, out := &in.FlexVolume, &out.FlexVolume + *out = new(FlexVolumeSource) + if err := DeepCopy_v1_FlexVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + if in.Cinder != nil { + in, out := &in.Cinder, &out.Cinder + *out = new(CinderVolumeSource) + **out = **in + } else { + out.Cinder = nil + } + if in.CephFS != nil { + in, out := &in.CephFS, &out.CephFS + *out = new(CephFSVolumeSource) + if err := DeepCopy_v1_CephFSVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.CephFS = nil + } + if in.Flocker != nil { + in, out := &in.Flocker, &out.Flocker + *out = new(FlockerVolumeSource) + **out = **in + } else { + out.Flocker = nil + } + if in.DownwardAPI != nil { + in, out := &in.DownwardAPI, &out.DownwardAPI + *out = new(DownwardAPIVolumeSource) + if err := DeepCopy_v1_DownwardAPIVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.DownwardAPI = nil + } + if in.FC != nil { + in, out := &in.FC, &out.FC + *out = new(FCVolumeSource) + if err := DeepCopy_v1_FCVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FC = nil + } + if in.AzureFile != nil { + in, out := &in.AzureFile, &out.AzureFile + *out = new(AzureFileVolumeSource) + **out = **in + } else { + out.AzureFile = nil + } + if in.ConfigMap != nil { + in, out := &in.ConfigMap, &out.ConfigMap + *out = new(ConfigMapVolumeSource) + if err := DeepCopy_v1_ConfigMapVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.ConfigMap = nil + } + if in.VsphereVolume != nil { + in, out := &in.VsphereVolume, &out.VsphereVolume + *out = new(VsphereVirtualDiskVolumeSource) + **out = **in + } else { + out.VsphereVolume = nil + } + return nil + } +} + +func DeepCopy_v1_VsphereVirtualDiskVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VsphereVirtualDiskVolumeSource) + out := out.(*VsphereVirtualDiskVolumeSource) + out.VolumePath = in.VolumePath + out.FSType = in.FSType + return nil + } +} + +func DeepCopy_v1_WeightedPodAffinityTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*WeightedPodAffinityTerm) + out := out.(*WeightedPodAffinityTerm) + out.Weight = in.Weight + if err := DeepCopy_v1_PodAffinityTerm(&in.PodAffinityTerm, &out.PodAffinityTerm, c); err != nil { + return err + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/validation/doc.go b/vendor/k8s.io/kubernetes/pkg/api/validation/doc.go index 1b7051073ba2..f17a15cf9c1d 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/validation/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/api/validation/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/validation/events.go b/vendor/k8s.io/kubernetes/pkg/api/validation/events.go index 0a5de5443bb3..754cf883001b 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/validation/events.go +++ b/vendor/k8s.io/kubernetes/pkg/api/validation/events.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/validation/name.go b/vendor/k8s.io/kubernetes/pkg/api/validation/name.go index cf2eb8bb2990..1358e6e7e9b0 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/validation/name.go +++ b/vendor/k8s.io/kubernetes/pkg/api/validation/name.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/api/validation/schema.go b/vendor/k8s.io/kubernetes/pkg/api/validation/schema.go index 345666c970b2..f6a4d0798bb1 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/validation/schema.go +++ b/vendor/k8s.io/kubernetes/pkg/api/validation/schema.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -297,6 +297,10 @@ func (s *SwaggerSchema) isGenericArray(p swagger.ModelProperty) bool { var versionRegexp = regexp.MustCompile(`^(v.+|unversioned)\..*`) func (s *SwaggerSchema) validateField(value interface{}, fieldName, fieldType string, fieldDetails *swagger.ModelProperty) []error { + allErrs := []error{} + if reflect.TypeOf(value) == nil { + return append(allErrs, fmt.Errorf("unexpected nil value for field %v", fieldName)) + } // TODO: caesarxuchao: because we have multiple group/versions and objects // may reference objects in other group, the commented out way of checking // if a filedType is a type defined by us is outdated. We use a hacky way @@ -310,7 +314,6 @@ func (s *SwaggerSchema) validateField(value interface{}, fieldName, fieldType st // if strings.HasPrefix(fieldType, apiVersion) { return s.ValidateObject(value, fieldName, fieldType) } - allErrs := []error{} switch fieldType { case "string": // Be loose about what we accept for 'string' since we use IntOrString in a couple of places diff --git a/vendor/k8s.io/kubernetes/pkg/api/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/api/validation/validation.go index 47213e40638c..e08bb1e5d60b 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/api/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,12 +19,10 @@ package validation import ( "encoding/json" "fmt" - "math" "net" "os" "path" "reflect" - "regexp" "strings" "github.com/golang/glog" @@ -51,17 +49,9 @@ var RepairMalformedUpdates bool = true const isNegativeErrorMsg string = `must be greater than or equal to 0` const isInvalidQuotaResource string = `must be a standard resource for quota` const fieldImmutableErrorMsg string = `field is immutable` -const cIdentifierErrorMsg string = `must be a C identifier (matching regex ` + validation.CIdentifierFmt + `): e.g. "my_name" or "MyName"` const isNotIntegerErrorMsg string = `must be an integer` -func InclusiveRangeErrorMsg(lo, hi int) string { - return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi) -} - -var pdPartitionErrorMsg string = InclusiveRangeErrorMsg(1, 255) -var PortRangeErrorMsg string = InclusiveRangeErrorMsg(1, 65535) -var IdRangeErrorMsg string = InclusiveRangeErrorMsg(0, math.MaxInt32) -var PortNameErrorMsg string = fmt.Sprintf(`must be an IANA_SVC_NAME (at most 15 characters, matching regex %s, it must contain at least one letter [a-z], and hyphens cannot be adjacent to other hyphens): e.g. "http"`, validation.IdentifierNoHyphensBeginEndFmt) +var pdPartitionErrorMsg string = validation.InclusiveRangeError(1, 255) const totalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB @@ -75,11 +65,13 @@ func ValidateHasLabel(meta api.ObjectMeta, fldPath *field.Path, key, expectedVal allErrs := field.ErrorList{} actualValue, found := meta.Labels[key] if !found { - allErrs = append(allErrs, field.Required(fldPath.Child("labels"), key+"="+expectedValue)) + allErrs = append(allErrs, field.Required(fldPath.Child("labels").Key(key), + fmt.Sprintf("must be '%s'", expectedValue))) return allErrs } if actualValue != expectedValue { - allErrs = append(allErrs, field.Invalid(fldPath.Child("labels"), meta.Labels, "expected "+key+"="+expectedValue)) + allErrs = append(allErrs, field.Invalid(fldPath.Child("labels").Key(key), meta.Labels, + fmt.Sprintf("must be '%s'", expectedValue))) } return allErrs } @@ -100,6 +92,14 @@ func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) fie return allErrs } +func ValidateDNS1123Label(value string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + for _, msg := range validation.IsDNS1123Label(value) { + allErrs = append(allErrs, field.Invalid(fldPath, value, msg)) + } + return allErrs +} + func ValidatePodSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if annotations[api.AffinityAnnotationKey] != "" { @@ -110,16 +110,12 @@ func ValidatePodSpecificAnnotations(annotations map[string]string, fldPath *fiel allErrs = append(allErrs, ValidateTolerationsInPodAnnotations(annotations, fldPath)...) } + // TODO: remove these after we EOL the annotations. if hostname, exists := annotations[utilpod.PodHostnameAnnotation]; exists { - for _, msg := range validation.IsDNS1123Label(hostname) { - allErrs = append(allErrs, field.Invalid(fldPath, utilpod.PodHostnameAnnotation, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(hostname, fldPath.Key(utilpod.PodHostnameAnnotation))...) } - if subdomain, exists := annotations[utilpod.PodSubdomainAnnotation]; exists { - for _, msg := range validation.IsDNS1123Label(subdomain) { - allErrs = append(allErrs, field.Invalid(fldPath, utilpod.PodSubdomainAnnotation, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(subdomain, fldPath.Key(utilpod.PodSubdomainAnnotation))...) } allErrs = append(allErrs, ValidateSeccompPodAnnotations(annotations, fldPath)...) @@ -129,6 +125,7 @@ func ValidatePodSpecificAnnotations(annotations map[string]string, fldPath *fiel func ValidateEndpointsSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} + // TODO: remove this after we EOL the annotation. hostnamesMap, exists := annotations[endpoints.PodHostnamesAnnotation] if exists && !isValidHostnamesMap(hostnamesMap) { allErrs = append(allErrs, field.Invalid(fldPath, endpoints.PodHostnamesAnnotation, @@ -382,6 +379,11 @@ func ValidateObjectMetaUpdate(newMeta, oldMeta *api.ObjectMeta, fldPath *field.P allErrs = append(allErrs, field.Invalid(fldPath.Child("resourceVersion"), newMeta.ResourceVersion, "must be specified for an update")) } + // Generation shouldn't be decremented + if newMeta.Generation < oldMeta.Generation { + allErrs = append(allErrs, field.Invalid(fldPath.Child("generation"), newMeta.Generation, "must not be decremented")) + } + allErrs = append(allErrs, ValidateImmutableField(newMeta.Name, oldMeta.Name, fldPath.Child("name"))...) allErrs = append(allErrs, ValidateImmutableField(newMeta.Namespace, oldMeta.Namespace, fldPath.Child("namespace"))...) allErrs = append(allErrs, ValidateImmutableField(newMeta.UID, oldMeta.UID, fldPath.Child("uid"))...) @@ -400,15 +402,15 @@ func validateVolumes(volumes []api.Volume, fldPath *field.Path) (sets.String, fi allNames := sets.String{} for i, vol := range volumes { idxPath := fldPath.Index(i) + namePath := idxPath.Child("name") el := validateVolumeSource(&vol.VolumeSource, idxPath) if len(vol.Name) == 0 { - el = append(el, field.Required(idxPath.Child("name"), "")) - } else if msgs := validation.IsDNS1123Label(vol.Name); len(msgs) != 0 { - for i := range msgs { - el = append(el, field.Invalid(idxPath.Child("name"), vol.Name, msgs[i])) - } - } else if allNames.Has(vol.Name) { - el = append(el, field.Duplicate(idxPath.Child("name"), vol.Name)) + el = append(el, field.Required(namePath, "")) + } else { + el = append(el, ValidateDNS1123Label(vol.Name, namePath)...) + } + if allNames.Has(vol.Name) { + el = append(el, field.Duplicate(namePath, vol.Name)) } if len(el) == 0 { allNames.Insert(vol.Name) @@ -610,7 +612,7 @@ func validateISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, fldPath *field.Path allErrs = append(allErrs, field.Required(fldPath.Child("iqn"), "")) } if iscsi.Lun < 0 || iscsi.Lun > 255 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), iscsi.Lun, InclusiveRangeErrorMsg(0, 255))) + allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), iscsi.Lun, validation.InclusiveRangeError(0, 255))) } return allErrs } @@ -625,7 +627,7 @@ func validateFCVolumeSource(fc *api.FCVolumeSource, fldPath *field.Path) field.E allErrs = append(allErrs, field.Required(fldPath.Child("lun"), "")) } else { if *fc.Lun < 0 || *fc.Lun > 255 { - allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), fc.Lun, InclusiveRangeErrorMsg(0, 255))) + allErrs = append(allErrs, field.Invalid(fldPath.Child("lun"), fc.Lun, validation.InclusiveRangeError(0, 255))) } } return allErrs @@ -1020,11 +1022,18 @@ func ValidatePersistentVolumeClaim(pvc *api.PersistentVolumeClaim) field.ErrorLi func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *api.PersistentVolumeClaim) field.ErrorList { allErrs := ValidateObjectMetaUpdate(&newPvc.ObjectMeta, &oldPvc.ObjectMeta, field.NewPath("metadata")) allErrs = append(allErrs, ValidatePersistentVolumeClaim(newPvc)...) - // if a pvc had a bound volume, we should not allow updates to resources or access modes - if len(oldPvc.Spec.VolumeName) != 0 { - if !api.Semantic.DeepEqual(newPvc.Spec, oldPvc.Spec) { - allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "spec is immutable once a claim has been bound to a volume")) - } + // PVController needs to update PVC.Spec w/ VolumeName. + // Claims are immutable in order to enforce quota, range limits, etc. without gaming the system. + if len(oldPvc.Spec.VolumeName) == 0 { + // volumeName changes are allowed once. + // Reset back to empty string after equality check + oldPvc.Spec.VolumeName = newPvc.Spec.VolumeName + defer func() { oldPvc.Spec.VolumeName = "" }() + } + // changes to Spec are not allowed, but updates to label/annotations are OK. + // no-op updates pass validation. + if !api.Semantic.DeepEqual(newPvc.Spec, oldPvc.Spec) { + allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "field is immutable after creation")) } newPvc.Status = oldPvc.Status return allErrs @@ -1055,8 +1064,10 @@ func validateContainerPorts(ports []api.ContainerPort, fldPath *field.Path) fiel for i, port := range ports { idxPath := fldPath.Index(i) if len(port.Name) > 0 { - if !validation.IsValidPortName(port.Name) { - allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), port.Name, PortNameErrorMsg)) + if msgs := validation.IsValidPortName(port.Name); len(msgs) != 0 { + for i = range msgs { + allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), port.Name, msgs[i])) + } } else if allNames.Has(port.Name) { allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), port.Name)) } else { @@ -1064,12 +1075,16 @@ func validateContainerPorts(ports []api.ContainerPort, fldPath *field.Path) fiel } } if port.ContainerPort == 0 { - allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg)) - } else if !validation.IsValidPortNum(int(port.ContainerPort)) { - allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, PortRangeErrorMsg)) + allErrs = append(allErrs, field.Required(idxPath.Child("containerPort"), "")) + } else { + for _, msg := range validation.IsValidPortNum(int(port.ContainerPort)) { + allErrs = append(allErrs, field.Invalid(idxPath.Child("containerPort"), port.ContainerPort, msg)) + } } - if port.HostPort != 0 && !validation.IsValidPortNum(int(port.HostPort)) { - allErrs = append(allErrs, field.Invalid(idxPath.Child("hostPort"), port.HostPort, PortRangeErrorMsg)) + if port.HostPort != 0 { + for _, msg := range validation.IsValidPortNum(int(port.HostPort)) { + allErrs = append(allErrs, field.Invalid(idxPath.Child("hostPort"), port.HostPort, msg)) + } } if len(port.Protocol) == 0 { allErrs = append(allErrs, field.Required(idxPath.Child("protocol"), "")) @@ -1087,8 +1102,10 @@ func validateEnv(vars []api.EnvVar, fldPath *field.Path) field.ErrorList { idxPath := fldPath.Index(i) if len(ev.Name) == 0 { allErrs = append(allErrs, field.Required(idxPath.Child("name"), "")) - } else if !validation.IsCIdentifier(ev.Name) { - allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ev.Name, cIdentifierErrorMsg)) + } else { + for _, msg := range validation.IsCIdentifier(ev.Name) { + allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ev.Name, msg)) + } } allErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child("valueFrom"))...) } @@ -1198,8 +1215,10 @@ func validateConfigMapKeySelector(s *api.ConfigMapKeySelector, fldPath *field.Pa } if len(s.Key) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child("key"), "")) - } else if !IsSecretKey(s.Key) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) + } else { + for _, msg := range validation.IsConfigMapKey(s.Key) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, msg)) + } } return allErrs @@ -1213,8 +1232,10 @@ func validateSecretKeySelector(s *api.SecretKeySelector, fldPath *field.Path) fi } if len(s.Key) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child("key"), "")) - } else if !IsSecretKey(s.Key) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) + } else { + for _, msg := range validation.IsConfigMapKey(s.Key) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), s.Key, msg)) + } } return allErrs @@ -1303,36 +1324,43 @@ func validateExecAction(exec *api.ExecAction, fldPath *field.Path) field.ErrorLi return allErrors } +var supportedHTTPSchemes = sets.NewString(string(api.URISchemeHTTP), string(api.URISchemeHTTPS)) + func validateHTTPGetAction(http *api.HTTPGetAction, fldPath *field.Path) field.ErrorList { allErrors := field.ErrorList{} if len(http.Path) == 0 { allErrors = append(allErrors, field.Required(fldPath.Child("path"), "")) } - if http.Port.Type == intstr.Int && !validation.IsValidPortNum(http.Port.IntValue()) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), http.Port, PortRangeErrorMsg)) - } else if http.Port.Type == intstr.String && !validation.IsValidPortName(http.Port.StrVal) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), http.Port.StrVal, PortNameErrorMsg)) - } - supportedSchemes := sets.NewString(string(api.URISchemeHTTP), string(api.URISchemeHTTPS)) - if !supportedSchemes.Has(string(http.Scheme)) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("scheme"), http.Scheme, fmt.Sprintf("must be one of %v", supportedSchemes.List()))) + allErrors = append(allErrors, ValidatePortNumOrName(http.Port, fldPath.Child("port"))...) + if !supportedHTTPSchemes.Has(string(http.Scheme)) { + allErrors = append(allErrors, field.NotSupported(fldPath.Child("scheme"), http.Scheme, supportedHTTPSchemes.List())) } for _, header := range http.HTTPHeaders { - if !validation.IsHTTPHeaderName(header.Name) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("httpHeaders"), header.Name, fmt.Sprintf("name must match %s", validation.HTTPHeaderNameFmt))) + for _, msg := range validation.IsHTTPHeaderName(header.Name) { + allErrors = append(allErrors, field.Invalid(fldPath.Child("httpHeaders"), header.Name, msg)) } } return allErrors } -func validateTCPSocketAction(tcp *api.TCPSocketAction, fldPath *field.Path) field.ErrorList { - allErrors := field.ErrorList{} - if tcp.Port.Type == intstr.Int && !validation.IsValidPortNum(tcp.Port.IntValue()) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), tcp.Port, PortRangeErrorMsg)) - } else if tcp.Port.Type == intstr.String && !validation.IsValidPortName(tcp.Port.StrVal) { - allErrors = append(allErrors, field.Invalid(fldPath.Child("port"), tcp.Port.StrVal, PortNameErrorMsg)) +func ValidatePortNumOrName(port intstr.IntOrString, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if port.Type == intstr.Int { + for _, msg := range validation.IsValidPortNum(port.IntValue()) { + allErrs = append(allErrs, field.Invalid(fldPath, port.IntValue(), msg)) + } + } else if port.Type == intstr.String { + for _, msg := range validation.IsValidPortName(port.StrVal) { + allErrs = append(allErrs, field.Invalid(fldPath, port.StrVal, msg)) + } + } else { + allErrs = append(allErrs, field.InternalError(fldPath, fmt.Errorf("unknown type: %v", port.Type))) } - return allErrors + return allErrs +} + +func validateTCPSocketAction(tcp *api.TCPSocketAction, fldPath *field.Path) field.ErrorList { + return ValidatePortNumOrName(tcp.Port, fldPath.Child("port")) } func validateHandler(handler *api.Handler, fldPath *field.Path) field.ErrorList { @@ -1437,14 +1465,14 @@ func validateContainers(containers []api.Container, volumes sets.String, fldPath allNames := sets.String{} for i, ctr := range containers { idxPath := fldPath.Index(i) + namePath := idxPath.Child("name") if len(ctr.Name) == 0 { - allErrs = append(allErrs, field.Required(idxPath.Child("name"), "")) - } else if msgs := validation.IsDNS1123Label(ctr.Name); len(msgs) != 0 { - for i := range msgs { - allErrs = append(allErrs, field.Invalid(idxPath.Child("name"), ctr.Name, msgs[i])) - } - } else if allNames.Has(ctr.Name) { - allErrs = append(allErrs, field.Duplicate(idxPath.Child("name"), ctr.Name)) + allErrs = append(allErrs, field.Required(namePath, "")) + } else { + allErrs = append(allErrs, ValidateDNS1123Label(ctr.Name, namePath)...) + } + if allNames.Has(ctr.Name) { + allErrs = append(allErrs, field.Duplicate(namePath, ctr.Name)) } else { allNames.Insert(ctr.Name) } @@ -1633,15 +1661,11 @@ func ValidatePodSpec(spec *api.PodSpec, fldPath *field.Path) field.ErrorList { } if len(spec.Hostname) > 0 { - for _, msg := range validation.IsDNS1123Label(spec.Hostname) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("hostname"), spec.Hostname, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(spec.Hostname, fldPath.Child("hostname"))...) } if len(spec.Subdomain) > 0 { - for _, msg := range validation.IsDNS1123Label(spec.Subdomain) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("subdomain"), spec.Subdomain, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(spec.Subdomain, fldPath.Child("subdomain"))...) } return allErrs @@ -1700,6 +1724,41 @@ func ValidateNodeSelector(nodeSelector *api.NodeSelector, fldPath *field.Path) f return allErrs } +// ValidateAvoidPodsInNodeAnnotations tests that the serialized AvoidPods in Node.Annotations has valid data +func ValidateAvoidPodsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + + avoids, err := api.GetAvoidPodsFromNodeAnnotations(annotations) + if err != nil { + allErrs = append(allErrs, field.Invalid(fldPath.Child("AvoidPods"), api.PreferAvoidPodsAnnotationKey, err.Error())) + return allErrs + } + + if len(avoids.PreferAvoidPods) != 0 { + for i, pa := range avoids.PreferAvoidPods { + idxPath := fldPath.Child(api.PreferAvoidPodsAnnotationKey).Index(i) + allErrs = append(allErrs, validatePreferAvoidPodsEntry(pa, idxPath)...) + } + } + + return allErrs +} + +// validatePreferAvoidPodsEntry tests if given PreferAvoidPodsEntry has valid data. +func validatePreferAvoidPodsEntry(avoidPodEntry api.PreferAvoidPodsEntry, fldPath *field.Path) field.ErrorList { + allErrors := field.ErrorList{} + if avoidPodEntry.PodSignature.PodController == nil { + allErrors = append(allErrors, field.Required(fldPath.Child("PodSignature"), "")) + } else { + if *(avoidPodEntry.PodSignature.PodController.Controller) != true { + allErrors = append(allErrors, + field.Invalid(fldPath.Child("PodSignature").Child("PodController").Child("Controller"), + *(avoidPodEntry.PodSignature.PodController.Controller), "must point to a controller")) + } + } + return allErrors +} + // ValidatePreferredSchedulingTerms tests that the specified SoftNodeAffinity fields has valid data func ValidatePreferredSchedulingTerms(terms []api.PreferredSchedulingTerm, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} @@ -1804,6 +1863,9 @@ func ValidateAffinityInPodAnnotations(annotations map[string]string, fldPath *fi allErrs = append(allErrs, field.Invalid(fldPath, api.AffinityAnnotationKey, err.Error())) return allErrs } + if affinity == nil { + return allErrs + } affinityFldPath := fldPath.Child(api.AffinityAnnotationKey) if affinity.NodeAffinity != nil { @@ -1881,16 +1943,19 @@ func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *a if securityContext != nil { allErrs = append(allErrs, validateHostNetwork(securityContext.HostNetwork, spec.Containers, specPath.Child("containers"))...) - if securityContext.FSGroup != nil && !validation.IsValidGroupId(*securityContext.FSGroup) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("fsGroup"), *(securityContext.FSGroup), IdRangeErrorMsg)) + if securityContext.FSGroup != nil { + for _, msg := range validation.IsValidGroupId(*securityContext.FSGroup) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("fsGroup"), *(securityContext.FSGroup), msg)) + } } - if securityContext.RunAsUser != nil && !validation.IsValidUserId(*securityContext.RunAsUser) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *(securityContext.RunAsUser), IdRangeErrorMsg)) + if securityContext.RunAsUser != nil { + for _, msg := range validation.IsValidUserId(*securityContext.RunAsUser) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *(securityContext.RunAsUser), msg)) + } } - for i, gid := range securityContext.SupplementalGroups { - if !validation.IsValidGroupId(gid) { - supplementalGroup := fmt.Sprintf(`supplementalGroups[%d]`, i) - allErrs = append(allErrs, field.Invalid(fldPath.Child(supplementalGroup), gid, IdRangeErrorMsg)) + for g, gid := range securityContext.SupplementalGroups { + for _, msg := range validation.IsValidGroupId(gid) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("supplementalGroups").Index(g), gid, msg)) } } } @@ -1898,6 +1963,23 @@ func ValidatePodSecurityContext(securityContext *api.PodSecurityContext, spec *a return allErrs } +func validateContainerUpdates(newContainers, oldContainers []api.Container, fldPath *field.Path) (allErrs field.ErrorList, stop bool) { + allErrs = field.ErrorList{} + if len(newContainers) != len(oldContainers) { + //TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff + allErrs = append(allErrs, field.Forbidden(fldPath, "pod updates may not add or remove containers")) + return allErrs, true + } + + // validate updated container images + for i, ctr := range newContainers { + if len(ctr.Image) == 0 { + allErrs = append(allErrs, field.Required(fldPath.Index(i).Child("image"), "")) + } + } + return allErrs, false +} + // ValidatePodUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields // that cannot be changed. func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList { @@ -1905,21 +1987,21 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList { allErrs := ValidateObjectMetaUpdate(&newPod.ObjectMeta, &oldPod.ObjectMeta, fldPath) allErrs = append(allErrs, ValidatePodSpecificAnnotations(newPod.ObjectMeta.Annotations, fldPath.Child("annotations"))...) specPath := field.NewPath("spec") - if len(newPod.Spec.Containers) != len(oldPod.Spec.Containers) { - //TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff - allErrs = append(allErrs, field.Forbidden(specPath.Child("containers"), "pod updates may not add or remove containers")) - return allErrs - } // validate updateable fields: // 1. containers[*].image - // 2. spec.activeDeadlineSeconds + // 2. initContainers[*].image + // 3. spec.activeDeadlineSeconds - // validate updated container images - for i, ctr := range newPod.Spec.Containers { - if len(ctr.Image) == 0 { - allErrs = append(allErrs, field.Required(specPath.Child("containers").Index(i).Child("image"), "")) - } + containerErrs, stop := validateContainerUpdates(newPod.Spec.Containers, oldPod.Spec.Containers, specPath.Child("containers")) + allErrs = append(allErrs, containerErrs...) + if stop { + return allErrs + } + containerErrs, stop = validateContainerUpdates(newPod.Spec.InitContainers, oldPod.Spec.InitContainers, specPath.Child("initContainers")) + allErrs = append(allErrs, containerErrs...) + if stop { + return allErrs } // validate updated spec.activeDeadlineSeconds. two types of updates are allowed: @@ -1951,6 +2033,13 @@ func ValidatePodUpdate(newPod, oldPod *api.Pod) field.ErrorList { newContainers = append(newContainers, container) } mungedPod.Spec.Containers = newContainers + // munge initContainers[*].image + var newInitContainers []api.Container + for ix, container := range mungedPod.Spec.InitContainers { + container.Image = oldPod.Spec.InitContainers[ix].Image + newInitContainers = append(newInitContainers, container) + } + mungedPod.Spec.InitContainers = newInitContainers // munge spec.activeDeadlineSeconds mungedPod.Spec.ActiveDeadlineSeconds = nil if oldPod.Spec.ActiveDeadlineSeconds != nil { @@ -2064,10 +2153,13 @@ func ValidateService(service *api.Service) field.ErrorList { ipPath := specPath.Child("externalIPs") for i, ip := range service.Spec.ExternalIPs { idxPath := ipPath.Index(i) - if ip == "0.0.0.0" { - allErrs = append(allErrs, field.Invalid(idxPath, ip, "must be a valid IP address")) + if msgs := validation.IsValidIP(ip); len(msgs) != 0 { + for i := range msgs { + allErrs = append(allErrs, field.Invalid(idxPath, ip, msgs[i])) + } + } else { + allErrs = append(allErrs, validateNonSpecialIP(ip, idxPath)...) } - allErrs = append(allErrs, validateIpIsNotLinkLocalOrLoopback(ip, idxPath)...) } if len(service.Spec.Type) == 0 { @@ -2150,19 +2242,16 @@ func validateServicePort(sp *api.ServicePort, requireName, isHeadlessService boo if requireName && len(sp.Name) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child("name"), "")) } else if len(sp.Name) != 0 { - if msgs := validation.IsDNS1123Label(sp.Name); len(msgs) != 0 { - for i := range msgs { - allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), sp.Name, msgs[i])) - } - } else if allNames.Has(sp.Name) { + allErrs = append(allErrs, ValidateDNS1123Label(sp.Name, fldPath.Child("name"))...) + if allNames.Has(sp.Name) { allErrs = append(allErrs, field.Duplicate(fldPath.Child("name"), sp.Name)) } else { allNames.Insert(sp.Name) } } - if !validation.IsValidPortNum(int(sp.Port)) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, PortRangeErrorMsg)) + for _, msg := range validation.IsValidPortNum(int(sp.Port)) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), sp.Port, msg)) } if len(sp.Protocol) == 0 { @@ -2171,12 +2260,7 @@ func validateServicePort(sp *api.ServicePort, requireName, isHeadlessService boo allErrs = append(allErrs, field.NotSupported(fldPath.Child("protocol"), sp.Protocol, supportedPortProtocols.List())) } - if sp.TargetPort.Type == intstr.Int && !validation.IsValidPortNum(sp.TargetPort.IntValue()) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, PortRangeErrorMsg)) - } - if sp.TargetPort.Type == intstr.String && !validation.IsValidPortName(sp.TargetPort.StrVal) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("targetPort"), sp.TargetPort, PortNameErrorMsg)) - } + allErrs = append(allErrs, ValidatePortNumOrName(sp.TargetPort, fldPath.Child("targetPort"))...) // in the v1 API, targetPorts on headless services were tolerated. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. @@ -2243,7 +2327,7 @@ func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path return allErrs } -// Validates the given template and ensures that it is in accordance with the desrired selector and replicas. +// Validates the given template and ensures that it is in accordance with the desired selector and replicas. func ValidatePodTemplateSpecForRC(template *api.PodTemplateSpec, selectorMap map[string]string, replicas int32, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if template == nil { @@ -2337,10 +2421,14 @@ func ValidateTaintsInNodeAnnotations(annotations map[string]string, fldPath *fie } func ValidateNodeSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if annotations[api.PreferAvoidPodsAnnotationKey] != "" { + allErrs = append(allErrs, ValidateAvoidPodsInNodeAnnotations(annotations, fldPath)...) + } if annotations[api.TaintsAnnotationKey] != "" { - return ValidateTaintsInNodeAnnotations(annotations, fldPath) + allErrs = append(allErrs, ValidateTaintsInNodeAnnotations(annotations, fldPath)...) } - return field.ErrorList{} + return allErrs } // ValidateNode tests if required fields in the node are set. @@ -2442,7 +2530,7 @@ func validateContainerResourceName(value string, fldPath *field.Path) field.Erro // Validate resource names that can go in a resource quota // Refer to docs/design/resources.md for more details. -func validateResourceQuotaResourceName(value string, fldPath *field.Path) field.ErrorList { +func ValidateResourceQuotaResourceName(value string, fldPath *field.Path) field.ErrorList { allErrs := validateResourceName(value, fldPath) if len(strings.Split(value, "/")) == 1 { if !api.IsStandardQuotaResourceName(value) { @@ -2610,16 +2698,6 @@ func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *api.Serv return allErrs } -const SecretKeyFmt string = "\\.?" + validation.DNS1123LabelFmt + "(\\." + validation.DNS1123LabelFmt + ")*" - -var secretKeyRegexp = regexp.MustCompile("^" + SecretKeyFmt + "$") - -// IsSecretKey tests for a string that conforms to the definition of a -// subdomain in DNS (RFC 1123), except that a leading dot is allowed -func IsSecretKey(value string) bool { - return len(value) <= validation.DNS1123SubdomainMaxLength && secretKeyRegexp.MatchString(value) -} - // ValidateSecret tests if required fields in the Secret are set. func ValidateSecret(secret *api.Secret) field.ErrorList { allErrs := ValidateObjectMeta(&secret.ObjectMeta, true, ValidateSecretName, field.NewPath("metadata")) @@ -2627,8 +2705,8 @@ func ValidateSecret(secret *api.Secret) field.ErrorList { dataPath := field.NewPath("data") totalSize := 0 for key, value := range secret.Data { - if !IsSecretKey(key) { - allErrs = append(allErrs, field.Invalid(dataPath.Key(key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) + for _, msg := range validation.IsConfigMapKey(key) { + allErrs = append(allErrs, field.Invalid(dataPath.Key(key), key, msg)) } totalSize += len(value) } @@ -2725,8 +2803,8 @@ func ValidateConfigMap(cfg *api.ConfigMap) field.ErrorList { totalSize := 0 for key, value := range cfg.Data { - if !IsSecretKey(key) { - allErrs = append(allErrs, field.Invalid(field.NewPath("data").Key(key), key, fmt.Sprintf("must have at most %d characters and match regex %s", validation.DNS1123SubdomainMaxLength, SecretKeyFmt))) + for _, msg := range validation.IsConfigMapKey(key) { + allErrs = append(allErrs, field.Invalid(field.NewPath("data").Key(key), key, msg)) } totalSize += len(value) } @@ -2788,24 +2866,24 @@ func ValidateResourceRequirements(requirements *api.ResourceRequirements, fldPat } // validateResourceQuotaScopes ensures that each enumerated hard resource constraint is valid for set of scopes -func validateResourceQuotaScopes(resourceQuota *api.ResourceQuota) field.ErrorList { +func validateResourceQuotaScopes(resourceQuotaSpec *api.ResourceQuotaSpec, fld *field.Path) field.ErrorList { allErrs := field.ErrorList{} - if len(resourceQuota.Spec.Scopes) == 0 { + if len(resourceQuotaSpec.Scopes) == 0 { return allErrs } hardLimits := sets.NewString() - for k := range resourceQuota.Spec.Hard { + for k := range resourceQuotaSpec.Hard { hardLimits.Insert(string(k)) } - fldPath := field.NewPath("spec", "scopes") + fldPath := fld.Child("scopes") scopeSet := sets.NewString() - for _, scope := range resourceQuota.Spec.Scopes { + for _, scope := range resourceQuotaSpec.Scopes { if !api.IsStandardResourceQuotaScope(string(scope)) { - allErrs = append(allErrs, field.Invalid(fldPath, resourceQuota.Spec.Scopes, "unsupported scope")) + allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope")) } for _, k := range hardLimits.List() { if api.IsStandardQuotaResourceName(k) && !api.IsResourceQuotaScopeValidForResource(scope, k) { - allErrs = append(allErrs, field.Invalid(fldPath, resourceQuota.Spec.Scopes, "unsupported scope applied to resource")) + allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope applied to resource")) } } scopeSet.Insert(string(scope)) @@ -2816,7 +2894,7 @@ func validateResourceQuotaScopes(resourceQuota *api.ResourceQuota) field.ErrorLi } for _, invalidScopePair := range invalidScopePairs { if scopeSet.HasAll(invalidScopePair.List()...) { - allErrs = append(allErrs, field.Invalid(fldPath, resourceQuota.Spec.Scopes, "conflicting scopes")) + allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "conflicting scopes")) } } return allErrs @@ -2826,32 +2904,47 @@ func validateResourceQuotaScopes(resourceQuota *api.ResourceQuota) field.ErrorLi func ValidateResourceQuota(resourceQuota *api.ResourceQuota) field.ErrorList { allErrs := ValidateObjectMeta(&resourceQuota.ObjectMeta, true, ValidateResourceQuotaName, field.NewPath("metadata")) - fldPath := field.NewPath("spec", "hard") - for k, v := range resourceQuota.Spec.Hard { + allErrs = append(allErrs, ValidateResourceQuotaSpec(&resourceQuota.Spec, field.NewPath("spec"))...) + allErrs = append(allErrs, ValidateResourceQuotaStatus(&resourceQuota.Status, field.NewPath("status"))...) + + return allErrs +} + +func ValidateResourceQuotaStatus(status *api.ResourceQuotaStatus, fld *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + + fldPath := fld.Child("hard") + for k, v := range status.Hard { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) + allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...) + allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...) } - allErrs = append(allErrs, validateResourceQuotaScopes(resourceQuota)...) - - fldPath = field.NewPath("status", "hard") - for k, v := range resourceQuota.Status.Hard { + fldPath = fld.Child("used") + for k, v := range status.Used { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) + allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...) + allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...) } - fldPath = field.NewPath("status", "used") - for k, v := range resourceQuota.Status.Used { + + return allErrs +} + +func ValidateResourceQuotaSpec(resourceQuotaSpec *api.ResourceQuotaSpec, fld *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + + fldPath := fld.Child("hard") + for k, v := range resourceQuotaSpec.Hard { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) + allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...) + allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...) } + allErrs = append(allErrs, validateResourceQuotaScopes(resourceQuotaSpec, fld)...) return allErrs } -// validateResourceQuantityValue enforces that specified quantity is valid for specified resource -func validateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList { +// ValidateResourceQuantityValue enforces that specified quantity is valid for specified resource +func ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} allErrs = append(allErrs, ValidateNonnegativeQuantity(value, fldPath)...) if api.IsIntegerResourceName(resource) { @@ -2866,15 +2959,10 @@ func validateResourceQuantityValue(resource string, value resource.Quantity, fld // newResourceQuota is updated with fields that cannot be changed. func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.ResourceQuota) field.ErrorList { allErrs := ValidateObjectMetaUpdate(&newResourceQuota.ObjectMeta, &oldResourceQuota.ObjectMeta, field.NewPath("metadata")) - fldPath := field.NewPath("spec", "hard") - for k, v := range newResourceQuota.Spec.Hard { - resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) - } + allErrs = append(allErrs, ValidateResourceQuotaSpec(&newResourceQuota.Spec, field.NewPath("spec"))...) // ensure scopes cannot change, and that resources are still valid for scope - fldPath = field.NewPath("spec", "scopes") + fldPath := field.NewPath("spec", "scopes") oldScopes := sets.NewString() newScopes := sets.NewString() for _, scope := range newResourceQuota.Spec.Scopes { @@ -2886,7 +2974,6 @@ func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *api.Resourc if !oldScopes.Equal(newScopes) { allErrs = append(allErrs, field.Invalid(fldPath, newResourceQuota.Spec.Scopes, "field is immutable")) } - allErrs = append(allErrs, validateResourceQuotaScopes(newResourceQuota)...) newResourceQuota.Status = oldResourceQuota.Status return allErrs @@ -2902,14 +2989,14 @@ func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *api.R fldPath := field.NewPath("status", "hard") for k, v := range newResourceQuota.Status.Hard { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) + allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...) + allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...) } fldPath = field.NewPath("status", "used") for k, v := range newResourceQuota.Status.Used { resPath := fldPath.Key(string(k)) - allErrs = append(allErrs, validateResourceQuotaResourceName(string(k), resPath)...) - allErrs = append(allErrs, validateResourceQuantityValue(string(k), v, resPath)...) + allErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...) + allErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...) } newResourceQuota.Spec = oldResourceQuota.Spec return allErrs @@ -3021,29 +3108,33 @@ func validateEndpointSubsets(subsets []api.EndpointSubset, fldPath *field.Path) func validateEndpointAddress(address *api.EndpointAddress, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - if !validation.IsValidIP(address.IP) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), address.IP, "must be a valid IP address")) + for _, msg := range validation.IsValidIP(address.IP) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("ip"), address.IP, msg)) } if len(address.Hostname) > 0 { - for _, msg := range validation.IsDNS1123Label(address.Hostname) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("hostname"), address.Hostname, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(address.Hostname, fldPath.Child("hostname"))...) } if len(allErrs) > 0 { return allErrs } - return validateIpIsNotLinkLocalOrLoopback(address.IP, fldPath.Child("ip")) + allErrs = append(allErrs, validateNonSpecialIP(address.IP, fldPath.Child("ip"))...) + return allErrs } -func validateIpIsNotLinkLocalOrLoopback(ipAddress string, fldPath *field.Path) field.ErrorList { - // We disallow some IPs as endpoints or external-ips. Specifically, loopback addresses are - // nonsensical and link-local addresses tend to be used for node-centric purposes (e.g. metadata service). +func validateNonSpecialIP(ipAddress string, fldPath *field.Path) field.ErrorList { + // We disallow some IPs as endpoints or external-ips. Specifically, + // unspecified and loopback addresses are nonsensical and link-local + // addresses tend to be used for node-centric purposes (e.g. metadata + // service). allErrs := field.ErrorList{} ip := net.ParseIP(ipAddress) if ip == nil { allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "must be a valid IP address")) return allErrs } + if ip.IsUnspecified() { + allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be unspecified (0.0.0.0)")) + } if ip.IsLoopback() { allErrs = append(allErrs, field.Invalid(fldPath, ipAddress, "may not be in the loopback range (127.0.0.0/8)")) } @@ -3061,12 +3152,10 @@ func validateEndpointPort(port *api.EndpointPort, requireName bool, fldPath *fie if requireName && len(port.Name) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child("name"), "")) } else if len(port.Name) != 0 { - for _, msg := range validation.IsDNS1123Label(port.Name) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), port.Name, msg)) - } + allErrs = append(allErrs, ValidateDNS1123Label(port.Name, fldPath.Child("name"))...) } - if !validation.IsValidPortNum(int(port.Port)) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), port.Port, PortRangeErrorMsg)) + for _, msg := range validation.IsValidPortNum(int(port.Port)) { + allErrs = append(allErrs, field.Invalid(fldPath.Child("port"), port.Port, msg)) } if len(port.Protocol) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child("protocol"), "")) @@ -3147,6 +3236,7 @@ func ValidateLoadBalancerStatus(status *api.LoadBalancerStatus, fldPath *field.P return allErrs } +// TODO: remove this after we EOL the annotation that carries it. func isValidHostnamesMap(serializedPodHostNames string) bool { if len(serializedPodHostNames) == 0 { return false diff --git a/vendor/k8s.io/kubernetes/pkg/api/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/api/zz_generated.deepcopy.go new file mode 100644 index 000000000000..2a4dfb7bb681 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/api/zz_generated.deepcopy.go @@ -0,0 +1,3608 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package api + +import ( + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + fields "k8s.io/kubernetes/pkg/fields" + labels "k8s.io/kubernetes/pkg/labels" + runtime "k8s.io/kubernetes/pkg/runtime" + types "k8s.io/kubernetes/pkg/types" + reflect "reflect" +) + +func init() { + if err := Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_AWSElasticBlockStoreVolumeSource, InType: reflect.TypeOf(func() *AWSElasticBlockStoreVolumeSource { var x *AWSElasticBlockStoreVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Affinity, InType: reflect.TypeOf(func() *Affinity { var x *Affinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_AttachedVolume, InType: reflect.TypeOf(func() *AttachedVolume { var x *AttachedVolume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_AvoidPods, InType: reflect.TypeOf(func() *AvoidPods { var x *AvoidPods; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_AzureFileVolumeSource, InType: reflect.TypeOf(func() *AzureFileVolumeSource { var x *AzureFileVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Binding, InType: reflect.TypeOf(func() *Binding { var x *Binding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Capabilities, InType: reflect.TypeOf(func() *Capabilities { var x *Capabilities; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_CephFSVolumeSource, InType: reflect.TypeOf(func() *CephFSVolumeSource { var x *CephFSVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_CinderVolumeSource, InType: reflect.TypeOf(func() *CinderVolumeSource { var x *CinderVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ComponentCondition, InType: reflect.TypeOf(func() *ComponentCondition { var x *ComponentCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ComponentStatus, InType: reflect.TypeOf(func() *ComponentStatus { var x *ComponentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ComponentStatusList, InType: reflect.TypeOf(func() *ComponentStatusList { var x *ComponentStatusList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ConfigMap, InType: reflect.TypeOf(func() *ConfigMap { var x *ConfigMap; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ConfigMapKeySelector, InType: reflect.TypeOf(func() *ConfigMapKeySelector { var x *ConfigMapKeySelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ConfigMapList, InType: reflect.TypeOf(func() *ConfigMapList { var x *ConfigMapList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ConfigMapVolumeSource, InType: reflect.TypeOf(func() *ConfigMapVolumeSource { var x *ConfigMapVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Container, InType: reflect.TypeOf(func() *Container { var x *Container; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerImage, InType: reflect.TypeOf(func() *ContainerImage { var x *ContainerImage; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerPort, InType: reflect.TypeOf(func() *ContainerPort { var x *ContainerPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerState, InType: reflect.TypeOf(func() *ContainerState { var x *ContainerState; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerStateRunning, InType: reflect.TypeOf(func() *ContainerStateRunning { var x *ContainerStateRunning; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerStateTerminated, InType: reflect.TypeOf(func() *ContainerStateTerminated { var x *ContainerStateTerminated; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerStateWaiting, InType: reflect.TypeOf(func() *ContainerStateWaiting { var x *ContainerStateWaiting; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ContainerStatus, InType: reflect.TypeOf(func() *ContainerStatus { var x *ContainerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ConversionError, InType: reflect.TypeOf(func() *ConversionError { var x *ConversionError; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_DaemonEndpoint, InType: reflect.TypeOf(func() *DaemonEndpoint { var x *DaemonEndpoint; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_DeleteOptions, InType: reflect.TypeOf(func() *DeleteOptions { var x *DeleteOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_DownwardAPIVolumeFile, InType: reflect.TypeOf(func() *DownwardAPIVolumeFile { var x *DownwardAPIVolumeFile; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_DownwardAPIVolumeSource, InType: reflect.TypeOf(func() *DownwardAPIVolumeSource { var x *DownwardAPIVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EmptyDirVolumeSource, InType: reflect.TypeOf(func() *EmptyDirVolumeSource { var x *EmptyDirVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EndpointAddress, InType: reflect.TypeOf(func() *EndpointAddress { var x *EndpointAddress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EndpointPort, InType: reflect.TypeOf(func() *EndpointPort { var x *EndpointPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EndpointSubset, InType: reflect.TypeOf(func() *EndpointSubset { var x *EndpointSubset; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Endpoints, InType: reflect.TypeOf(func() *Endpoints { var x *Endpoints; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EndpointsList, InType: reflect.TypeOf(func() *EndpointsList { var x *EndpointsList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EnvVar, InType: reflect.TypeOf(func() *EnvVar { var x *EnvVar; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EnvVarSource, InType: reflect.TypeOf(func() *EnvVarSource { var x *EnvVarSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Event, InType: reflect.TypeOf(func() *Event { var x *Event; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EventList, InType: reflect.TypeOf(func() *EventList { var x *EventList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_EventSource, InType: reflect.TypeOf(func() *EventSource { var x *EventSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ExecAction, InType: reflect.TypeOf(func() *ExecAction { var x *ExecAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ExportOptions, InType: reflect.TypeOf(func() *ExportOptions { var x *ExportOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_FCVolumeSource, InType: reflect.TypeOf(func() *FCVolumeSource { var x *FCVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_FlexVolumeSource, InType: reflect.TypeOf(func() *FlexVolumeSource { var x *FlexVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_FlockerVolumeSource, InType: reflect.TypeOf(func() *FlockerVolumeSource { var x *FlockerVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_GCEPersistentDiskVolumeSource, InType: reflect.TypeOf(func() *GCEPersistentDiskVolumeSource { var x *GCEPersistentDiskVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_GitRepoVolumeSource, InType: reflect.TypeOf(func() *GitRepoVolumeSource { var x *GitRepoVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_GlusterfsVolumeSource, InType: reflect.TypeOf(func() *GlusterfsVolumeSource { var x *GlusterfsVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_HTTPGetAction, InType: reflect.TypeOf(func() *HTTPGetAction { var x *HTTPGetAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_HTTPHeader, InType: reflect.TypeOf(func() *HTTPHeader { var x *HTTPHeader; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Handler, InType: reflect.TypeOf(func() *Handler { var x *Handler; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_HostPathVolumeSource, InType: reflect.TypeOf(func() *HostPathVolumeSource { var x *HostPathVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ISCSIVolumeSource, InType: reflect.TypeOf(func() *ISCSIVolumeSource { var x *ISCSIVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_KeyToPath, InType: reflect.TypeOf(func() *KeyToPath { var x *KeyToPath; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Lifecycle, InType: reflect.TypeOf(func() *Lifecycle { var x *Lifecycle; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LimitRange, InType: reflect.TypeOf(func() *LimitRange { var x *LimitRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LimitRangeItem, InType: reflect.TypeOf(func() *LimitRangeItem { var x *LimitRangeItem; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LimitRangeList, InType: reflect.TypeOf(func() *LimitRangeList { var x *LimitRangeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LimitRangeSpec, InType: reflect.TypeOf(func() *LimitRangeSpec { var x *LimitRangeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_List, InType: reflect.TypeOf(func() *List { var x *List; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ListOptions, InType: reflect.TypeOf(func() *ListOptions { var x *ListOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LoadBalancerIngress, InType: reflect.TypeOf(func() *LoadBalancerIngress { var x *LoadBalancerIngress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LoadBalancerStatus, InType: reflect.TypeOf(func() *LoadBalancerStatus { var x *LoadBalancerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_LocalObjectReference, InType: reflect.TypeOf(func() *LocalObjectReference { var x *LocalObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NFSVolumeSource, InType: reflect.TypeOf(func() *NFSVolumeSource { var x *NFSVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Namespace, InType: reflect.TypeOf(func() *Namespace { var x *Namespace; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NamespaceList, InType: reflect.TypeOf(func() *NamespaceList { var x *NamespaceList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NamespaceSpec, InType: reflect.TypeOf(func() *NamespaceSpec { var x *NamespaceSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NamespaceStatus, InType: reflect.TypeOf(func() *NamespaceStatus { var x *NamespaceStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Node, InType: reflect.TypeOf(func() *Node { var x *Node; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeAddress, InType: reflect.TypeOf(func() *NodeAddress { var x *NodeAddress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeAffinity, InType: reflect.TypeOf(func() *NodeAffinity { var x *NodeAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeCondition, InType: reflect.TypeOf(func() *NodeCondition { var x *NodeCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeDaemonEndpoints, InType: reflect.TypeOf(func() *NodeDaemonEndpoints { var x *NodeDaemonEndpoints; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeList, InType: reflect.TypeOf(func() *NodeList { var x *NodeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeProxyOptions, InType: reflect.TypeOf(func() *NodeProxyOptions { var x *NodeProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeResources, InType: reflect.TypeOf(func() *NodeResources { var x *NodeResources; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeSelector, InType: reflect.TypeOf(func() *NodeSelector { var x *NodeSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeSelectorRequirement, InType: reflect.TypeOf(func() *NodeSelectorRequirement { var x *NodeSelectorRequirement; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeSelectorTerm, InType: reflect.TypeOf(func() *NodeSelectorTerm { var x *NodeSelectorTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeSpec, InType: reflect.TypeOf(func() *NodeSpec { var x *NodeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeStatus, InType: reflect.TypeOf(func() *NodeStatus { var x *NodeStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_NodeSystemInfo, InType: reflect.TypeOf(func() *NodeSystemInfo { var x *NodeSystemInfo; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ObjectFieldSelector, InType: reflect.TypeOf(func() *ObjectFieldSelector { var x *ObjectFieldSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ObjectMeta, InType: reflect.TypeOf(func() *ObjectMeta { var x *ObjectMeta; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ObjectReference, InType: reflect.TypeOf(func() *ObjectReference { var x *ObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_OwnerReference, InType: reflect.TypeOf(func() *OwnerReference { var x *OwnerReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolume, InType: reflect.TypeOf(func() *PersistentVolume { var x *PersistentVolume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeClaim, InType: reflect.TypeOf(func() *PersistentVolumeClaim { var x *PersistentVolumeClaim; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeClaimList, InType: reflect.TypeOf(func() *PersistentVolumeClaimList { var x *PersistentVolumeClaimList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeClaimSpec, InType: reflect.TypeOf(func() *PersistentVolumeClaimSpec { var x *PersistentVolumeClaimSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeClaimStatus, InType: reflect.TypeOf(func() *PersistentVolumeClaimStatus { var x *PersistentVolumeClaimStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeClaimVolumeSource, InType: reflect.TypeOf(func() *PersistentVolumeClaimVolumeSource { var x *PersistentVolumeClaimVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeList, InType: reflect.TypeOf(func() *PersistentVolumeList { var x *PersistentVolumeList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeSource, InType: reflect.TypeOf(func() *PersistentVolumeSource { var x *PersistentVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeSpec, InType: reflect.TypeOf(func() *PersistentVolumeSpec { var x *PersistentVolumeSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PersistentVolumeStatus, InType: reflect.TypeOf(func() *PersistentVolumeStatus { var x *PersistentVolumeStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Pod, InType: reflect.TypeOf(func() *Pod { var x *Pod; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodAffinity, InType: reflect.TypeOf(func() *PodAffinity { var x *PodAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodAffinityTerm, InType: reflect.TypeOf(func() *PodAffinityTerm { var x *PodAffinityTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodAntiAffinity, InType: reflect.TypeOf(func() *PodAntiAffinity { var x *PodAntiAffinity; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodAttachOptions, InType: reflect.TypeOf(func() *PodAttachOptions { var x *PodAttachOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodCondition, InType: reflect.TypeOf(func() *PodCondition { var x *PodCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodExecOptions, InType: reflect.TypeOf(func() *PodExecOptions { var x *PodExecOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodList, InType: reflect.TypeOf(func() *PodList { var x *PodList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodLogOptions, InType: reflect.TypeOf(func() *PodLogOptions { var x *PodLogOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodProxyOptions, InType: reflect.TypeOf(func() *PodProxyOptions { var x *PodProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodSecurityContext, InType: reflect.TypeOf(func() *PodSecurityContext { var x *PodSecurityContext; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodSignature, InType: reflect.TypeOf(func() *PodSignature { var x *PodSignature; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodSpec, InType: reflect.TypeOf(func() *PodSpec { var x *PodSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodStatus, InType: reflect.TypeOf(func() *PodStatus { var x *PodStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodStatusResult, InType: reflect.TypeOf(func() *PodStatusResult { var x *PodStatusResult; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodTemplate, InType: reflect.TypeOf(func() *PodTemplate { var x *PodTemplate; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodTemplateList, InType: reflect.TypeOf(func() *PodTemplateList { var x *PodTemplateList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PodTemplateSpec, InType: reflect.TypeOf(func() *PodTemplateSpec { var x *PodTemplateSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Preconditions, InType: reflect.TypeOf(func() *Preconditions { var x *Preconditions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PreferAvoidPodsEntry, InType: reflect.TypeOf(func() *PreferAvoidPodsEntry { var x *PreferAvoidPodsEntry; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_PreferredSchedulingTerm, InType: reflect.TypeOf(func() *PreferredSchedulingTerm { var x *PreferredSchedulingTerm; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Probe, InType: reflect.TypeOf(func() *Probe { var x *Probe; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_RBDVolumeSource, InType: reflect.TypeOf(func() *RBDVolumeSource { var x *RBDVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_RangeAllocation, InType: reflect.TypeOf(func() *RangeAllocation { var x *RangeAllocation; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ReplicationController, InType: reflect.TypeOf(func() *ReplicationController { var x *ReplicationController; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ReplicationControllerList, InType: reflect.TypeOf(func() *ReplicationControllerList { var x *ReplicationControllerList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ReplicationControllerSpec, InType: reflect.TypeOf(func() *ReplicationControllerSpec { var x *ReplicationControllerSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ReplicationControllerStatus, InType: reflect.TypeOf(func() *ReplicationControllerStatus { var x *ReplicationControllerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceFieldSelector, InType: reflect.TypeOf(func() *ResourceFieldSelector { var x *ResourceFieldSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceQuota, InType: reflect.TypeOf(func() *ResourceQuota { var x *ResourceQuota; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceQuotaList, InType: reflect.TypeOf(func() *ResourceQuotaList { var x *ResourceQuotaList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceQuotaSpec, InType: reflect.TypeOf(func() *ResourceQuotaSpec { var x *ResourceQuotaSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceQuotaStatus, InType: reflect.TypeOf(func() *ResourceQuotaStatus { var x *ResourceQuotaStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ResourceRequirements, InType: reflect.TypeOf(func() *ResourceRequirements { var x *ResourceRequirements; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SELinuxOptions, InType: reflect.TypeOf(func() *SELinuxOptions { var x *SELinuxOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Secret, InType: reflect.TypeOf(func() *Secret { var x *Secret; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SecretKeySelector, InType: reflect.TypeOf(func() *SecretKeySelector { var x *SecretKeySelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SecretList, InType: reflect.TypeOf(func() *SecretList { var x *SecretList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SecretVolumeSource, InType: reflect.TypeOf(func() *SecretVolumeSource { var x *SecretVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SecurityContext, InType: reflect.TypeOf(func() *SecurityContext { var x *SecurityContext; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_SerializedReference, InType: reflect.TypeOf(func() *SerializedReference { var x *SerializedReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Service, InType: reflect.TypeOf(func() *Service { var x *Service; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceAccount, InType: reflect.TypeOf(func() *ServiceAccount { var x *ServiceAccount; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceAccountList, InType: reflect.TypeOf(func() *ServiceAccountList { var x *ServiceAccountList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceList, InType: reflect.TypeOf(func() *ServiceList { var x *ServiceList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServicePort, InType: reflect.TypeOf(func() *ServicePort { var x *ServicePort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceProxyOptions, InType: reflect.TypeOf(func() *ServiceProxyOptions { var x *ServiceProxyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceSpec, InType: reflect.TypeOf(func() *ServiceSpec { var x *ServiceSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_ServiceStatus, InType: reflect.TypeOf(func() *ServiceStatus { var x *ServiceStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_TCPSocketAction, InType: reflect.TypeOf(func() *TCPSocketAction { var x *TCPSocketAction; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Taint, InType: reflect.TypeOf(func() *Taint { var x *Taint; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Toleration, InType: reflect.TypeOf(func() *Toleration { var x *Toleration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_Volume, InType: reflect.TypeOf(func() *Volume { var x *Volume; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_VolumeMount, InType: reflect.TypeOf(func() *VolumeMount { var x *VolumeMount; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_VolumeSource, InType: reflect.TypeOf(func() *VolumeSource { var x *VolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_VsphereVirtualDiskVolumeSource, InType: reflect.TypeOf(func() *VsphereVirtualDiskVolumeSource { var x *VsphereVirtualDiskVolumeSource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_api_WeightedPodAffinityTerm, InType: reflect.TypeOf(func() *WeightedPodAffinityTerm { var x *WeightedPodAffinityTerm; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_api_AWSElasticBlockStoreVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AWSElasticBlockStoreVolumeSource) + out := out.(*AWSElasticBlockStoreVolumeSource) + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.Partition = in.Partition + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_Affinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Affinity) + out := out.(*Affinity) + if in.NodeAffinity != nil { + in, out := &in.NodeAffinity, &out.NodeAffinity + *out = new(NodeAffinity) + if err := DeepCopy_api_NodeAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.NodeAffinity = nil + } + if in.PodAffinity != nil { + in, out := &in.PodAffinity, &out.PodAffinity + *out = new(PodAffinity) + if err := DeepCopy_api_PodAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.PodAffinity = nil + } + if in.PodAntiAffinity != nil { + in, out := &in.PodAntiAffinity, &out.PodAntiAffinity + *out = new(PodAntiAffinity) + if err := DeepCopy_api_PodAntiAffinity(*in, *out, c); err != nil { + return err + } + } else { + out.PodAntiAffinity = nil + } + return nil + } +} + +func DeepCopy_api_AttachedVolume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AttachedVolume) + out := out.(*AttachedVolume) + out.Name = in.Name + out.DevicePath = in.DevicePath + return nil + } +} + +func DeepCopy_api_AvoidPods(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AvoidPods) + out := out.(*AvoidPods) + if in.PreferAvoidPods != nil { + in, out := &in.PreferAvoidPods, &out.PreferAvoidPods + *out = make([]PreferAvoidPodsEntry, len(*in)) + for i := range *in { + if err := DeepCopy_api_PreferAvoidPodsEntry(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferAvoidPods = nil + } + return nil + } +} + +func DeepCopy_api_AzureFileVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*AzureFileVolumeSource) + out := out.(*AzureFileVolumeSource) + out.SecretName = in.SecretName + out.ShareName = in.ShareName + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_Binding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Binding) + out := out.(*Binding) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Target = in.Target + return nil + } +} + +func DeepCopy_api_Capabilities(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Capabilities) + out := out.(*Capabilities) + if in.Add != nil { + in, out := &in.Add, &out.Add + *out = make([]Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Add = nil + } + if in.Drop != nil { + in, out := &in.Drop, &out.Drop + *out = make([]Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Drop = nil + } + return nil + } +} + +func DeepCopy_api_CephFSVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CephFSVolumeSource) + out := out.(*CephFSVolumeSource) + if in.Monitors != nil { + in, out := &in.Monitors, &out.Monitors + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Monitors = nil + } + out.Path = in.Path + out.User = in.User + out.SecretFile = in.SecretFile + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_CinderVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CinderVolumeSource) + out := out.(*CinderVolumeSource) + out.VolumeID = in.VolumeID + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_ComponentCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentCondition) + out := out.(*ComponentCondition) + out.Type = in.Type + out.Status = in.Status + out.Message = in.Message + out.Error = in.Error + return nil + } +} + +func DeepCopy_api_ComponentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentStatus) + out := out.(*ComponentStatus) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]ComponentCondition, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Conditions = nil + } + return nil + } +} + +func DeepCopy_api_ComponentStatusList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ComponentStatusList) + out := out.(*ComponentStatusList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ComponentStatus, len(*in)) + for i := range *in { + if err := DeepCopy_api_ComponentStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ConfigMap(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMap) + out := out.(*ConfigMap) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_api_ConfigMapKeySelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapKeySelector) + out := out.(*ConfigMapKeySelector) + out.LocalObjectReference = in.LocalObjectReference + out.Key = in.Key + return nil + } +} + +func DeepCopy_api_ConfigMapList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapList) + out := out.(*ConfigMapList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ConfigMap, len(*in)) + for i := range *in { + if err := DeepCopy_api_ConfigMap(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ConfigMapVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConfigMapVolumeSource) + out := out.(*ConfigMapVolumeSource) + out.LocalObjectReference = in.LocalObjectReference + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KeyToPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_Container(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Container) + out := out.(*Container) + out.Name = in.Name + out.Image = in.Image + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + if in.Args != nil { + in, out := &in.Args, &out.Args + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Args = nil + } + out.WorkingDir = in.WorkingDir + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]ContainerPort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]EnvVar, len(*in)) + for i := range *in { + if err := DeepCopy_api_EnvVar(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Env = nil + } + if err := DeepCopy_api_ResourceRequirements(&in.Resources, &out.Resources, c); err != nil { + return err + } + if in.VolumeMounts != nil { + in, out := &in.VolumeMounts, &out.VolumeMounts + *out = make([]VolumeMount, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumeMounts = nil + } + if in.LivenessProbe != nil { + in, out := &in.LivenessProbe, &out.LivenessProbe + *out = new(Probe) + if err := DeepCopy_api_Probe(*in, *out, c); err != nil { + return err + } + } else { + out.LivenessProbe = nil + } + if in.ReadinessProbe != nil { + in, out := &in.ReadinessProbe, &out.ReadinessProbe + *out = new(Probe) + if err := DeepCopy_api_Probe(*in, *out, c); err != nil { + return err + } + } else { + out.ReadinessProbe = nil + } + if in.Lifecycle != nil { + in, out := &in.Lifecycle, &out.Lifecycle + *out = new(Lifecycle) + if err := DeepCopy_api_Lifecycle(*in, *out, c); err != nil { + return err + } + } else { + out.Lifecycle = nil + } + out.TerminationMessagePath = in.TerminationMessagePath + out.ImagePullPolicy = in.ImagePullPolicy + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(SecurityContext) + if err := DeepCopy_api_SecurityContext(*in, *out, c); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + out.Stdin = in.Stdin + out.StdinOnce = in.StdinOnce + out.TTY = in.TTY + return nil + } +} + +func DeepCopy_api_ContainerImage(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerImage) + out := out.(*ContainerImage) + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Names = nil + } + out.SizeBytes = in.SizeBytes + return nil + } +} + +func DeepCopy_api_ContainerPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerPort) + out := out.(*ContainerPort) + out.Name = in.Name + out.HostPort = in.HostPort + out.ContainerPort = in.ContainerPort + out.Protocol = in.Protocol + out.HostIP = in.HostIP + return nil + } +} + +func DeepCopy_api_ContainerState(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerState) + out := out.(*ContainerState) + if in.Waiting != nil { + in, out := &in.Waiting, &out.Waiting + *out = new(ContainerStateWaiting) + **out = **in + } else { + out.Waiting = nil + } + if in.Running != nil { + in, out := &in.Running, &out.Running + *out = new(ContainerStateRunning) + if err := DeepCopy_api_ContainerStateRunning(*in, *out, c); err != nil { + return err + } + } else { + out.Running = nil + } + if in.Terminated != nil { + in, out := &in.Terminated, &out.Terminated + *out = new(ContainerStateTerminated) + if err := DeepCopy_api_ContainerStateTerminated(*in, *out, c); err != nil { + return err + } + } else { + out.Terminated = nil + } + return nil + } +} + +func DeepCopy_api_ContainerStateRunning(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateRunning) + out := out.(*ContainerStateRunning) + out.StartedAt = in.StartedAt.DeepCopy() + return nil + } +} + +func DeepCopy_api_ContainerStateTerminated(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateTerminated) + out := out.(*ContainerStateTerminated) + out.ExitCode = in.ExitCode + out.Signal = in.Signal + out.Reason = in.Reason + out.Message = in.Message + out.StartedAt = in.StartedAt.DeepCopy() + out.FinishedAt = in.FinishedAt.DeepCopy() + out.ContainerID = in.ContainerID + return nil + } +} + +func DeepCopy_api_ContainerStateWaiting(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStateWaiting) + out := out.(*ContainerStateWaiting) + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_api_ContainerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ContainerStatus) + out := out.(*ContainerStatus) + out.Name = in.Name + if err := DeepCopy_api_ContainerState(&in.State, &out.State, c); err != nil { + return err + } + if err := DeepCopy_api_ContainerState(&in.LastTerminationState, &out.LastTerminationState, c); err != nil { + return err + } + out.Ready = in.Ready + out.RestartCount = in.RestartCount + out.Image = in.Image + out.ImageID = in.ImageID + out.ContainerID = in.ContainerID + return nil + } +} + +func DeepCopy_api_ConversionError(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ConversionError) + out := out.(*ConversionError) + if in.In == nil { + out.In = nil + } else if newVal, err := c.DeepCopy(&in.In); err != nil { + return err + } else { + out.In = *newVal.(*interface{}) + } + if in.Out == nil { + out.Out = nil + } else if newVal, err := c.DeepCopy(&in.Out); err != nil { + return err + } else { + out.Out = *newVal.(*interface{}) + } + out.Message = in.Message + return nil + } +} + +func DeepCopy_api_DaemonEndpoint(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonEndpoint) + out := out.(*DaemonEndpoint) + out.Port = in.Port + return nil + } +} + +func DeepCopy_api_DeleteOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeleteOptions) + out := out.(*DeleteOptions) + out.TypeMeta = in.TypeMeta + if in.GracePeriodSeconds != nil { + in, out := &in.GracePeriodSeconds, &out.GracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.GracePeriodSeconds = nil + } + if in.Preconditions != nil { + in, out := &in.Preconditions, &out.Preconditions + *out = new(Preconditions) + if err := DeepCopy_api_Preconditions(*in, *out, c); err != nil { + return err + } + } else { + out.Preconditions = nil + } + if in.OrphanDependents != nil { + in, out := &in.OrphanDependents, &out.OrphanDependents + *out = new(bool) + **out = **in + } else { + out.OrphanDependents = nil + } + return nil + } +} + +func DeepCopy_api_DownwardAPIVolumeFile(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DownwardAPIVolumeFile) + out := out.(*DownwardAPIVolumeFile) + out.Path = in.Path + if in.FieldRef != nil { + in, out := &in.FieldRef, &out.FieldRef + *out = new(ObjectFieldSelector) + **out = **in + } else { + out.FieldRef = nil + } + if in.ResourceFieldRef != nil { + in, out := &in.ResourceFieldRef, &out.ResourceFieldRef + *out = new(ResourceFieldSelector) + if err := DeepCopy_api_ResourceFieldSelector(*in, *out, c); err != nil { + return err + } + } else { + out.ResourceFieldRef = nil + } + return nil + } +} + +func DeepCopy_api_DownwardAPIVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DownwardAPIVolumeSource) + out := out.(*DownwardAPIVolumeSource) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DownwardAPIVolumeFile, len(*in)) + for i := range *in { + if err := DeepCopy_api_DownwardAPIVolumeFile(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_EmptyDirVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EmptyDirVolumeSource) + out := out.(*EmptyDirVolumeSource) + out.Medium = in.Medium + return nil + } +} + +func DeepCopy_api_EndpointAddress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointAddress) + out := out.(*EndpointAddress) + out.IP = in.IP + out.Hostname = in.Hostname + if in.TargetRef != nil { + in, out := &in.TargetRef, &out.TargetRef + *out = new(ObjectReference) + **out = **in + } else { + out.TargetRef = nil + } + return nil + } +} + +func DeepCopy_api_EndpointPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointPort) + out := out.(*EndpointPort) + out.Name = in.Name + out.Port = in.Port + out.Protocol = in.Protocol + return nil + } +} + +func DeepCopy_api_EndpointSubset(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointSubset) + out := out.(*EndpointSubset) + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]EndpointAddress, len(*in)) + for i := range *in { + if err := DeepCopy_api_EndpointAddress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Addresses = nil + } + if in.NotReadyAddresses != nil { + in, out := &in.NotReadyAddresses, &out.NotReadyAddresses + *out = make([]EndpointAddress, len(*in)) + for i := range *in { + if err := DeepCopy_api_EndpointAddress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.NotReadyAddresses = nil + } + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]EndpointPort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + return nil + } +} + +func DeepCopy_api_Endpoints(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Endpoints) + out := out.(*Endpoints) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subsets != nil { + in, out := &in.Subsets, &out.Subsets + *out = make([]EndpointSubset, len(*in)) + for i := range *in { + if err := DeepCopy_api_EndpointSubset(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Subsets = nil + } + return nil + } +} + +func DeepCopy_api_EndpointsList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EndpointsList) + out := out.(*EndpointsList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Endpoints, len(*in)) + for i := range *in { + if err := DeepCopy_api_Endpoints(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_EnvVar(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EnvVar) + out := out.(*EnvVar) + out.Name = in.Name + out.Value = in.Value + if in.ValueFrom != nil { + in, out := &in.ValueFrom, &out.ValueFrom + *out = new(EnvVarSource) + if err := DeepCopy_api_EnvVarSource(*in, *out, c); err != nil { + return err + } + } else { + out.ValueFrom = nil + } + return nil + } +} + +func DeepCopy_api_EnvVarSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EnvVarSource) + out := out.(*EnvVarSource) + if in.FieldRef != nil { + in, out := &in.FieldRef, &out.FieldRef + *out = new(ObjectFieldSelector) + **out = **in + } else { + out.FieldRef = nil + } + if in.ResourceFieldRef != nil { + in, out := &in.ResourceFieldRef, &out.ResourceFieldRef + *out = new(ResourceFieldSelector) + if err := DeepCopy_api_ResourceFieldSelector(*in, *out, c); err != nil { + return err + } + } else { + out.ResourceFieldRef = nil + } + if in.ConfigMapKeyRef != nil { + in, out := &in.ConfigMapKeyRef, &out.ConfigMapKeyRef + *out = new(ConfigMapKeySelector) + **out = **in + } else { + out.ConfigMapKeyRef = nil + } + if in.SecretKeyRef != nil { + in, out := &in.SecretKeyRef, &out.SecretKeyRef + *out = new(SecretKeySelector) + **out = **in + } else { + out.SecretKeyRef = nil + } + return nil + } +} + +func DeepCopy_api_Event(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Event) + out := out.(*Event) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.InvolvedObject = in.InvolvedObject + out.Reason = in.Reason + out.Message = in.Message + out.Source = in.Source + out.FirstTimestamp = in.FirstTimestamp.DeepCopy() + out.LastTimestamp = in.LastTimestamp.DeepCopy() + out.Count = in.Count + out.Type = in.Type + return nil + } +} + +func DeepCopy_api_EventList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EventList) + out := out.(*EventList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Event, len(*in)) + for i := range *in { + if err := DeepCopy_api_Event(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_EventSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*EventSource) + out := out.(*EventSource) + out.Component = in.Component + out.Host = in.Host + return nil + } +} + +func DeepCopy_api_ExecAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExecAction) + out := out.(*ExecAction) + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + return nil + } +} + +func DeepCopy_api_ExportOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExportOptions) + out := out.(*ExportOptions) + out.TypeMeta = in.TypeMeta + out.Export = in.Export + out.Exact = in.Exact + return nil + } +} + +func DeepCopy_api_FCVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FCVolumeSource) + out := out.(*FCVolumeSource) + if in.TargetWWNs != nil { + in, out := &in.TargetWWNs, &out.TargetWWNs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.TargetWWNs = nil + } + if in.Lun != nil { + in, out := &in.Lun, &out.Lun + *out = new(int32) + **out = **in + } else { + out.Lun = nil + } + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_FlexVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FlexVolumeSource) + out := out.(*FlexVolumeSource) + out.Driver = in.Driver + out.FSType = in.FSType + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + if in.Options != nil { + in, out := &in.Options, &out.Options + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Options = nil + } + return nil + } +} + +func DeepCopy_api_FlockerVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FlockerVolumeSource) + out := out.(*FlockerVolumeSource) + out.DatasetName = in.DatasetName + return nil + } +} + +func DeepCopy_api_GCEPersistentDiskVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GCEPersistentDiskVolumeSource) + out := out.(*GCEPersistentDiskVolumeSource) + out.PDName = in.PDName + out.FSType = in.FSType + out.Partition = in.Partition + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_GitRepoVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GitRepoVolumeSource) + out := out.(*GitRepoVolumeSource) + out.Repository = in.Repository + out.Revision = in.Revision + out.Directory = in.Directory + return nil + } +} + +func DeepCopy_api_GlusterfsVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*GlusterfsVolumeSource) + out := out.(*GlusterfsVolumeSource) + out.EndpointsName = in.EndpointsName + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_HTTPGetAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPGetAction) + out := out.(*HTTPGetAction) + out.Path = in.Path + out.Port = in.Port + out.Host = in.Host + out.Scheme = in.Scheme + if in.HTTPHeaders != nil { + in, out := &in.HTTPHeaders, &out.HTTPHeaders + *out = make([]HTTPHeader, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.HTTPHeaders = nil + } + return nil + } +} + +func DeepCopy_api_HTTPHeader(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPHeader) + out := out.(*HTTPHeader) + out.Name = in.Name + out.Value = in.Value + return nil + } +} + +func DeepCopy_api_Handler(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Handler) + out := out.(*Handler) + if in.Exec != nil { + in, out := &in.Exec, &out.Exec + *out = new(ExecAction) + if err := DeepCopy_api_ExecAction(*in, *out, c); err != nil { + return err + } + } else { + out.Exec = nil + } + if in.HTTPGet != nil { + in, out := &in.HTTPGet, &out.HTTPGet + *out = new(HTTPGetAction) + if err := DeepCopy_api_HTTPGetAction(*in, *out, c); err != nil { + return err + } + } else { + out.HTTPGet = nil + } + if in.TCPSocket != nil { + in, out := &in.TCPSocket, &out.TCPSocket + *out = new(TCPSocketAction) + **out = **in + } else { + out.TCPSocket = nil + } + return nil + } +} + +func DeepCopy_api_HostPathVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HostPathVolumeSource) + out := out.(*HostPathVolumeSource) + out.Path = in.Path + return nil + } +} + +func DeepCopy_api_ISCSIVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ISCSIVolumeSource) + out := out.(*ISCSIVolumeSource) + out.TargetPortal = in.TargetPortal + out.IQN = in.IQN + out.Lun = in.Lun + out.ISCSIInterface = in.ISCSIInterface + out.FSType = in.FSType + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_KeyToPath(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KeyToPath) + out := out.(*KeyToPath) + out.Key = in.Key + out.Path = in.Path + return nil + } +} + +func DeepCopy_api_Lifecycle(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Lifecycle) + out := out.(*Lifecycle) + if in.PostStart != nil { + in, out := &in.PostStart, &out.PostStart + *out = new(Handler) + if err := DeepCopy_api_Handler(*in, *out, c); err != nil { + return err + } + } else { + out.PostStart = nil + } + if in.PreStop != nil { + in, out := &in.PreStop, &out.PreStop + *out = new(Handler) + if err := DeepCopy_api_Handler(*in, *out, c); err != nil { + return err + } + } else { + out.PreStop = nil + } + return nil + } +} + +func DeepCopy_api_LimitRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRange) + out := out.(*LimitRange) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_LimitRangeSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_LimitRangeItem(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeItem) + out := out.(*LimitRangeItem) + out.Type = in.Type + if in.Max != nil { + in, out := &in.Max, &out.Max + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Max = nil + } + if in.Min != nil { + in, out := &in.Min, &out.Min + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Min = nil + } + if in.Default != nil { + in, out := &in.Default, &out.Default + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Default = nil + } + if in.DefaultRequest != nil { + in, out := &in.DefaultRequest, &out.DefaultRequest + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.DefaultRequest = nil + } + if in.MaxLimitRequestRatio != nil { + in, out := &in.MaxLimitRequestRatio, &out.MaxLimitRequestRatio + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.MaxLimitRequestRatio = nil + } + return nil + } +} + +func DeepCopy_api_LimitRangeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeList) + out := out.(*LimitRangeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]LimitRange, len(*in)) + for i := range *in { + if err := DeepCopy_api_LimitRange(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_LimitRangeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LimitRangeSpec) + out := out.(*LimitRangeSpec) + if in.Limits != nil { + in, out := &in.Limits, &out.Limits + *out = make([]LimitRangeItem, len(*in)) + for i := range *in { + if err := DeepCopy_api_LimitRangeItem(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Limits = nil + } + return nil + } +} + +func DeepCopy_api_List(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*List) + out := out.(*List) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]runtime.Object, len(*in)) + for i := range *in { + if newVal, err := c.DeepCopy(&(*in)[i]); err != nil { + return err + } else { + (*out)[i] = *newVal.(*runtime.Object) + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ListOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ListOptions) + out := out.(*ListOptions) + out.TypeMeta = in.TypeMeta + if in.LabelSelector == nil { + out.LabelSelector = nil + } else if newVal, err := c.DeepCopy(&in.LabelSelector); err != nil { + return err + } else { + out.LabelSelector = *newVal.(*labels.Selector) + } + if in.FieldSelector == nil { + out.FieldSelector = nil + } else if newVal, err := c.DeepCopy(&in.FieldSelector); err != nil { + return err + } else { + out.FieldSelector = *newVal.(*fields.Selector) + } + out.Watch = in.Watch + out.ResourceVersion = in.ResourceVersion + if in.TimeoutSeconds != nil { + in, out := &in.TimeoutSeconds, &out.TimeoutSeconds + *out = new(int64) + **out = **in + } else { + out.TimeoutSeconds = nil + } + return nil + } +} + +func DeepCopy_api_LoadBalancerIngress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LoadBalancerIngress) + out := out.(*LoadBalancerIngress) + out.IP = in.IP + out.Hostname = in.Hostname + return nil + } +} + +func DeepCopy_api_LoadBalancerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LoadBalancerStatus) + out := out.(*LoadBalancerStatus) + if in.Ingress != nil { + in, out := &in.Ingress, &out.Ingress + *out = make([]LoadBalancerIngress, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ingress = nil + } + return nil + } +} + +func DeepCopy_api_LocalObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LocalObjectReference) + out := out.(*LocalObjectReference) + out.Name = in.Name + return nil + } +} + +func DeepCopy_api_NFSVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NFSVolumeSource) + out := out.(*NFSVolumeSource) + out.Server = in.Server + out.Path = in.Path + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_Namespace(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Namespace) + out := out.(*Namespace) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_NamespaceSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_api_NamespaceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceList) + out := out.(*NamespaceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Namespace, len(*in)) + for i := range *in { + if err := DeepCopy_api_Namespace(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_NamespaceSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceSpec) + out := out.(*NamespaceSpec) + if in.Finalizers != nil { + in, out := &in.Finalizers, &out.Finalizers + *out = make([]FinalizerName, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Finalizers = nil + } + return nil + } +} + +func DeepCopy_api_NamespaceStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NamespaceStatus) + out := out.(*NamespaceStatus) + out.Phase = in.Phase + return nil + } +} + +func DeepCopy_api_Node(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Node) + out := out.(*Node) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + if err := DeepCopy_api_NodeStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_NodeAddress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeAddress) + out := out.(*NodeAddress) + out.Type = in.Type + out.Address = in.Address + return nil + } +} + +func DeepCopy_api_NodeAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeAffinity) + out := out.(*NodeAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = new(NodeSelector) + if err := DeepCopy_api_NodeSelector(*in, *out, c); err != nil { + return err + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]PreferredSchedulingTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_PreferredSchedulingTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_api_NodeCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeCondition) + out := out.(*NodeCondition) + out.Type = in.Type + out.Status = in.Status + out.LastHeartbeatTime = in.LastHeartbeatTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_api_NodeDaemonEndpoints(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeDaemonEndpoints) + out := out.(*NodeDaemonEndpoints) + out.KubeletEndpoint = in.KubeletEndpoint + return nil + } +} + +func DeepCopy_api_NodeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeList) + out := out.(*NodeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Node, len(*in)) + for i := range *in { + if err := DeepCopy_api_Node(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_NodeProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeProxyOptions) + out := out.(*NodeProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_api_NodeResources(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeResources) + out := out.(*NodeResources) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + return nil + } +} + +func DeepCopy_api_NodeSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelector) + out := out.(*NodeSelector) + if in.NodeSelectorTerms != nil { + in, out := &in.NodeSelectorTerms, &out.NodeSelectorTerms + *out = make([]NodeSelectorTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_NodeSelectorTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.NodeSelectorTerms = nil + } + return nil + } +} + +func DeepCopy_api_NodeSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelectorRequirement) + out := out.(*NodeSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} + +func DeepCopy_api_NodeSelectorTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSelectorTerm) + out := out.(*NodeSelectorTerm) + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]NodeSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_api_NodeSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_api_NodeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSpec) + out := out.(*NodeSpec) + out.PodCIDR = in.PodCIDR + out.ExternalID = in.ExternalID + out.ProviderID = in.ProviderID + out.Unschedulable = in.Unschedulable + return nil + } +} + +func DeepCopy_api_NodeStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeStatus) + out := out.(*NodeStatus) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + if in.Allocatable != nil { + in, out := &in.Allocatable, &out.Allocatable + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Allocatable = nil + } + out.Phase = in.Phase + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]NodeCondition, len(*in)) + for i := range *in { + if err := DeepCopy_api_NodeCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Addresses != nil { + in, out := &in.Addresses, &out.Addresses + *out = make([]NodeAddress, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Addresses = nil + } + out.DaemonEndpoints = in.DaemonEndpoints + out.NodeInfo = in.NodeInfo + if in.Images != nil { + in, out := &in.Images, &out.Images + *out = make([]ContainerImage, len(*in)) + for i := range *in { + if err := DeepCopy_api_ContainerImage(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Images = nil + } + if in.VolumesInUse != nil { + in, out := &in.VolumesInUse, &out.VolumesInUse + *out = make([]UniqueVolumeName, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumesInUse = nil + } + if in.VolumesAttached != nil { + in, out := &in.VolumesAttached, &out.VolumesAttached + *out = make([]AttachedVolume, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.VolumesAttached = nil + } + return nil + } +} + +func DeepCopy_api_NodeSystemInfo(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NodeSystemInfo) + out := out.(*NodeSystemInfo) + out.MachineID = in.MachineID + out.SystemUUID = in.SystemUUID + out.BootID = in.BootID + out.KernelVersion = in.KernelVersion + out.OSImage = in.OSImage + out.ContainerRuntimeVersion = in.ContainerRuntimeVersion + out.KubeletVersion = in.KubeletVersion + out.KubeProxyVersion = in.KubeProxyVersion + out.OperatingSystem = in.OperatingSystem + out.Architecture = in.Architecture + return nil + } +} + +func DeepCopy_api_ObjectFieldSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectFieldSelector) + out := out.(*ObjectFieldSelector) + out.APIVersion = in.APIVersion + out.FieldPath = in.FieldPath + return nil + } +} + +func DeepCopy_api_ObjectMeta(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectMeta) + out := out.(*ObjectMeta) + out.Name = in.Name + out.GenerateName = in.GenerateName + out.Namespace = in.Namespace + out.SelfLink = in.SelfLink + out.UID = in.UID + out.ResourceVersion = in.ResourceVersion + out.Generation = in.Generation + out.CreationTimestamp = in.CreationTimestamp.DeepCopy() + if in.DeletionTimestamp != nil { + in, out := &in.DeletionTimestamp, &out.DeletionTimestamp + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.DeletionTimestamp = nil + } + if in.DeletionGracePeriodSeconds != nil { + in, out := &in.DeletionGracePeriodSeconds, &out.DeletionGracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.DeletionGracePeriodSeconds = nil + } + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Labels = nil + } + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Annotations = nil + } + if in.OwnerReferences != nil { + in, out := &in.OwnerReferences, &out.OwnerReferences + *out = make([]OwnerReference, len(*in)) + for i := range *in { + if err := DeepCopy_api_OwnerReference(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.OwnerReferences = nil + } + if in.Finalizers != nil { + in, out := &in.Finalizers, &out.Finalizers + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Finalizers = nil + } + return nil + } +} + +func DeepCopy_api_ObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ObjectReference) + out := out.(*ObjectReference) + out.Kind = in.Kind + out.Namespace = in.Namespace + out.Name = in.Name + out.UID = in.UID + out.APIVersion = in.APIVersion + out.ResourceVersion = in.ResourceVersion + out.FieldPath = in.FieldPath + return nil + } +} + +func DeepCopy_api_OwnerReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*OwnerReference) + out := out.(*OwnerReference) + out.APIVersion = in.APIVersion + out.Kind = in.Kind + out.Name = in.Name + out.UID = in.UID + if in.Controller != nil { + in, out := &in.Controller, &out.Controller + *out = new(bool) + **out = **in + } else { + out.Controller = nil + } + return nil + } +} + +func DeepCopy_api_PersistentVolume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolume) + out := out.(*PersistentVolume) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PersistentVolumeSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_api_PersistentVolumeClaim(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaim) + out := out.(*PersistentVolumeClaim) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PersistentVolumeClaimSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_api_PersistentVolumeClaimStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_PersistentVolumeClaimList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimList) + out := out.(*PersistentVolumeClaimList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PersistentVolumeClaim, len(*in)) + for i := range *in { + if err := DeepCopy_api_PersistentVolumeClaim(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_PersistentVolumeClaimSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimSpec) + out := out.(*PersistentVolumeClaimSpec) + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := DeepCopy_api_ResourceRequirements(&in.Resources, &out.Resources, c); err != nil { + return err + } + out.VolumeName = in.VolumeName + return nil + } +} + +func DeepCopy_api_PersistentVolumeClaimStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimStatus) + out := out.(*PersistentVolumeClaimStatus) + out.Phase = in.Phase + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + return nil + } +} + +func DeepCopy_api_PersistentVolumeClaimVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeClaimVolumeSource) + out := out.(*PersistentVolumeClaimVolumeSource) + out.ClaimName = in.ClaimName + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_PersistentVolumeList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeList) + out := out.(*PersistentVolumeList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PersistentVolume, len(*in)) + for i := range *in { + if err := DeepCopy_api_PersistentVolume(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_PersistentVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeSource) + out := out.(*PersistentVolumeSource) + if in.GCEPersistentDisk != nil { + in, out := &in.GCEPersistentDisk, &out.GCEPersistentDisk + *out = new(GCEPersistentDiskVolumeSource) + **out = **in + } else { + out.GCEPersistentDisk = nil + } + if in.AWSElasticBlockStore != nil { + in, out := &in.AWSElasticBlockStore, &out.AWSElasticBlockStore + *out = new(AWSElasticBlockStoreVolumeSource) + **out = **in + } else { + out.AWSElasticBlockStore = nil + } + if in.HostPath != nil { + in, out := &in.HostPath, &out.HostPath + *out = new(HostPathVolumeSource) + **out = **in + } else { + out.HostPath = nil + } + if in.Glusterfs != nil { + in, out := &in.Glusterfs, &out.Glusterfs + *out = new(GlusterfsVolumeSource) + **out = **in + } else { + out.Glusterfs = nil + } + if in.NFS != nil { + in, out := &in.NFS, &out.NFS + *out = new(NFSVolumeSource) + **out = **in + } else { + out.NFS = nil + } + if in.RBD != nil { + in, out := &in.RBD, &out.RBD + *out = new(RBDVolumeSource) + if err := DeepCopy_api_RBDVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.RBD = nil + } + if in.ISCSI != nil { + in, out := &in.ISCSI, &out.ISCSI + *out = new(ISCSIVolumeSource) + **out = **in + } else { + out.ISCSI = nil + } + if in.FlexVolume != nil { + in, out := &in.FlexVolume, &out.FlexVolume + *out = new(FlexVolumeSource) + if err := DeepCopy_api_FlexVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + if in.Cinder != nil { + in, out := &in.Cinder, &out.Cinder + *out = new(CinderVolumeSource) + **out = **in + } else { + out.Cinder = nil + } + if in.CephFS != nil { + in, out := &in.CephFS, &out.CephFS + *out = new(CephFSVolumeSource) + if err := DeepCopy_api_CephFSVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.CephFS = nil + } + if in.FC != nil { + in, out := &in.FC, &out.FC + *out = new(FCVolumeSource) + if err := DeepCopy_api_FCVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FC = nil + } + if in.Flocker != nil { + in, out := &in.Flocker, &out.Flocker + *out = new(FlockerVolumeSource) + **out = **in + } else { + out.Flocker = nil + } + if in.AzureFile != nil { + in, out := &in.AzureFile, &out.AzureFile + *out = new(AzureFileVolumeSource) + **out = **in + } else { + out.AzureFile = nil + } + if in.VsphereVolume != nil { + in, out := &in.VsphereVolume, &out.VsphereVolume + *out = new(VsphereVirtualDiskVolumeSource) + **out = **in + } else { + out.VsphereVolume = nil + } + return nil + } +} + +func DeepCopy_api_PersistentVolumeSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeSpec) + out := out.(*PersistentVolumeSpec) + if in.Capacity != nil { + in, out := &in.Capacity, &out.Capacity + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Capacity = nil + } + if err := DeepCopy_api_PersistentVolumeSource(&in.PersistentVolumeSource, &out.PersistentVolumeSource, c); err != nil { + return err + } + if in.AccessModes != nil { + in, out := &in.AccessModes, &out.AccessModes + *out = make([]PersistentVolumeAccessMode, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AccessModes = nil + } + if in.ClaimRef != nil { + in, out := &in.ClaimRef, &out.ClaimRef + *out = new(ObjectReference) + **out = **in + } else { + out.ClaimRef = nil + } + out.PersistentVolumeReclaimPolicy = in.PersistentVolumeReclaimPolicy + return nil + } +} + +func DeepCopy_api_PersistentVolumeStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeStatus) + out := out.(*PersistentVolumeStatus) + out.Phase = in.Phase + out.Message = in.Message + out.Reason = in.Reason + return nil + } +} + +func DeepCopy_api_Pod(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Pod) + out := out.(*Pod) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PodSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_api_PodStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_PodAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAffinity) + out := out.(*PodAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = make([]PodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_PodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]WeightedPodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_WeightedPodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_api_PodAffinityTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAffinityTerm) + out := out.(*PodAffinityTerm) + if in.LabelSelector != nil { + in, out := &in.LabelSelector, &out.LabelSelector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.LabelSelector = nil + } + if in.Namespaces != nil { + in, out := &in.Namespaces, &out.Namespaces + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Namespaces = nil + } + out.TopologyKey = in.TopologyKey + return nil + } +} + +func DeepCopy_api_PodAntiAffinity(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAntiAffinity) + out := out.(*PodAntiAffinity) + if in.RequiredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.RequiredDuringSchedulingIgnoredDuringExecution, &out.RequiredDuringSchedulingIgnoredDuringExecution + *out = make([]PodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_PodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.RequiredDuringSchedulingIgnoredDuringExecution = nil + } + if in.PreferredDuringSchedulingIgnoredDuringExecution != nil { + in, out := &in.PreferredDuringSchedulingIgnoredDuringExecution, &out.PreferredDuringSchedulingIgnoredDuringExecution + *out = make([]WeightedPodAffinityTerm, len(*in)) + for i := range *in { + if err := DeepCopy_api_WeightedPodAffinityTerm(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.PreferredDuringSchedulingIgnoredDuringExecution = nil + } + return nil + } +} + +func DeepCopy_api_PodAttachOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodAttachOptions) + out := out.(*PodAttachOptions) + out.TypeMeta = in.TypeMeta + out.Stdin = in.Stdin + out.Stdout = in.Stdout + out.Stderr = in.Stderr + out.TTY = in.TTY + out.Container = in.Container + return nil + } +} + +func DeepCopy_api_PodCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodCondition) + out := out.(*PodCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_api_PodExecOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodExecOptions) + out := out.(*PodExecOptions) + out.TypeMeta = in.TypeMeta + out.Stdin = in.Stdin + out.Stdout = in.Stdout + out.Stderr = in.Stderr + out.TTY = in.TTY + out.Container = in.Container + if in.Command != nil { + in, out := &in.Command, &out.Command + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Command = nil + } + return nil + } +} + +func DeepCopy_api_PodList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodList) + out := out.(*PodList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Pod, len(*in)) + for i := range *in { + if err := DeepCopy_api_Pod(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_PodLogOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodLogOptions) + out := out.(*PodLogOptions) + out.TypeMeta = in.TypeMeta + out.Container = in.Container + out.Follow = in.Follow + out.Previous = in.Previous + if in.SinceSeconds != nil { + in, out := &in.SinceSeconds, &out.SinceSeconds + *out = new(int64) + **out = **in + } else { + out.SinceSeconds = nil + } + if in.SinceTime != nil { + in, out := &in.SinceTime, &out.SinceTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.SinceTime = nil + } + out.Timestamps = in.Timestamps + if in.TailLines != nil { + in, out := &in.TailLines, &out.TailLines + *out = new(int64) + **out = **in + } else { + out.TailLines = nil + } + if in.LimitBytes != nil { + in, out := &in.LimitBytes, &out.LimitBytes + *out = new(int64) + **out = **in + } else { + out.LimitBytes = nil + } + return nil + } +} + +func DeepCopy_api_PodProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodProxyOptions) + out := out.(*PodProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_api_PodSecurityContext(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityContext) + out := out.(*PodSecurityContext) + out.HostNetwork = in.HostNetwork + out.HostPID = in.HostPID + out.HostIPC = in.HostIPC + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + in, out := &in.RunAsUser, &out.RunAsUser + *out = new(int64) + **out = **in + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + in, out := &in.RunAsNonRoot, &out.RunAsNonRoot + *out = new(bool) + **out = **in + } else { + out.RunAsNonRoot = nil + } + if in.SupplementalGroups != nil { + in, out := &in.SupplementalGroups, &out.SupplementalGroups + *out = make([]int64, len(*in)) + copy(*out, *in) + } else { + out.SupplementalGroups = nil + } + if in.FSGroup != nil { + in, out := &in.FSGroup, &out.FSGroup + *out = new(int64) + **out = **in + } else { + out.FSGroup = nil + } + return nil + } +} + +func DeepCopy_api_PodSignature(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSignature) + out := out.(*PodSignature) + if in.PodController != nil { + in, out := &in.PodController, &out.PodController + *out = new(OwnerReference) + if err := DeepCopy_api_OwnerReference(*in, *out, c); err != nil { + return err + } + } else { + out.PodController = nil + } + return nil + } +} + +func DeepCopy_api_PodSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSpec) + out := out.(*PodSpec) + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]Volume, len(*in)) + for i := range *in { + if err := DeepCopy_api_Volume(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Volumes = nil + } + if in.InitContainers != nil { + in, out := &in.InitContainers, &out.InitContainers + *out = make([]Container, len(*in)) + for i := range *in { + if err := DeepCopy_api_Container(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.InitContainers = nil + } + if in.Containers != nil { + in, out := &in.Containers, &out.Containers + *out = make([]Container, len(*in)) + for i := range *in { + if err := DeepCopy_api_Container(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Containers = nil + } + out.RestartPolicy = in.RestartPolicy + if in.TerminationGracePeriodSeconds != nil { + in, out := &in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds + *out = new(int64) + **out = **in + } else { + out.TerminationGracePeriodSeconds = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + out.DNSPolicy = in.DNSPolicy + if in.NodeSelector != nil { + in, out := &in.NodeSelector, &out.NodeSelector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.NodeSelector = nil + } + out.ServiceAccountName = in.ServiceAccountName + out.NodeName = in.NodeName + if in.SecurityContext != nil { + in, out := &in.SecurityContext, &out.SecurityContext + *out = new(PodSecurityContext) + if err := DeepCopy_api_PodSecurityContext(*in, *out, c); err != nil { + return err + } + } else { + out.SecurityContext = nil + } + if in.ImagePullSecrets != nil { + in, out := &in.ImagePullSecrets, &out.ImagePullSecrets + *out = make([]LocalObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ImagePullSecrets = nil + } + out.Hostname = in.Hostname + out.Subdomain = in.Subdomain + return nil + } +} + +func DeepCopy_api_PodStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodStatus) + out := out.(*PodStatus) + out.Phase = in.Phase + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]PodCondition, len(*in)) + for i := range *in { + if err := DeepCopy_api_PodCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + out.Message = in.Message + out.Reason = in.Reason + out.HostIP = in.HostIP + out.PodIP = in.PodIP + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.InitContainerStatuses != nil { + in, out := &in.InitContainerStatuses, &out.InitContainerStatuses + *out = make([]ContainerStatus, len(*in)) + for i := range *in { + if err := DeepCopy_api_ContainerStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.InitContainerStatuses = nil + } + if in.ContainerStatuses != nil { + in, out := &in.ContainerStatuses, &out.ContainerStatuses + *out = make([]ContainerStatus, len(*in)) + for i := range *in { + if err := DeepCopy_api_ContainerStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.ContainerStatuses = nil + } + return nil + } +} + +func DeepCopy_api_PodStatusResult(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodStatusResult) + out := out.(*PodStatusResult) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PodStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_PodTemplate(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplate) + out := out.(*PodTemplate) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_PodTemplateList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplateList) + out := out.(*PodTemplateList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodTemplate, len(*in)) + for i := range *in { + if err := DeepCopy_api_PodTemplate(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_PodTemplateSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodTemplateSpec) + out := out.(*PodTemplateSpec) + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_PodSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_Preconditions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Preconditions) + out := out.(*Preconditions) + if in.UID != nil { + in, out := &in.UID, &out.UID + *out = new(types.UID) + **out = **in + } else { + out.UID = nil + } + return nil + } +} + +func DeepCopy_api_PreferAvoidPodsEntry(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PreferAvoidPodsEntry) + out := out.(*PreferAvoidPodsEntry) + if err := DeepCopy_api_PodSignature(&in.PodSignature, &out.PodSignature, c); err != nil { + return err + } + out.EvictionTime = in.EvictionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_api_PreferredSchedulingTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PreferredSchedulingTerm) + out := out.(*PreferredSchedulingTerm) + out.Weight = in.Weight + if err := DeepCopy_api_NodeSelectorTerm(&in.Preference, &out.Preference, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_Probe(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Probe) + out := out.(*Probe) + if err := DeepCopy_api_Handler(&in.Handler, &out.Handler, c); err != nil { + return err + } + out.InitialDelaySeconds = in.InitialDelaySeconds + out.TimeoutSeconds = in.TimeoutSeconds + out.PeriodSeconds = in.PeriodSeconds + out.SuccessThreshold = in.SuccessThreshold + out.FailureThreshold = in.FailureThreshold + return nil + } +} + +func DeepCopy_api_RBDVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RBDVolumeSource) + out := out.(*RBDVolumeSource) + if in.CephMonitors != nil { + in, out := &in.CephMonitors, &out.CephMonitors + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.CephMonitors = nil + } + out.RBDImage = in.RBDImage + out.FSType = in.FSType + out.RBDPool = in.RBDPool + out.RadosUser = in.RadosUser + out.Keyring = in.Keyring + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(LocalObjectReference) + **out = **in + } else { + out.SecretRef = nil + } + out.ReadOnly = in.ReadOnly + return nil + } +} + +func DeepCopy_api_RangeAllocation(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RangeAllocation) + out := out.(*RangeAllocation) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Range = in.Range + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_api_ReplicationController(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationController) + out := out.(*ReplicationController) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_ReplicationControllerSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_api_ReplicationControllerList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerList) + out := out.(*ReplicationControllerList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ReplicationController, len(*in)) + for i := range *in { + if err := DeepCopy_api_ReplicationController(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ReplicationControllerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerSpec) + out := out.(*ReplicationControllerSpec) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Selector = nil + } + if in.Template != nil { + in, out := &in.Template, &out.Template + *out = new(PodTemplateSpec) + if err := DeepCopy_api_PodTemplateSpec(*in, *out, c); err != nil { + return err + } + } else { + out.Template = nil + } + return nil + } +} + +func DeepCopy_api_ReplicationControllerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerStatus) + out := out.(*ReplicationControllerStatus) + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil + } +} + +func DeepCopy_api_ResourceFieldSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceFieldSelector) + out := out.(*ResourceFieldSelector) + out.ContainerName = in.ContainerName + out.Resource = in.Resource + out.Divisor = in.Divisor.DeepCopy() + return nil + } +} + +func DeepCopy_api_ResourceQuota(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuota) + out := out.(*ResourceQuota) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_ResourceQuotaSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_api_ResourceQuotaStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_ResourceQuotaList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaList) + out := out.(*ResourceQuotaList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ResourceQuota, len(*in)) + for i := range *in { + if err := DeepCopy_api_ResourceQuota(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ResourceQuotaSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaSpec) + out := out.(*ResourceQuotaSpec) + if in.Hard != nil { + in, out := &in.Hard, &out.Hard + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Hard = nil + } + if in.Scopes != nil { + in, out := &in.Scopes, &out.Scopes + *out = make([]ResourceQuotaScope, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Scopes = nil + } + return nil + } +} + +func DeepCopy_api_ResourceQuotaStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceQuotaStatus) + out := out.(*ResourceQuotaStatus) + if in.Hard != nil { + in, out := &in.Hard, &out.Hard + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Hard = nil + } + if in.Used != nil { + in, out := &in.Used, &out.Used + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Used = nil + } + return nil + } +} + +func DeepCopy_api_ResourceRequirements(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceRequirements) + out := out.(*ResourceRequirements) + if in.Limits != nil { + in, out := &in.Limits, &out.Limits + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Limits = nil + } + if in.Requests != nil { + in, out := &in.Requests, &out.Requests + *out = make(ResourceList) + for key, val := range *in { + (*out)[key] = val.DeepCopy() + } + } else { + out.Requests = nil + } + return nil + } +} + +func DeepCopy_api_SELinuxOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SELinuxOptions) + out := out.(*SELinuxOptions) + out.User = in.User + out.Role = in.Role + out.Type = in.Type + out.Level = in.Level + return nil + } +} + +func DeepCopy_api_Secret(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Secret) + out := out.(*Secret) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make(map[string][]byte) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]byte) + } + } + } else { + out.Data = nil + } + out.Type = in.Type + return nil + } +} + +func DeepCopy_api_SecretKeySelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretKeySelector) + out := out.(*SecretKeySelector) + out.LocalObjectReference = in.LocalObjectReference + out.Key = in.Key + return nil + } +} + +func DeepCopy_api_SecretList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretList) + out := out.(*SecretList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Secret, len(*in)) + for i := range *in { + if err := DeepCopy_api_Secret(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_SecretVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecretVolumeSource) + out := out.(*SecretVolumeSource) + out.SecretName = in.SecretName + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KeyToPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_SecurityContext(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SecurityContext) + out := out.(*SecurityContext) + if in.Capabilities != nil { + in, out := &in.Capabilities, &out.Capabilities + *out = new(Capabilities) + if err := DeepCopy_api_Capabilities(*in, *out, c); err != nil { + return err + } + } else { + out.Capabilities = nil + } + if in.Privileged != nil { + in, out := &in.Privileged, &out.Privileged + *out = new(bool) + **out = **in + } else { + out.Privileged = nil + } + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + if in.RunAsUser != nil { + in, out := &in.RunAsUser, &out.RunAsUser + *out = new(int64) + **out = **in + } else { + out.RunAsUser = nil + } + if in.RunAsNonRoot != nil { + in, out := &in.RunAsNonRoot, &out.RunAsNonRoot + *out = new(bool) + **out = **in + } else { + out.RunAsNonRoot = nil + } + if in.ReadOnlyRootFilesystem != nil { + in, out := &in.ReadOnlyRootFilesystem, &out.ReadOnlyRootFilesystem + *out = new(bool) + **out = **in + } else { + out.ReadOnlyRootFilesystem = nil + } + return nil + } +} + +func DeepCopy_api_SerializedReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SerializedReference) + out := out.(*SerializedReference) + out.TypeMeta = in.TypeMeta + out.Reference = in.Reference + return nil + } +} + +func DeepCopy_api_Service(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Service) + out := out.(*Service) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_api_ServiceSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_api_ServiceStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_ServiceAccount(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceAccount) + out := out.(*ServiceAccount) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Secrets != nil { + in, out := &in.Secrets, &out.Secrets + *out = make([]ObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Secrets = nil + } + if in.ImagePullSecrets != nil { + in, out := &in.ImagePullSecrets, &out.ImagePullSecrets + *out = make([]LocalObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.ImagePullSecrets = nil + } + return nil + } +} + +func DeepCopy_api_ServiceAccountList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceAccountList) + out := out.(*ServiceAccountList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ServiceAccount, len(*in)) + for i := range *in { + if err := DeepCopy_api_ServiceAccount(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ServiceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceList) + out := out.(*ServiceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Service, len(*in)) + for i := range *in { + if err := DeepCopy_api_Service(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_api_ServicePort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServicePort) + out := out.(*ServicePort) + out.Name = in.Name + out.Protocol = in.Protocol + out.Port = in.Port + out.TargetPort = in.TargetPort + out.NodePort = in.NodePort + return nil + } +} + +func DeepCopy_api_ServiceProxyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceProxyOptions) + out := out.(*ServiceProxyOptions) + out.TypeMeta = in.TypeMeta + out.Path = in.Path + return nil + } +} + +func DeepCopy_api_ServiceSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceSpec) + out := out.(*ServiceSpec) + out.Type = in.Type + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]ServicePort, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ports = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Selector = nil + } + out.ClusterIP = in.ClusterIP + if in.ExternalIPs != nil { + in, out := &in.ExternalIPs, &out.ExternalIPs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.ExternalIPs = nil + } + out.LoadBalancerIP = in.LoadBalancerIP + out.SessionAffinity = in.SessionAffinity + if in.LoadBalancerSourceRanges != nil { + in, out := &in.LoadBalancerSourceRanges, &out.LoadBalancerSourceRanges + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.LoadBalancerSourceRanges = nil + } + return nil + } +} + +func DeepCopy_api_ServiceStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ServiceStatus) + out := out.(*ServiceStatus) + if err := DeepCopy_api_LoadBalancerStatus(&in.LoadBalancer, &out.LoadBalancer, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_TCPSocketAction(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TCPSocketAction) + out := out.(*TCPSocketAction) + out.Port = in.Port + return nil + } +} + +func DeepCopy_api_Taint(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Taint) + out := out.(*Taint) + out.Key = in.Key + out.Value = in.Value + out.Effect = in.Effect + return nil + } +} + +func DeepCopy_api_Toleration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Toleration) + out := out.(*Toleration) + out.Key = in.Key + out.Operator = in.Operator + out.Value = in.Value + out.Effect = in.Effect + return nil + } +} + +func DeepCopy_api_Volume(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Volume) + out := out.(*Volume) + out.Name = in.Name + if err := DeepCopy_api_VolumeSource(&in.VolumeSource, &out.VolumeSource, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_api_VolumeMount(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VolumeMount) + out := out.(*VolumeMount) + out.Name = in.Name + out.ReadOnly = in.ReadOnly + out.MountPath = in.MountPath + out.SubPath = in.SubPath + return nil + } +} + +func DeepCopy_api_VolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VolumeSource) + out := out.(*VolumeSource) + if in.HostPath != nil { + in, out := &in.HostPath, &out.HostPath + *out = new(HostPathVolumeSource) + **out = **in + } else { + out.HostPath = nil + } + if in.EmptyDir != nil { + in, out := &in.EmptyDir, &out.EmptyDir + *out = new(EmptyDirVolumeSource) + **out = **in + } else { + out.EmptyDir = nil + } + if in.GCEPersistentDisk != nil { + in, out := &in.GCEPersistentDisk, &out.GCEPersistentDisk + *out = new(GCEPersistentDiskVolumeSource) + **out = **in + } else { + out.GCEPersistentDisk = nil + } + if in.AWSElasticBlockStore != nil { + in, out := &in.AWSElasticBlockStore, &out.AWSElasticBlockStore + *out = new(AWSElasticBlockStoreVolumeSource) + **out = **in + } else { + out.AWSElasticBlockStore = nil + } + if in.GitRepo != nil { + in, out := &in.GitRepo, &out.GitRepo + *out = new(GitRepoVolumeSource) + **out = **in + } else { + out.GitRepo = nil + } + if in.Secret != nil { + in, out := &in.Secret, &out.Secret + *out = new(SecretVolumeSource) + if err := DeepCopy_api_SecretVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.Secret = nil + } + if in.NFS != nil { + in, out := &in.NFS, &out.NFS + *out = new(NFSVolumeSource) + **out = **in + } else { + out.NFS = nil + } + if in.ISCSI != nil { + in, out := &in.ISCSI, &out.ISCSI + *out = new(ISCSIVolumeSource) + **out = **in + } else { + out.ISCSI = nil + } + if in.Glusterfs != nil { + in, out := &in.Glusterfs, &out.Glusterfs + *out = new(GlusterfsVolumeSource) + **out = **in + } else { + out.Glusterfs = nil + } + if in.PersistentVolumeClaim != nil { + in, out := &in.PersistentVolumeClaim, &out.PersistentVolumeClaim + *out = new(PersistentVolumeClaimVolumeSource) + **out = **in + } else { + out.PersistentVolumeClaim = nil + } + if in.RBD != nil { + in, out := &in.RBD, &out.RBD + *out = new(RBDVolumeSource) + if err := DeepCopy_api_RBDVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.RBD = nil + } + if in.FlexVolume != nil { + in, out := &in.FlexVolume, &out.FlexVolume + *out = new(FlexVolumeSource) + if err := DeepCopy_api_FlexVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FlexVolume = nil + } + if in.Cinder != nil { + in, out := &in.Cinder, &out.Cinder + *out = new(CinderVolumeSource) + **out = **in + } else { + out.Cinder = nil + } + if in.CephFS != nil { + in, out := &in.CephFS, &out.CephFS + *out = new(CephFSVolumeSource) + if err := DeepCopy_api_CephFSVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.CephFS = nil + } + if in.Flocker != nil { + in, out := &in.Flocker, &out.Flocker + *out = new(FlockerVolumeSource) + **out = **in + } else { + out.Flocker = nil + } + if in.DownwardAPI != nil { + in, out := &in.DownwardAPI, &out.DownwardAPI + *out = new(DownwardAPIVolumeSource) + if err := DeepCopy_api_DownwardAPIVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.DownwardAPI = nil + } + if in.FC != nil { + in, out := &in.FC, &out.FC + *out = new(FCVolumeSource) + if err := DeepCopy_api_FCVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.FC = nil + } + if in.AzureFile != nil { + in, out := &in.AzureFile, &out.AzureFile + *out = new(AzureFileVolumeSource) + **out = **in + } else { + out.AzureFile = nil + } + if in.ConfigMap != nil { + in, out := &in.ConfigMap, &out.ConfigMap + *out = new(ConfigMapVolumeSource) + if err := DeepCopy_api_ConfigMapVolumeSource(*in, *out, c); err != nil { + return err + } + } else { + out.ConfigMap = nil + } + if in.VsphereVolume != nil { + in, out := &in.VsphereVolume, &out.VsphereVolume + *out = new(VsphereVirtualDiskVolumeSource) + **out = **in + } else { + out.VsphereVolume = nil + } + return nil + } +} + +func DeepCopy_api_VsphereVirtualDiskVolumeSource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VsphereVirtualDiskVolumeSource) + out := out.(*VsphereVirtualDiskVolumeSource) + out.VolumePath = in.VolumePath + out.FSType = in.FSType + return nil + } +} + +func DeepCopy_api_WeightedPodAffinityTerm(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*WeightedPodAffinityTerm) + out := out.(*WeightedPodAffinityTerm) + out.Weight = in.Weight + if err := DeepCopy_api_PodAffinityTerm(&in.PodAffinityTerm, &out.PodAffinityTerm, c); err != nil { + return err + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apimachinery/doc.go b/vendor/k8s.io/kubernetes/pkg/apimachinery/doc.go index 7c5a261b415b..ede22b3d6851 100644 --- a/vendor/k8s.io/kubernetes/pkg/apimachinery/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apimachinery/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go b/vendor/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go index c418de3b05b4..63cb76e9aaf6 100644 --- a/vendor/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go +++ b/vendor/k8s.io/kubernetes/pkg/apimachinery/registered/registered.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -55,6 +55,10 @@ var ( ) func init() { + loadKubeAPIVersions() +} + +func loadKubeAPIVersions() { // Env var KUBE_API_VERSIONS is a comma separated list of API versions that // should be registered in the scheme. kubeAPIVersions := os.Getenv("KUBE_API_VERSIONS") @@ -70,6 +74,16 @@ func init() { } } +// Resets everything to clean room for the start of a test +func clearForTesting() { + registeredVersions = map[unversioned.GroupVersion]struct{}{} + thirdPartyGroupVersions = []unversioned.GroupVersion{} + enabledVersions = map[unversioned.GroupVersion]struct{}{} + groupMetaMap = map[string]*apimachinery.GroupMeta{} + envRequestedVersions = []unversioned.GroupVersion{} + loadKubeAPIVersions() +} + // RegisterVersions adds the given group versions to the list of registered group versions. func RegisterVersions(availableVersions []unversioned.GroupVersion) { for _, v := range availableVersions { @@ -207,12 +221,7 @@ func AddThirdPartyAPIGroupVersions(gvs ...unversioned.GroupVersion) []unversione } RegisterVersions(filteredGVs) EnableVersions(filteredGVs...) - next := make([]unversioned.GroupVersion, len(gvs)) - for ix := range filteredGVs { - next[ix] = filteredGVs[ix] - } - thirdPartyGroupVersions = next - + thirdPartyGroupVersions = append(thirdPartyGroupVersions, filteredGVs...) return skippedGVs } diff --git a/vendor/k8s.io/kubernetes/pkg/apimachinery/types.go b/vendor/k8s.io/kubernetes/pkg/apimachinery/types.go index 3e86921ce2f0..0e90cbbe3210 100644 --- a/vendor/k8s.io/kubernetes/pkg/apimachinery/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apimachinery/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/latest/latest.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/latest/latest.go index 2618fc4fc248..d3c00c416f3b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/latest/latest.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/latest/latest.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/register.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/register.go index c555d5aa979b..49a4c7561941 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/types.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/types.go index 024c7ee2417a..49d59ce50c7f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/conversion.go index c0fda4bd5555..7e28ad66cf08 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/register.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/register.go index d5338045a984..26fc59003d38 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/types.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/types.go index 58bb569f40bb..5462add3dc05 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/v0/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/register.go index 95fd6b3ef18b..f79265f9ffc8 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/types.go index 7ce61ac4ac5d..ecf988de051a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/abac/v1beta1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/deep_copy_generated.go deleted file mode 100644 index 5a2135c6a990..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/deep_copy_generated.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package apps - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_apps_PetSet, - DeepCopy_apps_PetSetList, - DeepCopy_apps_PetSetSpec, - DeepCopy_apps_PetSetStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_apps_PetSet(in PetSet, out *PetSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_apps_PetSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_apps_PetSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_apps_PetSetList(in PetSetList, out *PetSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PetSet, len(in)) - for i := range in { - if err := DeepCopy_apps_PetSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_apps_PetSetSpec(in PetSetSpec, out *PetSetSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := api.DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - if in.VolumeClaimTemplates != nil { - in, out := in.VolumeClaimTemplates, &out.VolumeClaimTemplates - *out = make([]api.PersistentVolumeClaim, len(in)) - for i := range in { - if err := api.DeepCopy_api_PersistentVolumeClaim(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumeClaimTemplates = nil - } - out.ServiceName = in.ServiceName - return nil -} - -func DeepCopy_apps_PetSetStatus(in PetSetStatus, out *PetSetStatus, c *conversion.Cloner) error { - if in.ObservedGeneration != nil { - in, out := in.ObservedGeneration, &out.ObservedGeneration - *out = new(int64) - **out = *in - } else { - out.ObservedGeneration = nil - } - out.Replicas = in.Replicas - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/doc.go new file mode 100644 index 000000000000..bca1ff4ef013 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package apps diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/install/install.go index b4d9011d37fd..346740e44af7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/register.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/register.go index dd5b9a900e1f..90acc123157a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/types.generated.go index a084509225af..be8a54ad51fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/types.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/types.go index 87019c4566ee..c3e28972fe4e 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ type PetSetSpec struct { // Selector is a label query over pods that should match the replica count. // If empty, defaulted to labels on the pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *unversioned.LabelSelector `json:"selector,omitempty"` // Template is the object that describes the pod that will be created if diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion.go index 48f1f2b4d327..b2fb1be72f6d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/deep_copy_generated.go deleted file mode 100644 index 6e51cacbc25c..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/deep_copy_generated.go +++ /dev/null @@ -1,124 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1alpha1_PetSet, - DeepCopy_v1alpha1_PetSetList, - DeepCopy_v1alpha1_PetSetSpec, - DeepCopy_v1alpha1_PetSetStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1alpha1_PetSet(in PetSet, out *PetSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1alpha1_PetSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1alpha1_PetSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_PetSetList(in PetSetList, out *PetSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PetSet, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_PetSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_PetSetSpec(in PetSetSpec, out *PetSetSpec, c *conversion.Cloner) error { - if in.Replicas != nil { - in, out := in.Replicas, &out.Replicas - *out = new(int32) - **out = *in - } else { - out.Replicas = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - if in.VolumeClaimTemplates != nil { - in, out := in.VolumeClaimTemplates, &out.VolumeClaimTemplates - *out = make([]v1.PersistentVolumeClaim, len(in)) - for i := range in { - if err := v1.DeepCopy_v1_PersistentVolumeClaim(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.VolumeClaimTemplates = nil - } - out.ServiceName = in.ServiceName - return nil -} - -func DeepCopy_v1alpha1_PetSetStatus(in PetSetStatus, out *PetSetStatus, c *conversion.Cloner) error { - if in.ObservedGeneration != nil { - in, out := in.ObservedGeneration, &out.ObservedGeneration - *out = new(int64) - **out = *in - } else { - out.ObservedGeneration = nil - } - out.Replicas = in.Replicas - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/defaults.go index e41028138afd..e578e8c947e0 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/doc.go index 65a03a2093dc..53d9fcabc418 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/apps + package v1alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.pb.go index 88f1bcd40735..b5fc937cb899 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -39,6 +39,9 @@ import math "math" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" import k8s_io_kubernetes_pkg_api_v1 "k8s.io/kubernetes/pkg/api/v1" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -46,21 +49,17 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *PetSet) Reset() { *m = PetSet{} } -func (m *PetSet) String() string { return proto.CompactTextString(m) } -func (*PetSet) ProtoMessage() {} +func (m *PetSet) Reset() { *m = PetSet{} } +func (*PetSet) ProtoMessage() {} -func (m *PetSetList) Reset() { *m = PetSetList{} } -func (m *PetSetList) String() string { return proto.CompactTextString(m) } -func (*PetSetList) ProtoMessage() {} +func (m *PetSetList) Reset() { *m = PetSetList{} } +func (*PetSetList) ProtoMessage() {} -func (m *PetSetSpec) Reset() { *m = PetSetSpec{} } -func (m *PetSetSpec) String() string { return proto.CompactTextString(m) } -func (*PetSetSpec) ProtoMessage() {} +func (m *PetSetSpec) Reset() { *m = PetSetSpec{} } +func (*PetSetSpec) ProtoMessage() {} -func (m *PetSetStatus) Reset() { *m = PetSetStatus{} } -func (m *PetSetStatus) String() string { return proto.CompactTextString(m) } -func (*PetSetStatus) ProtoMessage() {} +func (m *PetSetStatus) Reset() { *m = PetSetStatus{} } +func (*PetSetStatus) ProtoMessage() {} func init() { proto.RegisterType((*PetSet)(nil), "k8s.io.kubernetes.pkg.apis.apps.v1alpha1.PetSet") @@ -330,6 +329,62 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *PetSet) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PetSet{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PetSetSpec", "PetSetSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PetSetStatus", "PetSetStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PetSetList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PetSetList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PetSet", "PetSet", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PetSetSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PetSetSpec{`, + `Replicas:` + valueToStringGenerated(this.Replicas) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "k8s_io_kubernetes_pkg_api_unversioned.LabelSelector", 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `VolumeClaimTemplates:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.VolumeClaimTemplates), "PersistentVolumeClaim", "k8s_io_kubernetes_pkg_api_v1.PersistentVolumeClaim", 1), `&`, ``, 1) + `,`, + `ServiceName:` + fmt.Sprintf("%v", this.ServiceName) + `,`, + `}`, + }, "") + return s +} +func (this *PetSetStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PetSetStatus{`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *PetSet) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto index 3bf7e6936aef..2338042bfd0d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package k8s.io.kubernetes.pkg.apis.apps.v1alpha1; import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; +import "k8s.io/kubernetes/pkg/runtime/generated.proto"; import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; // Package-wide variables from generator "generated". @@ -65,7 +66,7 @@ message PetSetSpec { // Selector is a label query over pods that should match the replica count. // If empty, defaulted to labels on the pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional k8s.io.kubernetes.pkg.api.unversioned.LabelSelector selector = 2; // Template is the object that describes the pod that will be created if diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/register.go index 9ab37dfb0df8..9fd138c4a27a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.generated.go index a544c4e6ad08..d03639227a5f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.go index fb0aa48a1d1a..93a0c66e48d1 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ type PetSetSpec struct { // Selector is a label query over pods that should match the replica count. // If empty, defaulted to labels on the pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *unversioned.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` // Template is the object that describes the pod that will be created if diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types_swagger_doc_generated.go index 8ce682b4b583..5191f1224cd7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ func (PetSetList) SwaggerDoc() map[string]string { var map_PetSetSpec = map[string]string{ "": "A PetSetSpec is the specification of a PetSet.", "replicas": "Replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1.", - "selector": "Selector is a label query over pods that should match the replica count. If empty, defaulted to labels on the pod template. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", + "selector": "Selector is a label query over pods that should match the replica count. If empty, defaulted to labels on the pod template. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", "template": "Template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the PetSet will fulfill this Template, but have a unique identity from the rest of the PetSet.", "volumeClaimTemplates": "VolumeClaimTemplates is a list of claims that pets are allowed to reference. The PetSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pet. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name.", "serviceName": "ServiceName is the name of the service that governs this PetSet. This service must exist before the PetSet, and is responsible for the network identity of the set. Pets get DNS/hostnames that follow the pattern: pet-specific-string.serviceName.default.svc.cluster.local where \"pet-specific-string\" is managed by the PetSet controller.", diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.conversion.go similarity index 98% rename from vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.conversion.go index cfd6ce44b275..3cf4728102f1 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..f458bed915a6 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,135 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PetSet, InType: reflect.TypeOf(func() *PetSet { var x *PetSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PetSetList, InType: reflect.TypeOf(func() *PetSetList { var x *PetSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PetSetSpec, InType: reflect.TypeOf(func() *PetSetSpec { var x *PetSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PetSetStatus, InType: reflect.TypeOf(func() *PetSetStatus { var x *PetSetStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1alpha1_PetSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSet) + out := out.(*PetSet) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1alpha1_PetSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1alpha1_PetSetStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1alpha1_PetSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetList) + out := out.(*PetSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PetSet, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_PetSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_PetSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetSpec) + out := out.(*PetSetSpec) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } else { + out.Replicas = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + if in.VolumeClaimTemplates != nil { + in, out := &in.VolumeClaimTemplates, &out.VolumeClaimTemplates + *out = make([]v1.PersistentVolumeClaim, len(*in)) + for i := range *in { + if err := v1.DeepCopy_v1_PersistentVolumeClaim(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.VolumeClaimTemplates = nil + } + out.ServiceName = in.ServiceName + return nil + } +} + +func DeepCopy_v1alpha1_PetSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetStatus) + out := out.(*PetSetStatus) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } else { + out.ObservedGeneration = nil + } + out.Replicas = in.Replicas + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/validation/validation.go index acbdfedfe1eb..5700cf8911ab 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/apps/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/apps/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/apps/zz_generated.deepcopy.go new file mode 100644 index 000000000000..c93a58cb50ec --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/apps/zz_generated.deepcopy.go @@ -0,0 +1,128 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package apps + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_PetSet, InType: reflect.TypeOf(func() *PetSet { var x *PetSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_PetSetList, InType: reflect.TypeOf(func() *PetSetList { var x *PetSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_PetSetSpec, InType: reflect.TypeOf(func() *PetSetSpec { var x *PetSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_apps_PetSetStatus, InType: reflect.TypeOf(func() *PetSetStatus { var x *PetSetStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_apps_PetSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSet) + out := out.(*PetSet) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_apps_PetSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_apps_PetSetStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_apps_PetSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetList) + out := out.(*PetSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PetSet, len(*in)) + for i := range *in { + if err := DeepCopy_apps_PetSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_apps_PetSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetSpec) + out := out.(*PetSetSpec) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + if in.VolumeClaimTemplates != nil { + in, out := &in.VolumeClaimTemplates, &out.VolumeClaimTemplates + *out = make([]api.PersistentVolumeClaim, len(*in)) + for i := range *in { + if err := api.DeepCopy_api_PersistentVolumeClaim(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.VolumeClaimTemplates = nil + } + out.ServiceName = in.ServiceName + return nil + } +} + +func DeepCopy_apps_PetSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PetSetStatus) + out := out.(*PetSetStatus) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } else { + out.ObservedGeneration = nil + } + out.Replicas = in.Replicas + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/deep_copy_generated.go deleted file mode 100644 index 75ac7281ed24..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/deep_copy_generated.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package authentication - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_authenticationk8sio_TokenReview, - DeepCopy_authenticationk8sio_TokenReviewSpec, - DeepCopy_authenticationk8sio_TokenReviewStatus, - DeepCopy_authenticationk8sio_UserInfo, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_authenticationk8sio_TokenReview(in TokenReview, out *TokenReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_authenticationk8sio_TokenReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_authenticationk8sio_TokenReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_authenticationk8sio_TokenReviewSpec(in TokenReviewSpec, out *TokenReviewSpec, c *conversion.Cloner) error { - out.Token = in.Token - return nil -} - -func DeepCopy_authenticationk8sio_TokenReviewStatus(in TokenReviewStatus, out *TokenReviewStatus, c *conversion.Cloner) error { - out.Authenticated = in.Authenticated - if err := DeepCopy_authenticationk8sio_UserInfo(in.User, &out.User, c); err != nil { - return err - } - return nil -} - -func DeepCopy_authenticationk8sio_UserInfo(in UserInfo, out *UserInfo, c *conversion.Cloner) error { - out.Username = in.Username - out.UID = in.UID - if in.Groups != nil { - in, out := in.Groups, &out.Groups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Groups = nil - } - if in.Extra != nil { - in, out := in.Extra, &out.Extra - *out = make(map[string][]string) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]string) - } - } - } else { - out.Extra = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/doc.go new file mode 100644 index 000000000000..66c5ae720c05 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package authentication diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install/install.go index 29447d217781..e021ea88f6d1 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/register.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/register.go index 4dda3140fc25..57394fcbcc1f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.generated.go index b3b72d653b1b..b666e8c1824b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.go index 02ec0d2b2b7a..20eac2bf750c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion.go index 6a8545d13409..e360ee8a20c6 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/deep_copy_generated.go deleted file mode 100644 index e44dfc86bf39..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/deep_copy_generated.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1beta1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1beta1_TokenReview, - DeepCopy_v1beta1_TokenReviewSpec, - DeepCopy_v1beta1_TokenReviewStatus, - DeepCopy_v1beta1_UserInfo, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1beta1_TokenReview(in TokenReview, out *TokenReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_TokenReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_TokenReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_TokenReviewSpec(in TokenReviewSpec, out *TokenReviewSpec, c *conversion.Cloner) error { - out.Token = in.Token - return nil -} - -func DeepCopy_v1beta1_TokenReviewStatus(in TokenReviewStatus, out *TokenReviewStatus, c *conversion.Cloner) error { - out.Authenticated = in.Authenticated - if err := DeepCopy_v1beta1_UserInfo(in.User, &out.User, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_UserInfo(in UserInfo, out *UserInfo, c *conversion.Cloner) error { - out.Username = in.Username - out.UID = in.UID - if in.Groups != nil { - in, out := in.Groups, &out.Groups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Groups = nil - } - if in.Extra != nil { - in, out := in.Extra, &out.Extra - *out = make(map[string][]string) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]string) - } - } - } else { - out.Extra = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/defaults.go index 0f3732e36dcb..83794ff7b1b9 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/doc.go index cfdb87c53d84..25b76fd347f6 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/authentication.k8s.io + package v1beta1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/register.go index e183299c0b5f..511793653a33 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.generated.go index 62d287ff57a4..60eeab9eb2c4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.go index fc136877a9ef..ee3220672b06 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.conversion.go index 9972f82ed100..d60db5ed9d15 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..e82224661891 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,103 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1beta1 + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_TokenReview, InType: reflect.TypeOf(func() *TokenReview { var x *TokenReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_TokenReviewSpec, InType: reflect.TypeOf(func() *TokenReviewSpec { var x *TokenReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_TokenReviewStatus, InType: reflect.TypeOf(func() *TokenReviewStatus { var x *TokenReviewStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_UserInfo, InType: reflect.TypeOf(func() *UserInfo { var x *UserInfo; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1beta1_TokenReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReview) + out := out.(*TokenReview) + out.TypeMeta = in.TypeMeta + out.Spec = in.Spec + if err := DeepCopy_v1beta1_TokenReviewStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_TokenReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReviewSpec) + out := out.(*TokenReviewSpec) + out.Token = in.Token + return nil + } +} + +func DeepCopy_v1beta1_TokenReviewStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReviewStatus) + out := out.(*TokenReviewStatus) + out.Authenticated = in.Authenticated + if err := DeepCopy_v1beta1_UserInfo(&in.User, &out.User, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_UserInfo(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*UserInfo) + out := out.(*UserInfo) + out.Username = in.Username + out.UID = in.UID + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + if in.Extra != nil { + in, out := &in.Extra, &out.Extra + *out = make(map[string][]string) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]string) + } + } + } else { + out.Extra = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/zz_generated.deepcopy.go new file mode 100644 index 000000000000..232756c0b3ba --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/zz_generated.deepcopy.go @@ -0,0 +1,103 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package authentication + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authenticationk8sio_TokenReview, InType: reflect.TypeOf(func() *TokenReview { var x *TokenReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authenticationk8sio_TokenReviewSpec, InType: reflect.TypeOf(func() *TokenReviewSpec { var x *TokenReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authenticationk8sio_TokenReviewStatus, InType: reflect.TypeOf(func() *TokenReviewStatus { var x *TokenReviewStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authenticationk8sio_UserInfo, InType: reflect.TypeOf(func() *UserInfo { var x *UserInfo; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_authenticationk8sio_TokenReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReview) + out := out.(*TokenReview) + out.TypeMeta = in.TypeMeta + out.Spec = in.Spec + if err := DeepCopy_authenticationk8sio_TokenReviewStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_authenticationk8sio_TokenReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReviewSpec) + out := out.(*TokenReviewSpec) + out.Token = in.Token + return nil + } +} + +func DeepCopy_authenticationk8sio_TokenReviewStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TokenReviewStatus) + out := out.(*TokenReviewStatus) + out.Authenticated = in.Authenticated + if err := DeepCopy_authenticationk8sio_UserInfo(&in.User, &out.User, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_authenticationk8sio_UserInfo(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*UserInfo) + out := out.(*UserInfo) + out.Username = in.Username + out.UID = in.UID + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + if in.Extra != nil { + in, out := &in.Extra, &out.Extra + *out = make(map[string][]string) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]string) + } + } + } else { + out.Extra = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/deep_copy_generated.go deleted file mode 100644 index bc40fb33ea3d..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/deep_copy_generated.go +++ /dev/null @@ -1,170 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package authorization - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_authorization_LocalSubjectAccessReview, - DeepCopy_authorization_NonResourceAttributes, - DeepCopy_authorization_ResourceAttributes, - DeepCopy_authorization_SelfSubjectAccessReview, - DeepCopy_authorization_SelfSubjectAccessReviewSpec, - DeepCopy_authorization_SubjectAccessReview, - DeepCopy_authorization_SubjectAccessReviewSpec, - DeepCopy_authorization_SubjectAccessReviewStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_authorization_LocalSubjectAccessReview(in LocalSubjectAccessReview, out *LocalSubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_authorization_SubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_authorization_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_authorization_NonResourceAttributes(in NonResourceAttributes, out *NonResourceAttributes, c *conversion.Cloner) error { - out.Path = in.Path - out.Verb = in.Verb - return nil -} - -func DeepCopy_authorization_ResourceAttributes(in ResourceAttributes, out *ResourceAttributes, c *conversion.Cloner) error { - out.Namespace = in.Namespace - out.Verb = in.Verb - out.Group = in.Group - out.Version = in.Version - out.Resource = in.Resource - out.Subresource = in.Subresource - out.Name = in.Name - return nil -} - -func DeepCopy_authorization_SelfSubjectAccessReview(in SelfSubjectAccessReview, out *SelfSubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_authorization_SelfSubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_authorization_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_authorization_SelfSubjectAccessReviewSpec(in SelfSubjectAccessReviewSpec, out *SelfSubjectAccessReviewSpec, c *conversion.Cloner) error { - if in.ResourceAttributes != nil { - in, out := in.ResourceAttributes, &out.ResourceAttributes - *out = new(ResourceAttributes) - if err := DeepCopy_authorization_ResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceAttributes = nil - } - if in.NonResourceAttributes != nil { - in, out := in.NonResourceAttributes, &out.NonResourceAttributes - *out = new(NonResourceAttributes) - if err := DeepCopy_authorization_NonResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.NonResourceAttributes = nil - } - return nil -} - -func DeepCopy_authorization_SubjectAccessReview(in SubjectAccessReview, out *SubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_authorization_SubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_authorization_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_authorization_SubjectAccessReviewSpec(in SubjectAccessReviewSpec, out *SubjectAccessReviewSpec, c *conversion.Cloner) error { - if in.ResourceAttributes != nil { - in, out := in.ResourceAttributes, &out.ResourceAttributes - *out = new(ResourceAttributes) - if err := DeepCopy_authorization_ResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceAttributes = nil - } - if in.NonResourceAttributes != nil { - in, out := in.NonResourceAttributes, &out.NonResourceAttributes - *out = new(NonResourceAttributes) - if err := DeepCopy_authorization_NonResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.NonResourceAttributes = nil - } - out.User = in.User - if in.Groups != nil { - in, out := in.Groups, &out.Groups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Groups = nil - } - if in.Extra != nil { - in, out := in.Extra, &out.Extra - *out = make(map[string][]string) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]string) - } - } - } else { - out.Extra = nil - } - return nil -} - -func DeepCopy_authorization_SubjectAccessReviewStatus(in SubjectAccessReviewStatus, out *SubjectAccessReviewStatus, c *conversion.Cloner) error { - out.Allowed = in.Allowed - out.Reason = in.Reason - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/doc.go new file mode 100644 index 000000000000..9660e5eacf90 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package authorization diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/install/install.go index bf8814dd5e92..789981559877 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/register.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/register.go index fdb6c4f4bdee..b1cfa491bc92 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.generated.go index 1c071376cac4..a0811c8a7102 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.go index 8cfdfbe9775f..afa2c4273c7a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion.go index 0b45ed5fbaba..cd03e61b0795 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/deep_copy_generated.go deleted file mode 100644 index 94a35650cb45..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/deep_copy_generated.go +++ /dev/null @@ -1,170 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1beta1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1beta1_LocalSubjectAccessReview, - DeepCopy_v1beta1_NonResourceAttributes, - DeepCopy_v1beta1_ResourceAttributes, - DeepCopy_v1beta1_SelfSubjectAccessReview, - DeepCopy_v1beta1_SelfSubjectAccessReviewSpec, - DeepCopy_v1beta1_SubjectAccessReview, - DeepCopy_v1beta1_SubjectAccessReviewSpec, - DeepCopy_v1beta1_SubjectAccessReviewStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1beta1_LocalSubjectAccessReview(in LocalSubjectAccessReview, out *LocalSubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_NonResourceAttributes(in NonResourceAttributes, out *NonResourceAttributes, c *conversion.Cloner) error { - out.Path = in.Path - out.Verb = in.Verb - return nil -} - -func DeepCopy_v1beta1_ResourceAttributes(in ResourceAttributes, out *ResourceAttributes, c *conversion.Cloner) error { - out.Namespace = in.Namespace - out.Verb = in.Verb - out.Group = in.Group - out.Version = in.Version - out.Resource = in.Resource - out.Subresource = in.Subresource - out.Name = in.Name - return nil -} - -func DeepCopy_v1beta1_SelfSubjectAccessReview(in SelfSubjectAccessReview, out *SelfSubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SelfSubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_SelfSubjectAccessReviewSpec(in SelfSubjectAccessReviewSpec, out *SelfSubjectAccessReviewSpec, c *conversion.Cloner) error { - if in.ResourceAttributes != nil { - in, out := in.ResourceAttributes, &out.ResourceAttributes - *out = new(ResourceAttributes) - if err := DeepCopy_v1beta1_ResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceAttributes = nil - } - if in.NonResourceAttributes != nil { - in, out := in.NonResourceAttributes, &out.NonResourceAttributes - *out = new(NonResourceAttributes) - if err := DeepCopy_v1beta1_NonResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.NonResourceAttributes = nil - } - return nil -} - -func DeepCopy_v1beta1_SubjectAccessReview(in SubjectAccessReview, out *SubjectAccessReview, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SubjectAccessReviewSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SubjectAccessReviewStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_SubjectAccessReviewSpec(in SubjectAccessReviewSpec, out *SubjectAccessReviewSpec, c *conversion.Cloner) error { - if in.ResourceAttributes != nil { - in, out := in.ResourceAttributes, &out.ResourceAttributes - *out = new(ResourceAttributes) - if err := DeepCopy_v1beta1_ResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.ResourceAttributes = nil - } - if in.NonResourceAttributes != nil { - in, out := in.NonResourceAttributes, &out.NonResourceAttributes - *out = new(NonResourceAttributes) - if err := DeepCopy_v1beta1_NonResourceAttributes(*in, *out, c); err != nil { - return err - } - } else { - out.NonResourceAttributes = nil - } - out.User = in.User - if in.Groups != nil { - in, out := in.Groups, &out.Groups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Groups = nil - } - if in.Extra != nil { - in, out := in.Extra, &out.Extra - *out = make(map[string][]string) - for key, val := range in { - if newVal, err := c.DeepCopy(val); err != nil { - return err - } else { - (*out)[key] = newVal.([]string) - } - } - } else { - out.Extra = nil - } - return nil -} - -func DeepCopy_v1beta1_SubjectAccessReviewStatus(in SubjectAccessReviewStatus, out *SubjectAccessReviewStatus, c *conversion.Cloner) error { - out.Allowed = in.Allowed - out.Reason = in.Reason - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/defaults.go index 340f80755a2f..f9dda995e3cf 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/doc.go index cfdb87c53d84..a6f2c27b10e7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/authorization + package v1beta1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/register.go index d9e33ed5a22d..fe99bee3fa1b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.generated.go index 3b5e4fbe9322..0bd74a1bb409 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.go index 27078e9fc0e6..70c1282a7552 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go index d4c337db797e..dc934768d86f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.conversion.go index a475c0fd0a73..18d11380bfa4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..af3dcdb8d833 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,182 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1beta1 + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_LocalSubjectAccessReview, InType: reflect.TypeOf(func() *LocalSubjectAccessReview { var x *LocalSubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NonResourceAttributes, InType: reflect.TypeOf(func() *NonResourceAttributes { var x *NonResourceAttributes; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ResourceAttributes, InType: reflect.TypeOf(func() *ResourceAttributes { var x *ResourceAttributes; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SelfSubjectAccessReview, InType: reflect.TypeOf(func() *SelfSubjectAccessReview { var x *SelfSubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SelfSubjectAccessReviewSpec, InType: reflect.TypeOf(func() *SelfSubjectAccessReviewSpec { var x *SelfSubjectAccessReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SubjectAccessReview, InType: reflect.TypeOf(func() *SubjectAccessReview { var x *SubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SubjectAccessReviewSpec, InType: reflect.TypeOf(func() *SubjectAccessReviewSpec { var x *SubjectAccessReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SubjectAccessReviewStatus, InType: reflect.TypeOf(func() *SubjectAccessReviewStatus { var x *SubjectAccessReviewStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1beta1_LocalSubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LocalSubjectAccessReview) + out := out.(*LocalSubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1beta1_SubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_NonResourceAttributes(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NonResourceAttributes) + out := out.(*NonResourceAttributes) + out.Path = in.Path + out.Verb = in.Verb + return nil + } +} + +func DeepCopy_v1beta1_ResourceAttributes(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceAttributes) + out := out.(*ResourceAttributes) + out.Namespace = in.Namespace + out.Verb = in.Verb + out.Group = in.Group + out.Version = in.Version + out.Resource = in.Resource + out.Subresource = in.Subresource + out.Name = in.Name + return nil + } +} + +func DeepCopy_v1beta1_SelfSubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SelfSubjectAccessReview) + out := out.(*SelfSubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1beta1_SelfSubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_SelfSubjectAccessReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SelfSubjectAccessReviewSpec) + out := out.(*SelfSubjectAccessReviewSpec) + if in.ResourceAttributes != nil { + in, out := &in.ResourceAttributes, &out.ResourceAttributes + *out = new(ResourceAttributes) + **out = **in + } else { + out.ResourceAttributes = nil + } + if in.NonResourceAttributes != nil { + in, out := &in.NonResourceAttributes, &out.NonResourceAttributes + *out = new(NonResourceAttributes) + **out = **in + } else { + out.NonResourceAttributes = nil + } + return nil + } +} + +func DeepCopy_v1beta1_SubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReview) + out := out.(*SubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_v1beta1_SubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_SubjectAccessReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReviewSpec) + out := out.(*SubjectAccessReviewSpec) + if in.ResourceAttributes != nil { + in, out := &in.ResourceAttributes, &out.ResourceAttributes + *out = new(ResourceAttributes) + **out = **in + } else { + out.ResourceAttributes = nil + } + if in.NonResourceAttributes != nil { + in, out := &in.NonResourceAttributes, &out.NonResourceAttributes + *out = new(NonResourceAttributes) + **out = **in + } else { + out.NonResourceAttributes = nil + } + out.User = in.User + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + if in.Extra != nil { + in, out := &in.Extra, &out.Extra + *out = make(map[string][]string) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]string) + } + } + } else { + out.Extra = nil + } + return nil + } +} + +func DeepCopy_v1beta1_SubjectAccessReviewStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReviewStatus) + out := out.(*SubjectAccessReviewStatus) + out.Allowed = in.Allowed + out.Reason = in.Reason + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/authorization/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/authorization/zz_generated.deepcopy.go new file mode 100644 index 000000000000..b66c33a4e2b2 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/authorization/zz_generated.deepcopy.go @@ -0,0 +1,182 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package authorization + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_LocalSubjectAccessReview, InType: reflect.TypeOf(func() *LocalSubjectAccessReview { var x *LocalSubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_NonResourceAttributes, InType: reflect.TypeOf(func() *NonResourceAttributes { var x *NonResourceAttributes; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_ResourceAttributes, InType: reflect.TypeOf(func() *ResourceAttributes { var x *ResourceAttributes; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_SelfSubjectAccessReview, InType: reflect.TypeOf(func() *SelfSubjectAccessReview { var x *SelfSubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_SelfSubjectAccessReviewSpec, InType: reflect.TypeOf(func() *SelfSubjectAccessReviewSpec { var x *SelfSubjectAccessReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_SubjectAccessReview, InType: reflect.TypeOf(func() *SubjectAccessReview { var x *SubjectAccessReview; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_SubjectAccessReviewSpec, InType: reflect.TypeOf(func() *SubjectAccessReviewSpec { var x *SubjectAccessReviewSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_authorization_SubjectAccessReviewStatus, InType: reflect.TypeOf(func() *SubjectAccessReviewStatus { var x *SubjectAccessReviewStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_authorization_LocalSubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LocalSubjectAccessReview) + out := out.(*LocalSubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_authorization_SubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_authorization_NonResourceAttributes(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NonResourceAttributes) + out := out.(*NonResourceAttributes) + out.Path = in.Path + out.Verb = in.Verb + return nil + } +} + +func DeepCopy_authorization_ResourceAttributes(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ResourceAttributes) + out := out.(*ResourceAttributes) + out.Namespace = in.Namespace + out.Verb = in.Verb + out.Group = in.Group + out.Version = in.Version + out.Resource = in.Resource + out.Subresource = in.Subresource + out.Name = in.Name + return nil + } +} + +func DeepCopy_authorization_SelfSubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SelfSubjectAccessReview) + out := out.(*SelfSubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_authorization_SelfSubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_authorization_SelfSubjectAccessReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SelfSubjectAccessReviewSpec) + out := out.(*SelfSubjectAccessReviewSpec) + if in.ResourceAttributes != nil { + in, out := &in.ResourceAttributes, &out.ResourceAttributes + *out = new(ResourceAttributes) + **out = **in + } else { + out.ResourceAttributes = nil + } + if in.NonResourceAttributes != nil { + in, out := &in.NonResourceAttributes, &out.NonResourceAttributes + *out = new(NonResourceAttributes) + **out = **in + } else { + out.NonResourceAttributes = nil + } + return nil + } +} + +func DeepCopy_authorization_SubjectAccessReview(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReview) + out := out.(*SubjectAccessReview) + out.TypeMeta = in.TypeMeta + if err := DeepCopy_authorization_SubjectAccessReviewSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_authorization_SubjectAccessReviewSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReviewSpec) + out := out.(*SubjectAccessReviewSpec) + if in.ResourceAttributes != nil { + in, out := &in.ResourceAttributes, &out.ResourceAttributes + *out = new(ResourceAttributes) + **out = **in + } else { + out.ResourceAttributes = nil + } + if in.NonResourceAttributes != nil { + in, out := &in.NonResourceAttributes, &out.NonResourceAttributes + *out = new(NonResourceAttributes) + **out = **in + } else { + out.NonResourceAttributes = nil + } + out.User = in.User + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + if in.Extra != nil { + in, out := &in.Extra, &out.Extra + *out = make(map[string][]string) + for key, val := range *in { + if newVal, err := c.DeepCopy(&val); err != nil { + return err + } else { + (*out)[key] = *newVal.(*[]string) + } + } + } else { + out.Extra = nil + } + return nil + } +} + +func DeepCopy_authorization_SubjectAccessReviewStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubjectAccessReviewStatus) + out := out.(*SubjectAccessReviewStatus) + out.Allowed = in.Allowed + out.Reason = in.Reason + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/deep_copy_generated.go deleted file mode 100644 index d78bad7cbc39..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/deep_copy_generated.go +++ /dev/null @@ -1,165 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package autoscaling - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_autoscaling_CrossVersionObjectReference, - DeepCopy_autoscaling_HorizontalPodAutoscaler, - DeepCopy_autoscaling_HorizontalPodAutoscalerList, - DeepCopy_autoscaling_HorizontalPodAutoscalerSpec, - DeepCopy_autoscaling_HorizontalPodAutoscalerStatus, - DeepCopy_autoscaling_Scale, - DeepCopy_autoscaling_ScaleSpec, - DeepCopy_autoscaling_ScaleStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_autoscaling_CrossVersionObjectReference(in CrossVersionObjectReference, out *CrossVersionObjectReference, c *conversion.Cloner) error { - out.Kind = in.Kind - out.Name = in.Name - out.APIVersion = in.APIVersion - return nil -} - -func DeepCopy_autoscaling_HorizontalPodAutoscaler(in HorizontalPodAutoscaler, out *HorizontalPodAutoscaler, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_autoscaling_HorizontalPodAutoscalerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_autoscaling_HorizontalPodAutoscalerStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_autoscaling_HorizontalPodAutoscalerList(in HorizontalPodAutoscalerList, out *HorizontalPodAutoscalerList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]HorizontalPodAutoscaler, len(in)) - for i := range in { - if err := DeepCopy_autoscaling_HorizontalPodAutoscaler(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_autoscaling_HorizontalPodAutoscalerSpec(in HorizontalPodAutoscalerSpec, out *HorizontalPodAutoscalerSpec, c *conversion.Cloner) error { - if err := DeepCopy_autoscaling_CrossVersionObjectReference(in.ScaleTargetRef, &out.ScaleTargetRef, c); err != nil { - return err - } - if in.MinReplicas != nil { - in, out := in.MinReplicas, &out.MinReplicas - *out = new(int32) - **out = *in - } else { - out.MinReplicas = nil - } - out.MaxReplicas = in.MaxReplicas - if in.TargetCPUUtilizationPercentage != nil { - in, out := in.TargetCPUUtilizationPercentage, &out.TargetCPUUtilizationPercentage - *out = new(int32) - **out = *in - } else { - out.TargetCPUUtilizationPercentage = nil - } - return nil -} - -func DeepCopy_autoscaling_HorizontalPodAutoscalerStatus(in HorizontalPodAutoscalerStatus, out *HorizontalPodAutoscalerStatus, c *conversion.Cloner) error { - if in.ObservedGeneration != nil { - in, out := in.ObservedGeneration, &out.ObservedGeneration - *out = new(int64) - **out = *in - } else { - out.ObservedGeneration = nil - } - if in.LastScaleTime != nil { - in, out := in.LastScaleTime, &out.LastScaleTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.LastScaleTime = nil - } - out.CurrentReplicas = in.CurrentReplicas - out.DesiredReplicas = in.DesiredReplicas - if in.CurrentCPUUtilizationPercentage != nil { - in, out := in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage - *out = new(int32) - **out = *in - } else { - out.CurrentCPUUtilizationPercentage = nil - } - return nil -} - -func DeepCopy_autoscaling_Scale(in Scale, out *Scale, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_autoscaling_ScaleSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_autoscaling_ScaleStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_autoscaling_ScaleSpec(in ScaleSpec, out *ScaleSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - return nil -} - -func DeepCopy_autoscaling_ScaleStatus(in ScaleStatus, out *ScaleStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.Selector = in.Selector - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/doc.go new file mode 100644 index 000000000000..2c770186ba76 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package autoscaling diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/install/install.go index 6e226a06644e..be236ff0e439 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/register.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/register.go index 6a4fb747be8e..ee0d3c75bd88 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go index fdd05919003c..ded7227842bd 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.go index caafcde308b4..6accc9fd4b50 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,13 +24,13 @@ import ( // Scale represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. api.ObjectMeta `json:"metadata,omitempty"` - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty"` - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty"` } @@ -48,15 +48,15 @@ type ScaleStatus struct { // label query over pods that should match the replicas count. This is same // as the label selector but in the string format to avoid introspection // by clients. The string will be in the same format as the query-param syntax. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector string `json:"selector,omitempty"` } // CrossVersionObjectReference contains enough information to let you identify the referred resource. type CrossVersionObjectReference struct { - // Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds" Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` - // Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // API version of the referent APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,3,opt,name=apiVersion"` @@ -103,7 +103,7 @@ type HorizontalPodAutoscaler struct { unversioned.TypeMeta `json:",inline"` api.ObjectMeta `json:"metadata,omitempty"` - // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty"` // current information about the autoscaler. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go deleted file mode 100644 index 6932ba638106..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/deep_copy_generated.go +++ /dev/null @@ -1,166 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - api_v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1_CrossVersionObjectReference, - DeepCopy_v1_HorizontalPodAutoscaler, - DeepCopy_v1_HorizontalPodAutoscalerList, - DeepCopy_v1_HorizontalPodAutoscalerSpec, - DeepCopy_v1_HorizontalPodAutoscalerStatus, - DeepCopy_v1_Scale, - DeepCopy_v1_ScaleSpec, - DeepCopy_v1_ScaleStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1_CrossVersionObjectReference(in CrossVersionObjectReference, out *CrossVersionObjectReference, c *conversion.Cloner) error { - out.Kind = in.Kind - out.Name = in.Name - out.APIVersion = in.APIVersion - return nil -} - -func DeepCopy_v1_HorizontalPodAutoscaler(in HorizontalPodAutoscaler, out *HorizontalPodAutoscaler, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api_v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_HorizontalPodAutoscalerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_HorizontalPodAutoscalerStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_HorizontalPodAutoscalerList(in HorizontalPodAutoscalerList, out *HorizontalPodAutoscalerList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]HorizontalPodAutoscaler, len(in)) - for i := range in { - if err := DeepCopy_v1_HorizontalPodAutoscaler(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_HorizontalPodAutoscalerSpec(in HorizontalPodAutoscalerSpec, out *HorizontalPodAutoscalerSpec, c *conversion.Cloner) error { - if err := DeepCopy_v1_CrossVersionObjectReference(in.ScaleTargetRef, &out.ScaleTargetRef, c); err != nil { - return err - } - if in.MinReplicas != nil { - in, out := in.MinReplicas, &out.MinReplicas - *out = new(int32) - **out = *in - } else { - out.MinReplicas = nil - } - out.MaxReplicas = in.MaxReplicas - if in.TargetCPUUtilizationPercentage != nil { - in, out := in.TargetCPUUtilizationPercentage, &out.TargetCPUUtilizationPercentage - *out = new(int32) - **out = *in - } else { - out.TargetCPUUtilizationPercentage = nil - } - return nil -} - -func DeepCopy_v1_HorizontalPodAutoscalerStatus(in HorizontalPodAutoscalerStatus, out *HorizontalPodAutoscalerStatus, c *conversion.Cloner) error { - if in.ObservedGeneration != nil { - in, out := in.ObservedGeneration, &out.ObservedGeneration - *out = new(int64) - **out = *in - } else { - out.ObservedGeneration = nil - } - if in.LastScaleTime != nil { - in, out := in.LastScaleTime, &out.LastScaleTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.LastScaleTime = nil - } - out.CurrentReplicas = in.CurrentReplicas - out.DesiredReplicas = in.DesiredReplicas - if in.CurrentCPUUtilizationPercentage != nil { - in, out := in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage - *out = new(int32) - **out = *in - } else { - out.CurrentCPUUtilizationPercentage = nil - } - return nil -} - -func DeepCopy_v1_Scale(in Scale, out *Scale, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api_v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_ScaleSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_ScaleStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_ScaleSpec(in ScaleSpec, out *ScaleSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - return nil -} - -func DeepCopy_v1_ScaleStatus(in ScaleStatus, out *ScaleStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.Selector = in.Selector - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/defaults.go index 3fb24c46b786..aacf552fca83 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/doc.go index 1c67cc3a94c4..be1c70fdb5a7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/autoscaling + package v1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.pb.go index e90dd5d62c7f..3ac42bc0450f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -42,6 +42,9 @@ import math "math" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -49,37 +52,29 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *CrossVersionObjectReference) Reset() { *m = CrossVersionObjectReference{} } -func (m *CrossVersionObjectReference) String() string { return proto.CompactTextString(m) } -func (*CrossVersionObjectReference) ProtoMessage() {} +func (m *CrossVersionObjectReference) Reset() { *m = CrossVersionObjectReference{} } +func (*CrossVersionObjectReference) ProtoMessage() {} -func (m *HorizontalPodAutoscaler) Reset() { *m = HorizontalPodAutoscaler{} } -func (m *HorizontalPodAutoscaler) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscaler) ProtoMessage() {} +func (m *HorizontalPodAutoscaler) Reset() { *m = HorizontalPodAutoscaler{} } +func (*HorizontalPodAutoscaler) ProtoMessage() {} -func (m *HorizontalPodAutoscalerList) Reset() { *m = HorizontalPodAutoscalerList{} } -func (m *HorizontalPodAutoscalerList) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerList) ProtoMessage() {} +func (m *HorizontalPodAutoscalerList) Reset() { *m = HorizontalPodAutoscalerList{} } +func (*HorizontalPodAutoscalerList) ProtoMessage() {} -func (m *HorizontalPodAutoscalerSpec) Reset() { *m = HorizontalPodAutoscalerSpec{} } -func (m *HorizontalPodAutoscalerSpec) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerSpec) ProtoMessage() {} +func (m *HorizontalPodAutoscalerSpec) Reset() { *m = HorizontalPodAutoscalerSpec{} } +func (*HorizontalPodAutoscalerSpec) ProtoMessage() {} -func (m *HorizontalPodAutoscalerStatus) Reset() { *m = HorizontalPodAutoscalerStatus{} } -func (m *HorizontalPodAutoscalerStatus) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerStatus) ProtoMessage() {} +func (m *HorizontalPodAutoscalerStatus) Reset() { *m = HorizontalPodAutoscalerStatus{} } +func (*HorizontalPodAutoscalerStatus) ProtoMessage() {} -func (m *Scale) Reset() { *m = Scale{} } -func (m *Scale) String() string { return proto.CompactTextString(m) } -func (*Scale) ProtoMessage() {} +func (m *Scale) Reset() { *m = Scale{} } +func (*Scale) ProtoMessage() {} -func (m *ScaleSpec) Reset() { *m = ScaleSpec{} } -func (m *ScaleSpec) String() string { return proto.CompactTextString(m) } -func (*ScaleSpec) ProtoMessage() {} +func (m *ScaleSpec) Reset() { *m = ScaleSpec{} } +func (*ScaleSpec) ProtoMessage() {} -func (m *ScaleStatus) Reset() { *m = ScaleStatus{} } -func (m *ScaleStatus) String() string { return proto.CompactTextString(m) } -func (*ScaleStatus) ProtoMessage() {} +func (m *ScaleStatus) Reset() { *m = ScaleStatus{} } +func (*ScaleStatus) ProtoMessage() {} func init() { proto.RegisterType((*CrossVersionObjectReference)(nil), "k8s.io.kubernetes.pkg.apis.autoscaling.v1.CrossVersionObjectReference") @@ -511,6 +506,109 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *CrossVersionObjectReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CrossVersionObjectReference{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscaler) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscaler{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "HorizontalPodAutoscalerSpec", "HorizontalPodAutoscalerSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "HorizontalPodAutoscalerStatus", "HorizontalPodAutoscalerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "HorizontalPodAutoscaler", "HorizontalPodAutoscaler", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerSpec{`, + `ScaleTargetRef:` + strings.Replace(strings.Replace(this.ScaleTargetRef.String(), "CrossVersionObjectReference", "CrossVersionObjectReference", 1), `&`, ``, 1) + `,`, + `MinReplicas:` + valueToStringGenerated(this.MinReplicas) + `,`, + `MaxReplicas:` + fmt.Sprintf("%v", this.MaxReplicas) + `,`, + `TargetCPUUtilizationPercentage:` + valueToStringGenerated(this.TargetCPUUtilizationPercentage) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerStatus{`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, + `LastScaleTime:` + strings.Replace(fmt.Sprintf("%v", this.LastScaleTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `CurrentReplicas:` + fmt.Sprintf("%v", this.CurrentReplicas) + `,`, + `DesiredReplicas:` + fmt.Sprintf("%v", this.DesiredReplicas) + `,`, + `CurrentCPUUtilizationPercentage:` + valueToStringGenerated(this.CurrentCPUUtilizationPercentage) + `,`, + `}`, + }, "") + return s +} +func (this *Scale) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Scale{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ScaleSpec", "ScaleSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ScaleStatus", "ScaleStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ScaleSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScaleSpec{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `}`, + }, "") + return s +} +func (this *ScaleStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScaleStatus{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `Selector:` + fmt.Sprintf("%v", this.Selector) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *CrossVersionObjectReference) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.proto index b41980743b3f..891aff3b52b2 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package k8s.io.kubernetes.pkg.apis.autoscaling.v1; import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; +import "k8s.io/kubernetes/pkg/runtime/generated.proto"; import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; // Package-wide variables from generator "generated". @@ -31,10 +32,10 @@ option go_package = "v1"; // CrossVersionObjectReference contains enough information to let you identify the referred resource. message CrossVersionObjectReference { - // Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds" optional string kind = 1; - // Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 2; // API version of the referent @@ -43,10 +44,10 @@ message CrossVersionObjectReference { // configuration of a horizontal pod autoscaler. message HorizontalPodAutoscaler { - // Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; - // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. optional HorizontalPodAutoscalerSpec spec = 2; // current information about the autoscaler. @@ -101,13 +102,13 @@ message HorizontalPodAutoscalerStatus { // Scale represents a scaling request for a resource. message Scale { - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. optional ScaleSpec spec = 2; - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. optional ScaleStatus status = 3; } @@ -125,7 +126,7 @@ message ScaleStatus { // label query over pods that should match the replicas count. This is same // as the label selector but in the string format to avoid introspection // by clients. The string will be in the same format as the query-param syntax. - // More info about label selectors: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info about label selectors: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional string selector = 2; } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go index fed2cdf48cff..93d9535e4a2e 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go index d8401bb8bccb..ab9ebc5120c5 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go index 7acb52720886..035288cb2109 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import ( // CrossVersionObjectReference contains enough information to let you identify the referred resource. type CrossVersionObjectReference struct { - // Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds" + // Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds" Kind string `json:"kind" protobuf:"bytes,1,opt,name=kind"` - // Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name" protobuf:"bytes,2,opt,name=name"` // API version of the referent APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,3,opt,name=apiVersion"` @@ -70,10 +70,10 @@ type HorizontalPodAutoscalerStatus struct { // configuration of a horizontal pod autoscaler. type HorizontalPodAutoscaler struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // current information about the autoscaler. @@ -93,13 +93,13 @@ type HorizontalPodAutoscalerList struct { // Scale represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -117,6 +117,6 @@ type ScaleStatus struct { // label query over pods that should match the replicas count. This is same // as the label selector but in the string format to avoid introspection // by clients. The string will be in the same format as the query-param syntax. - // More info about label selectors: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info about label selectors: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector string `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go index 904e36a6a930..6b9bcf47e80d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE var map_CrossVersionObjectReference = map[string]string{ "": "CrossVersionObjectReference contains enough information to let you identify the referred resource.", - "kind": "Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds\"", - "name": "Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", + "kind": "Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds\"", + "name": "Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", "apiVersion": "API version of the referent", } @@ -40,8 +40,8 @@ func (CrossVersionObjectReference) SwaggerDoc() map[string]string { var map_HorizontalPodAutoscaler = map[string]string{ "": "configuration of a horizontal pod autoscaler.", - "metadata": "Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status.", + "metadata": "Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.", "status": "current information about the autoscaler.", } @@ -86,9 +86,9 @@ func (HorizontalPodAutoscalerStatus) SwaggerDoc() map[string]string { var map_Scale = map[string]string{ "": "Scale represents a scaling request for a resource.", - "metadata": "Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata.", - "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status.", - "status": "current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only.", + "metadata": "Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata.", + "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.", + "status": "current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only.", } func (Scale) SwaggerDoc() map[string]string { @@ -107,7 +107,7 @@ func (ScaleSpec) SwaggerDoc() map[string]string { var map_ScaleStatus = map[string]string{ "": "ScaleStatus represents the current status of a scale subresource.", "replicas": "actual number of observed instances of the scaled object.", - "selector": "label query over pods that should match the replicas count. This is same as the label selector but in the string format to avoid introspection by clients. The string will be in the same format as the query-param syntax. More info about label selectors: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", + "selector": "label query over pods that should match the replicas count. This is same as the label selector but in the string format to avoid introspection by clients. The string will be in the same format as the query-param syntax. More info about label selectors: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", } func (ScaleStatus) SwaggerDoc() map[string]string { diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.conversion.go index 11ca6a056d8a..3d569928380d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..b218efcced1a --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/v1/zz_generated.deepcopy.go @@ -0,0 +1,183 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + api_v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_CrossVersionObjectReference, InType: reflect.TypeOf(func() *CrossVersionObjectReference { var x *CrossVersionObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HorizontalPodAutoscaler, InType: reflect.TypeOf(func() *HorizontalPodAutoscaler { var x *HorizontalPodAutoscaler; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HorizontalPodAutoscalerList, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerList { var x *HorizontalPodAutoscalerList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HorizontalPodAutoscalerSpec, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerSpec { var x *HorizontalPodAutoscalerSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_HorizontalPodAutoscalerStatus, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerStatus { var x *HorizontalPodAutoscalerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Scale, InType: reflect.TypeOf(func() *Scale { var x *Scale; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ScaleSpec, InType: reflect.TypeOf(func() *ScaleSpec { var x *ScaleSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_ScaleStatus, InType: reflect.TypeOf(func() *ScaleStatus { var x *ScaleStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1_CrossVersionObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CrossVersionObjectReference) + out := out.(*CrossVersionObjectReference) + out.Kind = in.Kind + out.Name = in.Name + out.APIVersion = in.APIVersion + return nil + } +} + +func DeepCopy_v1_HorizontalPodAutoscaler(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscaler) + out := out.(*HorizontalPodAutoscaler) + out.TypeMeta = in.TypeMeta + if err := api_v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_HorizontalPodAutoscalerList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerList) + out := out.(*HorizontalPodAutoscalerList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]HorizontalPodAutoscaler, len(*in)) + for i := range *in { + if err := DeepCopy_v1_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_HorizontalPodAutoscalerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerSpec) + out := out.(*HorizontalPodAutoscalerSpec) + out.ScaleTargetRef = in.ScaleTargetRef + if in.MinReplicas != nil { + in, out := &in.MinReplicas, &out.MinReplicas + *out = new(int32) + **out = **in + } else { + out.MinReplicas = nil + } + out.MaxReplicas = in.MaxReplicas + if in.TargetCPUUtilizationPercentage != nil { + in, out := &in.TargetCPUUtilizationPercentage, &out.TargetCPUUtilizationPercentage + *out = new(int32) + **out = **in + } else { + out.TargetCPUUtilizationPercentage = nil + } + return nil + } +} + +func DeepCopy_v1_HorizontalPodAutoscalerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerStatus) + out := out.(*HorizontalPodAutoscalerStatus) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } else { + out.ObservedGeneration = nil + } + if in.LastScaleTime != nil { + in, out := &in.LastScaleTime, &out.LastScaleTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.LastScaleTime = nil + } + out.CurrentReplicas = in.CurrentReplicas + out.DesiredReplicas = in.DesiredReplicas + if in.CurrentCPUUtilizationPercentage != nil { + in, out := &in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage + *out = new(int32) + **out = **in + } else { + out.CurrentCPUUtilizationPercentage = nil + } + return nil + } +} + +func DeepCopy_v1_Scale(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Scale) + out := out.(*Scale) + out.TypeMeta = in.TypeMeta + if err := api_v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1_ScaleSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleSpec) + out := out.(*ScaleSpec) + out.Replicas = in.Replicas + return nil + } +} + +func DeepCopy_v1_ScaleStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleStatus) + out := out.(*ScaleStatus) + out.Replicas = in.Replicas + out.Selector = in.Selector + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/validation/validation.go index 3432e3cb1c40..d7e0e17decf8 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/zz_generated.deepcopy.go new file mode 100644 index 000000000000..89522247deee --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/autoscaling/zz_generated.deepcopy.go @@ -0,0 +1,182 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package autoscaling + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_CrossVersionObjectReference, InType: reflect.TypeOf(func() *CrossVersionObjectReference { var x *CrossVersionObjectReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_HorizontalPodAutoscaler, InType: reflect.TypeOf(func() *HorizontalPodAutoscaler { var x *HorizontalPodAutoscaler; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_HorizontalPodAutoscalerList, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerList { var x *HorizontalPodAutoscalerList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_HorizontalPodAutoscalerSpec, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerSpec { var x *HorizontalPodAutoscalerSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_HorizontalPodAutoscalerStatus, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerStatus { var x *HorizontalPodAutoscalerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_Scale, InType: reflect.TypeOf(func() *Scale { var x *Scale; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_ScaleSpec, InType: reflect.TypeOf(func() *ScaleSpec { var x *ScaleSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_autoscaling_ScaleStatus, InType: reflect.TypeOf(func() *ScaleStatus { var x *ScaleStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_autoscaling_CrossVersionObjectReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CrossVersionObjectReference) + out := out.(*CrossVersionObjectReference) + out.Kind = in.Kind + out.Name = in.Name + out.APIVersion = in.APIVersion + return nil + } +} + +func DeepCopy_autoscaling_HorizontalPodAutoscaler(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscaler) + out := out.(*HorizontalPodAutoscaler) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_autoscaling_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_autoscaling_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_autoscaling_HorizontalPodAutoscalerList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerList) + out := out.(*HorizontalPodAutoscalerList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]HorizontalPodAutoscaler, len(*in)) + for i := range *in { + if err := DeepCopy_autoscaling_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_autoscaling_HorizontalPodAutoscalerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerSpec) + out := out.(*HorizontalPodAutoscalerSpec) + out.ScaleTargetRef = in.ScaleTargetRef + if in.MinReplicas != nil { + in, out := &in.MinReplicas, &out.MinReplicas + *out = new(int32) + **out = **in + } else { + out.MinReplicas = nil + } + out.MaxReplicas = in.MaxReplicas + if in.TargetCPUUtilizationPercentage != nil { + in, out := &in.TargetCPUUtilizationPercentage, &out.TargetCPUUtilizationPercentage + *out = new(int32) + **out = **in + } else { + out.TargetCPUUtilizationPercentage = nil + } + return nil + } +} + +func DeepCopy_autoscaling_HorizontalPodAutoscalerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerStatus) + out := out.(*HorizontalPodAutoscalerStatus) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } else { + out.ObservedGeneration = nil + } + if in.LastScaleTime != nil { + in, out := &in.LastScaleTime, &out.LastScaleTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.LastScaleTime = nil + } + out.CurrentReplicas = in.CurrentReplicas + out.DesiredReplicas = in.DesiredReplicas + if in.CurrentCPUUtilizationPercentage != nil { + in, out := &in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage + *out = new(int32) + **out = **in + } else { + out.CurrentCPUUtilizationPercentage = nil + } + return nil + } +} + +func DeepCopy_autoscaling_Scale(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Scale) + out := out.(*Scale) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + out.Status = in.Status + return nil + } +} + +func DeepCopy_autoscaling_ScaleSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleSpec) + out := out.(*ScaleSpec) + out.Replicas = in.Replicas + return nil + } +} + +func DeepCopy_autoscaling_ScaleStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleStatus) + out := out.(*ScaleStatus) + out.Replicas = in.Replicas + out.Selector = in.Selector + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go deleted file mode 100644 index 6e08ec410914..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/deep_copy_generated.go +++ /dev/null @@ -1,284 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package batch - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_batch_Job, - DeepCopy_batch_JobCondition, - DeepCopy_batch_JobList, - DeepCopy_batch_JobSpec, - DeepCopy_batch_JobStatus, - DeepCopy_batch_JobTemplate, - DeepCopy_batch_JobTemplateSpec, - DeepCopy_batch_ScheduledJob, - DeepCopy_batch_ScheduledJobList, - DeepCopy_batch_ScheduledJobSpec, - DeepCopy_batch_ScheduledJobStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_batch_Job(in Job, out *Job, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_batch_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_batch_JobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_JobCondition(in JobCondition, out *JobCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_batch_JobList(in JobList, out *JobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Job, len(in)) - for i := range in { - if err := DeepCopy_batch_Job(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_batch_JobSpec(in JobSpec, out *JobSpec, c *conversion.Cloner) error { - if in.Parallelism != nil { - in, out := in.Parallelism, &out.Parallelism - *out = new(int32) - **out = *in - } else { - out.Parallelism = nil - } - if in.Completions != nil { - in, out := in.Completions, &out.Completions - *out = new(int32) - **out = *in - } else { - out.Completions = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if in.ManualSelector != nil { - in, out := in.ManualSelector, &out.ManualSelector - *out = new(bool) - **out = *in - } else { - out.ManualSelector = nil - } - if err := api.DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_JobStatus(in JobStatus, out *JobStatus, c *conversion.Cloner) error { - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]JobCondition, len(in)) - for i := range in { - if err := DeepCopy_batch_JobCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.CompletionTime != nil { - in, out := in.CompletionTime, &out.CompletionTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.CompletionTime = nil - } - out.Active = in.Active - out.Succeeded = in.Succeeded - out.Failed = in.Failed - return nil -} - -func DeepCopy_batch_JobTemplate(in JobTemplate, out *JobTemplate, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_batch_JobTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_JobTemplateSpec(in JobTemplateSpec, out *JobTemplateSpec, c *conversion.Cloner) error { - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_batch_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_ScheduledJob(in ScheduledJob, out *ScheduledJob, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_batch_ScheduledJobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_batch_ScheduledJobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_ScheduledJobList(in ScheduledJobList, out *ScheduledJobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ScheduledJob, len(in)) - for i := range in { - if err := DeepCopy_batch_ScheduledJob(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_batch_ScheduledJobSpec(in ScheduledJobSpec, out *ScheduledJobSpec, c *conversion.Cloner) error { - out.Schedule = in.Schedule - if in.StartingDeadlineSeconds != nil { - in, out := in.StartingDeadlineSeconds, &out.StartingDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.StartingDeadlineSeconds = nil - } - out.ConcurrencyPolicy = in.ConcurrencyPolicy - if in.Suspend != nil { - in, out := in.Suspend, &out.Suspend - *out = new(bool) - **out = *in - } else { - out.Suspend = nil - } - if err := DeepCopy_batch_JobTemplateSpec(in.JobTemplate, &out.JobTemplate, c); err != nil { - return err - } - return nil -} - -func DeepCopy_batch_ScheduledJobStatus(in ScheduledJobStatus, out *ScheduledJobStatus, c *conversion.Cloner) error { - if in.Active != nil { - in, out := in.Active, &out.Active - *out = make([]api.ObjectReference, len(in)) - for i := range in { - if err := api.DeepCopy_api_ObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Active = nil - } - if in.LastScheduleTime != nil { - in, out := in.LastScheduleTime, &out.LastScheduleTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.LastScheduleTime = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/doc.go new file mode 100644 index 000000000000..c6b203cd8ebe --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package batch diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/install/install.go index 9d1a88603b8f..22f92b708c83 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/register.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/register.go index cafa3fd8985b..641df5f3911b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/types.generated.go index 14c44a0f828b..03f0d248c64b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/types.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/types.go index 1ad4699148d2..61a35d47fa7f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,15 +27,15 @@ import ( type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty"` } @@ -43,7 +43,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Job. @@ -54,22 +54,22 @@ type JobList struct { type JobTemplate struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Template defines jobs that will be created from this template - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Template JobTemplateSpec `json:"template,omitempty"` } // JobTemplateSpec describes the data a Job should have when created from a template type JobTemplateSpec struct { // Standard object's metadata of the jobs created from this template. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Specification of the desired behavior of the job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty"` } @@ -171,15 +171,15 @@ type JobCondition struct { type ScheduledJob struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Spec is a structure defining the expected behavior of a job, including the schedule. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ScheduledJobSpec `json:"spec,omitempty"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ScheduledJobStatus `json:"status,omitempty"` } @@ -187,7 +187,7 @@ type ScheduledJob struct { type ScheduledJobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of ScheduledJob. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go index 2d163c6e9a8e..8846af1ed5e3 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go deleted file mode 100644 index c2a50b4ee181..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/deep_copy_generated.go +++ /dev/null @@ -1,211 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - api_v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1_Job, - DeepCopy_v1_JobCondition, - DeepCopy_v1_JobList, - DeepCopy_v1_JobSpec, - DeepCopy_v1_JobStatus, - DeepCopy_v1_LabelSelector, - DeepCopy_v1_LabelSelectorRequirement, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1_Job(in Job, out *Job, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api_v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1_JobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_JobCondition(in JobCondition, out *JobCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v1_JobList(in JobList, out *JobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Job, len(in)) - for i := range in { - if err := DeepCopy_v1_Job(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1_JobSpec(in JobSpec, out *JobSpec, c *conversion.Cloner) error { - if in.Parallelism != nil { - in, out := in.Parallelism, &out.Parallelism - *out = new(int32) - **out = *in - } else { - out.Parallelism = nil - } - if in.Completions != nil { - in, out := in.Completions, &out.Completions - *out = new(int32) - **out = *in - } else { - out.Completions = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if in.ManualSelector != nil { - in, out := in.ManualSelector, &out.ManualSelector - *out = new(bool) - **out = *in - } else { - out.ManualSelector = nil - } - if err := api_v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1_JobStatus(in JobStatus, out *JobStatus, c *conversion.Cloner) error { - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]JobCondition, len(in)) - for i := range in { - if err := DeepCopy_v1_JobCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.CompletionTime != nil { - in, out := in.CompletionTime, &out.CompletionTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.CompletionTime = nil - } - out.Active = in.Active - out.Succeeded = in.Succeeded - out.Failed = in.Failed - return nil -} - -func DeepCopy_v1_LabelSelector(in LabelSelector, out *LabelSelector, c *conversion.Cloner) error { - if in.MatchLabels != nil { - in, out := in.MatchLabels, &out.MatchLabels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.MatchLabels = nil - } - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]LabelSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_v1_LabelSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_v1_LabelSelectorRequirement(in LabelSelectorRequirement, out *LabelSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go index 81aa90c1d095..571d2c524fdb 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/doc.go index 1c67cc3a94c4..5695b9e4022b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/batch + package v1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.pb.go index 95646919d8c0..218a963861dd 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -42,6 +42,10 @@ import math "math" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" import k8s_io_kubernetes_pkg_api_v1 "k8s.io/kubernetes/pkg/api/v1" +import strings "strings" +import reflect "reflect" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -49,33 +53,26 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *Job) Reset() { *m = Job{} } -func (m *Job) String() string { return proto.CompactTextString(m) } -func (*Job) ProtoMessage() {} +func (m *Job) Reset() { *m = Job{} } +func (*Job) ProtoMessage() {} -func (m *JobCondition) Reset() { *m = JobCondition{} } -func (m *JobCondition) String() string { return proto.CompactTextString(m) } -func (*JobCondition) ProtoMessage() {} +func (m *JobCondition) Reset() { *m = JobCondition{} } +func (*JobCondition) ProtoMessage() {} -func (m *JobList) Reset() { *m = JobList{} } -func (m *JobList) String() string { return proto.CompactTextString(m) } -func (*JobList) ProtoMessage() {} +func (m *JobList) Reset() { *m = JobList{} } +func (*JobList) ProtoMessage() {} -func (m *JobSpec) Reset() { *m = JobSpec{} } -func (m *JobSpec) String() string { return proto.CompactTextString(m) } -func (*JobSpec) ProtoMessage() {} +func (m *JobSpec) Reset() { *m = JobSpec{} } +func (*JobSpec) ProtoMessage() {} -func (m *JobStatus) Reset() { *m = JobStatus{} } -func (m *JobStatus) String() string { return proto.CompactTextString(m) } -func (*JobStatus) ProtoMessage() {} +func (m *JobStatus) Reset() { *m = JobStatus{} } +func (*JobStatus) ProtoMessage() {} -func (m *LabelSelector) Reset() { *m = LabelSelector{} } -func (m *LabelSelector) String() string { return proto.CompactTextString(m) } -func (*LabelSelector) ProtoMessage() {} +func (m *LabelSelector) Reset() { *m = LabelSelector{} } +func (*LabelSelector) ProtoMessage() {} -func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } -func (m *LabelSelectorRequirement) String() string { return proto.CompactTextString(m) } -func (*LabelSelectorRequirement) ProtoMessage() {} +func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } +func (*LabelSelectorRequirement) ProtoMessage() {} func init() { proto.RegisterType((*Job)(nil), "k8s.io.kubernetes.pkg.apis.batch.v1.Job") @@ -591,6 +588,115 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *Job) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Job{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "JobSpec", "JobSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "JobStatus", "JobStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `LastProbeTime:` + strings.Replace(strings.Replace(this.LastProbeTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(this.LastTransitionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *JobList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Job", "Job", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobSpec{`, + `Parallelism:` + valueToStringGenerated(this.Parallelism) + `,`, + `Completions:` + valueToStringGenerated(this.Completions) + `,`, + `ActiveDeadlineSeconds:` + valueToStringGenerated(this.ActiveDeadlineSeconds) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `ManualSelector:` + valueToStringGenerated(this.ManualSelector) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobStatus{`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "JobCondition", "JobCondition", 1), `&`, ``, 1) + `,`, + `StartTime:` + strings.Replace(fmt.Sprintf("%v", this.StartTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `CompletionTime:` + strings.Replace(fmt.Sprintf("%v", this.CompletionTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `Active:` + fmt.Sprintf("%v", this.Active) + `,`, + `Succeeded:` + fmt.Sprintf("%v", this.Succeeded) + `,`, + `Failed:` + fmt.Sprintf("%v", this.Failed) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelector) String() string { + if this == nil { + return "nil" + } + keysForMatchLabels := make([]string, 0, len(this.MatchLabels)) + for k := range this.MatchLabels { + keysForMatchLabels = append(keysForMatchLabels, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMatchLabels) + mapStringForMatchLabels := "map[string]string{" + for _, k := range keysForMatchLabels { + mapStringForMatchLabels += fmt.Sprintf("%v: %v,", k, this.MatchLabels[k]) + } + mapStringForMatchLabels += "}" + s := strings.Join([]string{`&LabelSelector{`, + `MatchLabels:` + mapStringForMatchLabels + `,`, + `MatchExpressions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.MatchExpressions), "LabelSelectorRequirement", "LabelSelectorRequirement", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelectorRequirement) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LabelSelectorRequirement{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Values:` + fmt.Sprintf("%v", this.Values) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *Job) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.proto index 8d50f7f7281f..264959e4f8c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package k8s.io.kubernetes.pkg.apis.batch.v1; import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; +import "k8s.io/kubernetes/pkg/runtime/generated.proto"; import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; // Package-wide variables from generator "generated". @@ -32,15 +33,15 @@ option go_package = "v1"; // Job represents the configuration of a single job. message Job { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobSpec spec = 2; // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobStatus status = 3; } @@ -68,7 +69,7 @@ message JobCondition { // JobList is a collection of jobs. message JobList { // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of Job. @@ -81,7 +82,7 @@ message JobSpec { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 parallelism = 1; // Completions specifies the desired number of successfully finished pods the @@ -89,7 +90,7 @@ message JobSpec { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 completions = 2; // Optional duration in seconds relative to the startTime that the job may be active @@ -98,7 +99,7 @@ message JobSpec { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional LabelSelector selector = 4; // ManualSelector controls generation of pod labels and pod selectors. @@ -110,19 +111,19 @@ message JobSpec { // and other jobs to not function correctly. However, You may see // `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` // API. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md optional bool manualSelector = 5; // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 6; } // JobStatus represents the current state of a Job. message JobStatus { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md repeated JobCondition conditions = 1; // StartTime represents time when the job was acknowledged by the Job Manager. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/register.go index d8c087f1bb96..3631c02d12a8 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go index 58d5f6f54c77..a44952c7aff9 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.go index 35ec05206e1a..a821e936622b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,15 +27,15 @@ import ( type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -43,7 +43,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Job. @@ -57,7 +57,7 @@ type JobSpec struct { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Parallelism *int32 `json:"parallelism,omitempty" protobuf:"varint,1,opt,name=parallelism"` // Completions specifies the desired number of successfully finished pods the @@ -65,7 +65,7 @@ type JobSpec struct { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Completions *int32 `json:"completions,omitempty" protobuf:"varint,2,opt,name=completions"` // Optional duration in seconds relative to the startTime that the job may be active @@ -74,7 +74,7 @@ type JobSpec struct { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty" protobuf:"bytes,4,opt,name=selector"` // ManualSelector controls generation of pod labels and pod selectors. @@ -86,12 +86,12 @@ type JobSpec struct { // and other jobs to not function correctly. However, You may see // `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` // API. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md ManualSelector *bool `json:"manualSelector,omitempty" protobuf:"varint,5,opt,name=manualSelector"` // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,6,opt,name=template"` } @@ -99,7 +99,7 @@ type JobSpec struct { type JobStatus struct { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Conditions []JobCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // StartTime represents time when the job was acknowledged by the Job Manager. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go index 21c621abfa0a..aa0dbcc2fd16 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes 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 @@ package v1 // AUTO-GENERATED FUNCTIONS START HERE var map_Job = map[string]string{ "": "Job represents the configuration of a single job.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Job) SwaggerDoc() map[string]string { @@ -54,7 +54,7 @@ func (JobCondition) SwaggerDoc() map[string]string { var map_JobList = map[string]string{ "": "JobList is a collection of jobs.", - "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Job.", } @@ -64,12 +64,12 @@ func (JobList) SwaggerDoc() map[string]string { var map_JobSpec = map[string]string{ "": "JobSpec describes how the job execution will look like.", - "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", - "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", + "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "activeDeadlineSeconds": "Optional duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer", - "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "manualSelector": "ManualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md", - "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "manualSelector": "ManualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md", + "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", } func (JobSpec) SwaggerDoc() map[string]string { @@ -78,7 +78,7 @@ func (JobSpec) SwaggerDoc() map[string]string { var map_JobStatus = map[string]string{ "": "JobStatus represents the current state of a Job.", - "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "startTime": "StartTime represents time when the job was acknowledged by the Job Manager. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "completionTime": "CompletionTime represents time when the job was completed. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "active": "Active is the number of actively running pods.", diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.conversion.go index 4bb13c498d5f..88e6d961ffa3 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..e25230089714 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v1/zz_generated.deepcopy.go @@ -0,0 +1,226 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + api_v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_Job, InType: reflect.TypeOf(func() *Job { var x *Job; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_JobCondition, InType: reflect.TypeOf(func() *JobCondition { var x *JobCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_JobList, InType: reflect.TypeOf(func() *JobList { var x *JobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_JobSpec, InType: reflect.TypeOf(func() *JobSpec { var x *JobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_JobStatus, InType: reflect.TypeOf(func() *JobStatus { var x *JobStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LabelSelector, InType: reflect.TypeOf(func() *LabelSelector { var x *LabelSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1_LabelSelectorRequirement, InType: reflect.TypeOf(func() *LabelSelectorRequirement { var x *LabelSelectorRequirement; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1_Job(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Job) + out := out.(*Job) + out.TypeMeta = in.TypeMeta + if err := api_v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1_JobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_JobCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobCondition) + out := out.(*JobCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1_JobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobList) + out := out.(*JobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Job, len(*in)) + for i := range *in { + if err := DeepCopy_v1_Job(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1_JobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobSpec) + out := out.(*JobSpec) + if in.Parallelism != nil { + in, out := &in.Parallelism, &out.Parallelism + *out = new(int32) + **out = **in + } else { + out.Parallelism = nil + } + if in.Completions != nil { + in, out := &in.Completions, &out.Completions + *out = new(int32) + **out = **in + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + in, out := &in.ManualSelector, &out.ManualSelector + *out = new(bool) + **out = **in + } else { + out.ManualSelector = nil + } + if err := api_v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1_JobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobStatus) + out := out.(*JobStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]JobCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v1_JobCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.CompletionTime = nil + } + out.Active = in.Active + out.Succeeded = in.Succeeded + out.Failed = in.Failed + return nil + } +} + +func DeepCopy_v1_LabelSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelector) + out := out.(*LabelSelector) + if in.MatchLabels != nil { + in, out := &in.MatchLabels, &out.MatchLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]LabelSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_v1_LabelSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_v1_LabelSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelectorRequirement) + out := out.(*LabelSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion.go index 4714fda0fb3e..2d5710a23157 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/deep_copy_generated.go deleted file mode 100644 index 92cb71ea080c..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/deep_copy_generated.go +++ /dev/null @@ -1,324 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v2alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v2alpha1_Job, - DeepCopy_v2alpha1_JobCondition, - DeepCopy_v2alpha1_JobList, - DeepCopy_v2alpha1_JobSpec, - DeepCopy_v2alpha1_JobStatus, - DeepCopy_v2alpha1_JobTemplate, - DeepCopy_v2alpha1_JobTemplateSpec, - DeepCopy_v2alpha1_LabelSelector, - DeepCopy_v2alpha1_LabelSelectorRequirement, - DeepCopy_v2alpha1_ScheduledJob, - DeepCopy_v2alpha1_ScheduledJobList, - DeepCopy_v2alpha1_ScheduledJobSpec, - DeepCopy_v2alpha1_ScheduledJobStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v2alpha1_Job(in Job, out *Job, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_JobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_JobCondition(in JobCondition, out *JobCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v2alpha1_JobList(in JobList, out *JobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Job, len(in)) - for i := range in { - if err := DeepCopy_v2alpha1_Job(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v2alpha1_JobSpec(in JobSpec, out *JobSpec, c *conversion.Cloner) error { - if in.Parallelism != nil { - in, out := in.Parallelism, &out.Parallelism - *out = new(int32) - **out = *in - } else { - out.Parallelism = nil - } - if in.Completions != nil { - in, out := in.Completions, &out.Completions - *out = new(int32) - **out = *in - } else { - out.Completions = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v2alpha1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if in.ManualSelector != nil { - in, out := in.ManualSelector, &out.ManualSelector - *out = new(bool) - **out = *in - } else { - out.ManualSelector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_JobStatus(in JobStatus, out *JobStatus, c *conversion.Cloner) error { - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]JobCondition, len(in)) - for i := range in { - if err := DeepCopy_v2alpha1_JobCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.CompletionTime != nil { - in, out := in.CompletionTime, &out.CompletionTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.CompletionTime = nil - } - out.Active = in.Active - out.Succeeded = in.Succeeded - out.Failed = in.Failed - return nil -} - -func DeepCopy_v2alpha1_JobTemplate(in JobTemplate, out *JobTemplate, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_JobTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_JobTemplateSpec(in JobTemplateSpec, out *JobTemplateSpec, c *conversion.Cloner) error { - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_LabelSelector(in LabelSelector, out *LabelSelector, c *conversion.Cloner) error { - if in.MatchLabels != nil { - in, out := in.MatchLabels, &out.MatchLabels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.MatchLabels = nil - } - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]LabelSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_v2alpha1_LabelSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_v2alpha1_LabelSelectorRequirement(in LabelSelectorRequirement, out *LabelSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} - -func DeepCopy_v2alpha1_ScheduledJob(in ScheduledJob, out *ScheduledJob, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_ScheduledJobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v2alpha1_ScheduledJobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_ScheduledJobList(in ScheduledJobList, out *ScheduledJobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ScheduledJob, len(in)) - for i := range in { - if err := DeepCopy_v2alpha1_ScheduledJob(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v2alpha1_ScheduledJobSpec(in ScheduledJobSpec, out *ScheduledJobSpec, c *conversion.Cloner) error { - out.Schedule = in.Schedule - if in.StartingDeadlineSeconds != nil { - in, out := in.StartingDeadlineSeconds, &out.StartingDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.StartingDeadlineSeconds = nil - } - out.ConcurrencyPolicy = in.ConcurrencyPolicy - if in.Suspend != nil { - in, out := in.Suspend, &out.Suspend - *out = new(bool) - **out = *in - } else { - out.Suspend = nil - } - if err := DeepCopy_v2alpha1_JobTemplateSpec(in.JobTemplate, &out.JobTemplate, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v2alpha1_ScheduledJobStatus(in ScheduledJobStatus, out *ScheduledJobStatus, c *conversion.Cloner) error { - if in.Active != nil { - in, out := in.Active, &out.Active - *out = make([]v1.ObjectReference, len(in)) - for i := range in { - if err := v1.DeepCopy_v1_ObjectReference(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Active = nil - } - if in.LastScheduleTime != nil { - in, out := in.LastScheduleTime, &out.LastScheduleTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.LastScheduleTime = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/defaults.go index 72da797c77f7..a7d24ceac910 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/doc.go index 0e6b67b5894e..76b5d325131b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/batch + package v2alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.pb.go index 17192c01c483..48364e1044e9 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -48,6 +48,10 @@ import math "math" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" import k8s_io_kubernetes_pkg_api_v1 "k8s.io/kubernetes/pkg/api/v1" +import strings "strings" +import reflect "reflect" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -55,57 +59,44 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *Job) Reset() { *m = Job{} } -func (m *Job) String() string { return proto.CompactTextString(m) } -func (*Job) ProtoMessage() {} +func (m *Job) Reset() { *m = Job{} } +func (*Job) ProtoMessage() {} -func (m *JobCondition) Reset() { *m = JobCondition{} } -func (m *JobCondition) String() string { return proto.CompactTextString(m) } -func (*JobCondition) ProtoMessage() {} +func (m *JobCondition) Reset() { *m = JobCondition{} } +func (*JobCondition) ProtoMessage() {} -func (m *JobList) Reset() { *m = JobList{} } -func (m *JobList) String() string { return proto.CompactTextString(m) } -func (*JobList) ProtoMessage() {} +func (m *JobList) Reset() { *m = JobList{} } +func (*JobList) ProtoMessage() {} -func (m *JobSpec) Reset() { *m = JobSpec{} } -func (m *JobSpec) String() string { return proto.CompactTextString(m) } -func (*JobSpec) ProtoMessage() {} +func (m *JobSpec) Reset() { *m = JobSpec{} } +func (*JobSpec) ProtoMessage() {} -func (m *JobStatus) Reset() { *m = JobStatus{} } -func (m *JobStatus) String() string { return proto.CompactTextString(m) } -func (*JobStatus) ProtoMessage() {} +func (m *JobStatus) Reset() { *m = JobStatus{} } +func (*JobStatus) ProtoMessage() {} -func (m *JobTemplate) Reset() { *m = JobTemplate{} } -func (m *JobTemplate) String() string { return proto.CompactTextString(m) } -func (*JobTemplate) ProtoMessage() {} +func (m *JobTemplate) Reset() { *m = JobTemplate{} } +func (*JobTemplate) ProtoMessage() {} -func (m *JobTemplateSpec) Reset() { *m = JobTemplateSpec{} } -func (m *JobTemplateSpec) String() string { return proto.CompactTextString(m) } -func (*JobTemplateSpec) ProtoMessage() {} +func (m *JobTemplateSpec) Reset() { *m = JobTemplateSpec{} } +func (*JobTemplateSpec) ProtoMessage() {} -func (m *LabelSelector) Reset() { *m = LabelSelector{} } -func (m *LabelSelector) String() string { return proto.CompactTextString(m) } -func (*LabelSelector) ProtoMessage() {} +func (m *LabelSelector) Reset() { *m = LabelSelector{} } +func (*LabelSelector) ProtoMessage() {} -func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } -func (m *LabelSelectorRequirement) String() string { return proto.CompactTextString(m) } -func (*LabelSelectorRequirement) ProtoMessage() {} +func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } +func (*LabelSelectorRequirement) ProtoMessage() {} -func (m *ScheduledJob) Reset() { *m = ScheduledJob{} } -func (m *ScheduledJob) String() string { return proto.CompactTextString(m) } -func (*ScheduledJob) ProtoMessage() {} +func (m *ScheduledJob) Reset() { *m = ScheduledJob{} } +func (*ScheduledJob) ProtoMessage() {} -func (m *ScheduledJobList) Reset() { *m = ScheduledJobList{} } -func (m *ScheduledJobList) String() string { return proto.CompactTextString(m) } -func (*ScheduledJobList) ProtoMessage() {} +func (m *ScheduledJobList) Reset() { *m = ScheduledJobList{} } +func (*ScheduledJobList) ProtoMessage() {} -func (m *ScheduledJobSpec) Reset() { *m = ScheduledJobSpec{} } -func (m *ScheduledJobSpec) String() string { return proto.CompactTextString(m) } -func (*ScheduledJobSpec) ProtoMessage() {} +func (m *ScheduledJobSpec) Reset() { *m = ScheduledJobSpec{} } +func (*ScheduledJobSpec) ProtoMessage() {} -func (m *ScheduledJobStatus) Reset() { *m = ScheduledJobStatus{} } -func (m *ScheduledJobStatus) String() string { return proto.CompactTextString(m) } -func (*ScheduledJobStatus) ProtoMessage() {} +func (m *ScheduledJobStatus) Reset() { *m = ScheduledJobStatus{} } +func (*ScheduledJobStatus) ProtoMessage() {} func init() { proto.RegisterType((*Job)(nil), "k8s.io.kubernetes.pkg.apis.batch.v2alpha1.Job") @@ -944,6 +935,185 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *Job) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Job{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "JobSpec", "JobSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "JobStatus", "JobStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `LastProbeTime:` + strings.Replace(strings.Replace(this.LastProbeTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(this.LastTransitionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *JobList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Job", "Job", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobSpec{`, + `Parallelism:` + valueToStringGenerated(this.Parallelism) + `,`, + `Completions:` + valueToStringGenerated(this.Completions) + `,`, + `ActiveDeadlineSeconds:` + valueToStringGenerated(this.ActiveDeadlineSeconds) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `ManualSelector:` + valueToStringGenerated(this.ManualSelector) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobStatus{`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "JobCondition", "JobCondition", 1), `&`, ``, 1) + `,`, + `StartTime:` + strings.Replace(fmt.Sprintf("%v", this.StartTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `CompletionTime:` + strings.Replace(fmt.Sprintf("%v", this.CompletionTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `Active:` + fmt.Sprintf("%v", this.Active) + `,`, + `Succeeded:` + fmt.Sprintf("%v", this.Succeeded) + `,`, + `Failed:` + fmt.Sprintf("%v", this.Failed) + `,`, + `}`, + }, "") + return s +} +func (this *JobTemplate) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobTemplate{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "JobTemplateSpec", "JobTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobTemplateSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobTemplateSpec{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "JobSpec", "JobSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelector) String() string { + if this == nil { + return "nil" + } + keysForMatchLabels := make([]string, 0, len(this.MatchLabels)) + for k := range this.MatchLabels { + keysForMatchLabels = append(keysForMatchLabels, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMatchLabels) + mapStringForMatchLabels := "map[string]string{" + for _, k := range keysForMatchLabels { + mapStringForMatchLabels += fmt.Sprintf("%v: %v,", k, this.MatchLabels[k]) + } + mapStringForMatchLabels += "}" + s := strings.Join([]string{`&LabelSelector{`, + `MatchLabels:` + mapStringForMatchLabels + `,`, + `MatchExpressions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.MatchExpressions), "LabelSelectorRequirement", "LabelSelectorRequirement", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelectorRequirement) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LabelSelectorRequirement{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Values:` + fmt.Sprintf("%v", this.Values) + `,`, + `}`, + }, "") + return s +} +func (this *ScheduledJob) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScheduledJob{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ScheduledJobSpec", "ScheduledJobSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ScheduledJobStatus", "ScheduledJobStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ScheduledJobList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScheduledJobList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ScheduledJob", "ScheduledJob", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ScheduledJobSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScheduledJobSpec{`, + `Schedule:` + fmt.Sprintf("%v", this.Schedule) + `,`, + `StartingDeadlineSeconds:` + valueToStringGenerated(this.StartingDeadlineSeconds) + `,`, + `ConcurrencyPolicy:` + fmt.Sprintf("%v", this.ConcurrencyPolicy) + `,`, + `Suspend:` + valueToStringGenerated(this.Suspend) + `,`, + `JobTemplate:` + strings.Replace(strings.Replace(this.JobTemplate.String(), "JobTemplateSpec", "JobTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ScheduledJobStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScheduledJobStatus{`, + `Active:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Active), "ObjectReference", "k8s_io_kubernetes_pkg_api_v1.ObjectReference", 1), `&`, ``, 1) + `,`, + `LastScheduleTime:` + strings.Replace(fmt.Sprintf("%v", this.LastScheduleTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *Job) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.proto index 5098f5166a98..95e371e2f7ab 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package k8s.io.kubernetes.pkg.apis.batch.v2alpha1; import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; +import "k8s.io/kubernetes/pkg/runtime/generated.proto"; import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; // Package-wide variables from generator "generated". @@ -32,15 +33,15 @@ option go_package = "v2alpha1"; // Job represents the configuration of a single job. message Job { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobSpec spec = 2; // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobStatus status = 3; } @@ -68,7 +69,7 @@ message JobCondition { // JobList is a collection of jobs. message JobList { // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of Job. @@ -81,7 +82,7 @@ message JobSpec { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 parallelism = 1; // Completions specifies the desired number of successfully finished pods the @@ -89,7 +90,7 @@ message JobSpec { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 completions = 2; // Optional duration in seconds relative to the startTime that the job may be active @@ -98,7 +99,7 @@ message JobSpec { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional LabelSelector selector = 4; // ManualSelector controls generation of pod labels and pod selectors. @@ -110,19 +111,19 @@ message JobSpec { // and other jobs to not function correctly. However, You may see // `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` // API. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md optional bool manualSelector = 5; // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 6; } // JobStatus represents the current state of a Job. message JobStatus { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md repeated JobCondition conditions = 1; // StartTime represents time when the job was acknowledged by the Job Manager. @@ -148,22 +149,22 @@ message JobStatus { // JobTemplate describes a template for creating copies of a predefined pod. message JobTemplate { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Template defines jobs that will be created from this template - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobTemplateSpec template = 2; } // JobTemplateSpec describes the data a Job should have when created from a template message JobTemplateSpec { // Standard object's metadata of the jobs created from this template. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Specification of the desired behavior of the job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobSpec spec = 2; } @@ -200,22 +201,22 @@ message LabelSelectorRequirement { // ScheduledJob represents the configuration of a single scheduled job. message ScheduledJob { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec is a structure defining the expected behavior of a job, including the schedule. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ScheduledJobSpec spec = 2; // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ScheduledJobStatus status = 3; } // ScheduledJobList is a collection of scheduled jobs. message ScheduledJobList { // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of ScheduledJob. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/register.go index 00142f018a72..54f0d6290a15 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.generated.go index 341d1d217a1d..bd48550ca778 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.go index 568f51712360..0402df2e8134 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,15 +25,15 @@ import ( type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -41,7 +41,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Job. @@ -52,22 +52,22 @@ type JobList struct { type JobTemplate struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Template defines jobs that will be created from this template - // http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Template JobTemplateSpec `json:"template,omitempty" protobuf:"bytes,2,opt,name=template"` } // JobTemplateSpec describes the data a Job should have when created from a template type JobTemplateSpec struct { // Standard object's metadata of the jobs created from this template. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` } @@ -78,7 +78,7 @@ type JobSpec struct { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Parallelism *int32 `json:"parallelism,omitempty" protobuf:"varint,1,opt,name=parallelism"` // Completions specifies the desired number of successfully finished pods the @@ -86,7 +86,7 @@ type JobSpec struct { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Completions *int32 `json:"completions,omitempty" protobuf:"varint,2,opt,name=completions"` // Optional duration in seconds relative to the startTime that the job may be active @@ -95,7 +95,7 @@ type JobSpec struct { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty" protobuf:"bytes,4,opt,name=selector"` // ManualSelector controls generation of pod labels and pod selectors. @@ -107,12 +107,12 @@ type JobSpec struct { // and other jobs to not function correctly. However, You may see // `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` // API. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md ManualSelector *bool `json:"manualSelector,omitempty" protobuf:"varint,5,opt,name=manualSelector"` // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,6,opt,name=template"` } @@ -120,7 +120,7 @@ type JobSpec struct { type JobStatus struct { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Conditions []JobCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // StartTime represents time when the job was acknowledged by the Job Manager. @@ -173,15 +173,15 @@ type JobCondition struct { type ScheduledJob struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is a structure defining the expected behavior of a job, including the schedule. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ScheduledJobSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ScheduledJobStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -189,7 +189,7 @@ type ScheduledJob struct { type ScheduledJobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of ScheduledJob. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types_swagger_doc_generated.go index 95b86d0de740..17d43318df1b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes 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 @@ package v2alpha1 // AUTO-GENERATED FUNCTIONS START HERE var map_Job = map[string]string{ "": "Job represents the configuration of a single job.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Job) SwaggerDoc() map[string]string { @@ -54,7 +54,7 @@ func (JobCondition) SwaggerDoc() map[string]string { var map_JobList = map[string]string{ "": "JobList is a collection of jobs.", - "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Job.", } @@ -64,12 +64,12 @@ func (JobList) SwaggerDoc() map[string]string { var map_JobSpec = map[string]string{ "": "JobSpec describes how the job execution will look like.", - "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", - "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", + "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "activeDeadlineSeconds": "Optional duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer", - "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "manualSelector": "ManualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md", - "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "manualSelector": "ManualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md", + "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", } func (JobSpec) SwaggerDoc() map[string]string { @@ -78,7 +78,7 @@ func (JobSpec) SwaggerDoc() map[string]string { var map_JobStatus = map[string]string{ "": "JobStatus represents the current state of a Job.", - "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "startTime": "StartTime represents time when the job was acknowledged by the Job Manager. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "completionTime": "CompletionTime represents time when the job was completed. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "active": "Active is the number of actively running pods.", @@ -92,8 +92,8 @@ func (JobStatus) SwaggerDoc() map[string]string { var map_JobTemplate = map[string]string{ "": "JobTemplate describes a template for creating copies of a predefined pod.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "template": "Template defines jobs that will be created from this template http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "template": "Template defines jobs that will be created from this template http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (JobTemplate) SwaggerDoc() map[string]string { @@ -102,8 +102,8 @@ func (JobTemplate) SwaggerDoc() map[string]string { var map_JobTemplateSpec = map[string]string{ "": "JobTemplateSpec describes the data a Job should have when created from a template", - "metadata": "Standard object's metadata of the jobs created from this template. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Specification of the desired behavior of the job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata of the jobs created from this template. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Specification of the desired behavior of the job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (JobTemplateSpec) SwaggerDoc() map[string]string { @@ -133,9 +133,9 @@ func (LabelSelectorRequirement) SwaggerDoc() map[string]string { var map_ScheduledJob = map[string]string{ "": "ScheduledJob represents the configuration of a single scheduled job.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec is a structure defining the expected behavior of a job, including the schedule. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec is a structure defining the expected behavior of a job, including the schedule. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (ScheduledJob) SwaggerDoc() map[string]string { @@ -144,7 +144,7 @@ func (ScheduledJob) SwaggerDoc() map[string]string { var map_ScheduledJobList = map[string]string{ "": "ScheduledJobList is a collection of scheduled jobs.", - "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of ScheduledJob.", } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.conversion.go index c411875e37f4..3265269bdfb9 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..a20352219c89 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/v2alpha1/zz_generated.deepcopy.go @@ -0,0 +1,351 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v2alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_Job, InType: reflect.TypeOf(func() *Job { var x *Job; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobCondition, InType: reflect.TypeOf(func() *JobCondition { var x *JobCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobList, InType: reflect.TypeOf(func() *JobList { var x *JobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobSpec, InType: reflect.TypeOf(func() *JobSpec { var x *JobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobStatus, InType: reflect.TypeOf(func() *JobStatus { var x *JobStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobTemplate, InType: reflect.TypeOf(func() *JobTemplate { var x *JobTemplate; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_JobTemplateSpec, InType: reflect.TypeOf(func() *JobTemplateSpec { var x *JobTemplateSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_LabelSelector, InType: reflect.TypeOf(func() *LabelSelector { var x *LabelSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_LabelSelectorRequirement, InType: reflect.TypeOf(func() *LabelSelectorRequirement { var x *LabelSelectorRequirement; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_ScheduledJob, InType: reflect.TypeOf(func() *ScheduledJob { var x *ScheduledJob; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_ScheduledJobList, InType: reflect.TypeOf(func() *ScheduledJobList { var x *ScheduledJobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_ScheduledJobSpec, InType: reflect.TypeOf(func() *ScheduledJobSpec { var x *ScheduledJobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v2alpha1_ScheduledJobStatus, InType: reflect.TypeOf(func() *ScheduledJobStatus { var x *ScheduledJobStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v2alpha1_Job(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Job) + out := out.(*Job) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_JobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_JobCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobCondition) + out := out.(*JobCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v2alpha1_JobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobList) + out := out.(*JobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Job, len(*in)) + for i := range *in { + if err := DeepCopy_v2alpha1_Job(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v2alpha1_JobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobSpec) + out := out.(*JobSpec) + if in.Parallelism != nil { + in, out := &in.Parallelism, &out.Parallelism + *out = new(int32) + **out = **in + } else { + out.Parallelism = nil + } + if in.Completions != nil { + in, out := &in.Completions, &out.Completions + *out = new(int32) + **out = **in + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v2alpha1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + in, out := &in.ManualSelector, &out.ManualSelector + *out = new(bool) + **out = **in + } else { + out.ManualSelector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_JobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobStatus) + out := out.(*JobStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]JobCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v2alpha1_JobCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.CompletionTime = nil + } + out.Active = in.Active + out.Succeeded = in.Succeeded + out.Failed = in.Failed + return nil + } +} + +func DeepCopy_v2alpha1_JobTemplate(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobTemplate) + out := out.(*JobTemplate) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_JobTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_JobTemplateSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobTemplateSpec) + out := out.(*JobTemplateSpec) + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_LabelSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelector) + out := out.(*LabelSelector) + if in.MatchLabels != nil { + in, out := &in.MatchLabels, &out.MatchLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]LabelSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_v2alpha1_LabelSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_v2alpha1_LabelSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelectorRequirement) + out := out.(*LabelSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} + +func DeepCopy_v2alpha1_ScheduledJob(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJob) + out := out.(*ScheduledJob) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_ScheduledJobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v2alpha1_ScheduledJobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_ScheduledJobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobList) + out := out.(*ScheduledJobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ScheduledJob, len(*in)) + for i := range *in { + if err := DeepCopy_v2alpha1_ScheduledJob(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v2alpha1_ScheduledJobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobSpec) + out := out.(*ScheduledJobSpec) + out.Schedule = in.Schedule + if in.StartingDeadlineSeconds != nil { + in, out := &in.StartingDeadlineSeconds, &out.StartingDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.StartingDeadlineSeconds = nil + } + out.ConcurrencyPolicy = in.ConcurrencyPolicy + if in.Suspend != nil { + in, out := &in.Suspend, &out.Suspend + *out = new(bool) + **out = **in + } else { + out.Suspend = nil + } + if err := DeepCopy_v2alpha1_JobTemplateSpec(&in.JobTemplate, &out.JobTemplate, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v2alpha1_ScheduledJobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobStatus) + out := out.(*ScheduledJobStatus) + if in.Active != nil { + in, out := &in.Active, &out.Active + *out = make([]v1.ObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Active = nil + } + if in.LastScheduleTime != nil { + in, out := &in.LastScheduleTime, &out.LastScheduleTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.LastScheduleTime = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/validation/validation.go index e592ca18dcaa..7139ac75f211 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/batch/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/batch/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/batch/zz_generated.deepcopy.go new file mode 100644 index 000000000000..9ef37952dcf0 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/batch/zz_generated.deepcopy.go @@ -0,0 +1,303 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package batch + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_Job, InType: reflect.TypeOf(func() *Job { var x *Job; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobCondition, InType: reflect.TypeOf(func() *JobCondition { var x *JobCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobList, InType: reflect.TypeOf(func() *JobList { var x *JobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobSpec, InType: reflect.TypeOf(func() *JobSpec { var x *JobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobStatus, InType: reflect.TypeOf(func() *JobStatus { var x *JobStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobTemplate, InType: reflect.TypeOf(func() *JobTemplate { var x *JobTemplate; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_JobTemplateSpec, InType: reflect.TypeOf(func() *JobTemplateSpec { var x *JobTemplateSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_ScheduledJob, InType: reflect.TypeOf(func() *ScheduledJob { var x *ScheduledJob; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_ScheduledJobList, InType: reflect.TypeOf(func() *ScheduledJobList { var x *ScheduledJobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_ScheduledJobSpec, InType: reflect.TypeOf(func() *ScheduledJobSpec { var x *ScheduledJobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_batch_ScheduledJobStatus, InType: reflect.TypeOf(func() *ScheduledJobStatus { var x *ScheduledJobStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_batch_Job(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Job) + out := out.(*Job) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_batch_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_batch_JobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_JobCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobCondition) + out := out.(*JobCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_batch_JobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobList) + out := out.(*JobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Job, len(*in)) + for i := range *in { + if err := DeepCopy_batch_Job(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_batch_JobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobSpec) + out := out.(*JobSpec) + if in.Parallelism != nil { + in, out := &in.Parallelism, &out.Parallelism + *out = new(int32) + **out = **in + } else { + out.Parallelism = nil + } + if in.Completions != nil { + in, out := &in.Completions, &out.Completions + *out = new(int32) + **out = **in + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.ManualSelector != nil { + in, out := &in.ManualSelector, &out.ManualSelector + *out = new(bool) + **out = **in + } else { + out.ManualSelector = nil + } + if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_JobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobStatus) + out := out.(*JobStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]JobCondition, len(*in)) + for i := range *in { + if err := DeepCopy_batch_JobCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.CompletionTime = nil + } + out.Active = in.Active + out.Succeeded = in.Succeeded + out.Failed = in.Failed + return nil + } +} + +func DeepCopy_batch_JobTemplate(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobTemplate) + out := out.(*JobTemplate) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_batch_JobTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_JobTemplateSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobTemplateSpec) + out := out.(*JobTemplateSpec) + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_batch_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_ScheduledJob(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJob) + out := out.(*ScheduledJob) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_batch_ScheduledJobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_batch_ScheduledJobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_ScheduledJobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobList) + out := out.(*ScheduledJobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ScheduledJob, len(*in)) + for i := range *in { + if err := DeepCopy_batch_ScheduledJob(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_batch_ScheduledJobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobSpec) + out := out.(*ScheduledJobSpec) + out.Schedule = in.Schedule + if in.StartingDeadlineSeconds != nil { + in, out := &in.StartingDeadlineSeconds, &out.StartingDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.StartingDeadlineSeconds = nil + } + out.ConcurrencyPolicy = in.ConcurrencyPolicy + if in.Suspend != nil { + in, out := &in.Suspend, &out.Suspend + *out = new(bool) + **out = **in + } else { + out.Suspend = nil + } + if err := DeepCopy_batch_JobTemplateSpec(&in.JobTemplate, &out.JobTemplate, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_batch_ScheduledJobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScheduledJobStatus) + out := out.(*ScheduledJobStatus) + if in.Active != nil { + in, out := &in.Active, &out.Active + *out = make([]api.ObjectReference, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Active = nil + } + if in.LastScheduleTime != nil { + in, out := &in.LastScheduleTime, &out.LastScheduleTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.LastScheduleTime = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/doc.go new file mode 100644 index 000000000000..d2897cb87d7c --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package certificates diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/install/install.go new file mode 100644 index 000000000000..cf54da430e5f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/install/install.go @@ -0,0 +1,131 @@ +/* +Copyright 2016 The Kubernetes 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 install installs the certificates API group, making it available as +// an option to all of the API encoding/decoding machinery. +package install + +import ( + "fmt" + + "github.com/golang/glog" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/meta" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apimachinery" + "k8s.io/kubernetes/pkg/apimachinery/registered" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/sets" +) + +const importPrefix = "k8s.io/kubernetes/pkg/apis/certificates" + +var accessor = meta.NewAccessor() + +// availableVersions lists all known external versions for this group from most preferred to least preferred +var availableVersions = []unversioned.GroupVersion{v1alpha1.SchemeGroupVersion} + +func init() { + registered.RegisterVersions(availableVersions) + externalVersions := []unversioned.GroupVersion{} + for _, v := range availableVersions { + if registered.IsAllowedVersion(v) { + externalVersions = append(externalVersions, v) + } + } + if len(externalVersions) == 0 { + glog.V(4).Infof("No version is registered for group %v", certificates.GroupName) + return + } + + if err := registered.EnableVersions(externalVersions...); err != nil { + glog.V(4).Infof("%v", err) + return + } + if err := enableVersions(externalVersions); err != nil { + glog.V(4).Infof("%v", err) + return + } +} + +// TODO: enableVersions should be centralized rather than spread in each API +// group. +// We can combine registered.RegisterVersions, registered.EnableVersions and +// registered.RegisterGroup once we have moved enableVersions therecertificates +func enableVersions(externalVersions []unversioned.GroupVersion) error { + addVersionsToScheme(externalVersions...) + preferredExternalVersion := externalVersions[0] + + groupMeta := apimachinery.GroupMeta{ + GroupVersion: preferredExternalVersion, + GroupVersions: externalVersions, + RESTMapper: newRESTMapper(externalVersions), + SelfLinker: runtime.SelfLinker(accessor), + InterfacesFor: interfacesFor, + } + + if err := registered.RegisterGroup(groupMeta); err != nil { + return err + } + api.RegisterRESTMapper(groupMeta.RESTMapper) + return nil +} + +func newRESTMapper(externalVersions []unversioned.GroupVersion) meta.RESTMapper { + // the list of kinds that are scoped at the root of the api hierarchy + // if a kind is not enumerated here, it is assumed to have a namespace scope + rootScoped := sets.NewString( + "CertificateSigningRequest", + ) + + ignoredKinds := sets.NewString() + + return api.NewDefaultRESTMapper(externalVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped) +} + +// interfacesFor returns the default Codec and ResourceVersioner for a given version +// string, or an error if the version is not known. +func interfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) { + switch version { + case v1alpha1.SchemeGroupVersion: + return &meta.VersionInterfaces{ + ObjectConvertor: api.Scheme, + MetadataAccessor: accessor, + }, nil + default: + g, _ := registered.Group(certificates.GroupName) + return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, g.GroupVersions) + } +} + +func addVersionsToScheme(externalVersions ...unversioned.GroupVersion) { + // add the internal version to Scheme + certificates.AddToScheme(api.Scheme) + // add the enabled external versions to Scheme + for _, v := range externalVersions { + if !registered.IsEnabledVersion(v) { + glog.Errorf("Version %s is not enabled, so it will not be added to the Scheme.", v) + continue + } + switch v { + case v1alpha1.SchemeGroupVersion: + v1alpha1.AddToScheme(api.Scheme) + } + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/register.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/register.go new file mode 100644 index 000000000000..d232b3c86176 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/register.go @@ -0,0 +1,57 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/runtime" +) + +// GroupName is the group name use in this package +const GroupName = "certificates" + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: runtime.APIVersionInternal} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) unversioned.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns back a Group qualified GroupResource +func Resource(resource string) unversioned.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +func AddToScheme(scheme *runtime.Scheme) { + // Add the API to Scheme. + addKnownTypes(scheme) +} + +// Adds the list of known types to api.Scheme. +func addKnownTypes(scheme *runtime.Scheme) { + scheme.AddKnownTypes(SchemeGroupVersion, + &CertificateSigningRequest{}, + &CertificateSigningRequestList{}, + &api.ListOptions{}, + &api.DeleteOptions{}, + ) +} + +func (obj *CertificateSigningRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *CertificateSigningRequestList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.generated.go new file mode 100644 index 000000000000..21798df3c337 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.generated.go @@ -0,0 +1,1963 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package certificates + +import ( + "errors" + "fmt" + codec1978 "github.com/ugorji/go/codec" + pkg2_api "k8s.io/kubernetes/pkg/api" + pkg1_unversioned "k8s.io/kubernetes/pkg/api/unversioned" + pkg3_types "k8s.io/kubernetes/pkg/types" + "reflect" + "runtime" + time "time" +) + +const ( + // ----- content types ---- + codecSelferC_UTF81234 = 1 + codecSelferC_RAW1234 = 0 + // ----- value types used ---- + codecSelferValueTypeArray1234 = 10 + codecSelferValueTypeMap1234 = 9 + // ----- containerStateValues ---- + codecSelfer_containerMapKey1234 = 2 + codecSelfer_containerMapValue1234 = 3 + codecSelfer_containerMapEnd1234 = 4 + codecSelfer_containerArrayElem1234 = 6 + codecSelfer_containerArrayEnd1234 = 7 +) + +var ( + codecSelferBitsize1234 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr1234 = errors.New(`only encoded map or array can be decoded into a struct`) +) + +type codecSelfer1234 struct{} + +func init() { + if codec1978.GenVersion != 5 { + _, file, _, _ := runtime.Caller(0) + err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", + 5, codec1978.GenVersion, file) + panic(err) + } + if false { // reference the types, but skip this branch at build/run time + var v0 pkg2_api.ObjectMeta + var v1 pkg1_unversioned.TypeMeta + var v2 pkg3_types.UID + var v3 time.Time + _, _, _, _ = v0, v1, v2, v3 + } +} + +func (x *CertificateSigningRequest) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [5]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[1] = true + yyq2[2] = true + yyq2[3] = x.Kind != "" + yyq2[4] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(5) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ObjectMeta + yy4.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ObjectMeta + yy6.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yy9 := &x.Spec + yy9.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("spec")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy11 := &x.Spec + yy11.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yy14 := &x.Status + yy14.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("status")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy16 := &x.Status + yy16.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequest) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequest) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_api.ObjectMeta{} + } else { + yyv4 := &x.ObjectMeta + yyv4.CodecDecodeSelf(d) + } + case "spec": + if r.TryDecodeAsNil() { + x.Spec = CertificateSigningRequestSpec{} + } else { + yyv5 := &x.Spec + yyv5.CodecDecodeSelf(d) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = CertificateSigningRequestStatus{} + } else { + yyv6 := &x.Status + yyv6.CodecDecodeSelf(d) + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequest) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_api.ObjectMeta{} + } else { + yyv10 := &x.ObjectMeta + yyv10.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Spec = CertificateSigningRequestSpec{} + } else { + yyv11 := &x.Spec + yyv11.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Status = CertificateSigningRequestStatus{} + } else { + yyv12 := &x.Status + yyv12.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestSpec) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = x.Username != "" + yyq2[2] = x.UID != "" + yyq2[3] = len(x.Groups) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.Request == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Request)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("request")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Request == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Request)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Username)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("username")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Username)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.UID)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("uid")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.UID)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + if x.Groups == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + z.F.EncSliceStringV(x.Groups, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("groups")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Groups == nil { + r.EncodeNil() + } else { + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + z.F.EncSliceStringV(x.Groups, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestSpec) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "request": + if r.TryDecodeAsNil() { + x.Request = nil + } else { + yyv4 := &x.Request + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *yyv4 = r.DecodeBytes(*(*[]byte)(yyv4), false, false) + } + } + case "username": + if r.TryDecodeAsNil() { + x.Username = "" + } else { + x.Username = string(r.DecodeString()) + } + case "uid": + if r.TryDecodeAsNil() { + x.UID = "" + } else { + x.UID = string(r.DecodeString()) + } + case "groups": + if r.TryDecodeAsNil() { + x.Groups = nil + } else { + yyv8 := &x.Groups + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + z.F.DecSliceStringX(yyv8, false, d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Request = nil + } else { + yyv11 := &x.Request + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *yyv11 = r.DecodeBytes(*(*[]byte)(yyv11), false, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Username = "" + } else { + x.Username = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.UID = "" + } else { + x.UID = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Groups = nil + } else { + yyv15 := &x.Groups + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + z.F.DecSliceStringX(yyv15, false, d) + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestStatus) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = len(x.Conditions) != 0 + yyq2[1] = len(x.Certificate) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.Conditions == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceCertificateSigningRequestCondition(([]CertificateSigningRequestCondition)(x.Conditions), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("conditions")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Conditions == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceCertificateSigningRequestCondition(([]CertificateSigningRequestCondition)(x.Conditions), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Certificate == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Certificate)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("certificate")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Certificate == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Certificate)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestStatus) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "conditions": + if r.TryDecodeAsNil() { + x.Conditions = nil + } else { + yyv4 := &x.Conditions + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceCertificateSigningRequestCondition((*[]CertificateSigningRequestCondition)(yyv4), d) + } + } + case "certificate": + if r.TryDecodeAsNil() { + x.Certificate = nil + } else { + yyv6 := &x.Certificate + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *yyv6 = r.DecodeBytes(*(*[]byte)(yyv6), false, false) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Conditions = nil + } else { + yyv9 := &x.Conditions + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceCertificateSigningRequestCondition((*[]CertificateSigningRequestCondition)(yyv9), d) + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Certificate = nil + } else { + yyv11 := &x.Certificate + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *yyv11 = r.DecodeBytes(*(*[]byte)(yyv11), false, false) + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x RequestConditionType) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x)) + } +} + +func (x *RequestConditionType) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + *((*string)(x)) = r.DecodeString() + } +} + +func (x *CertificateSigningRequestCondition) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = x.Reason != "" + yyq2[2] = x.Message != "" + yyq2[3] = true + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + x.Type.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("type")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + x.Type.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("reason")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("message")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yy13 := &x.LastUpdateTime + yym14 := z.EncBinary() + _ = yym14 + if false { + } else if z.HasExtensions() && z.EncExt(yy13) { + } else if yym14 { + z.EncBinaryMarshal(yy13) + } else if !yym14 && z.IsJSONHandle() { + z.EncJSONMarshal(yy13) + } else { + z.EncFallback(yy13) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lastUpdateTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy15 := &x.LastUpdateTime + yym16 := z.EncBinary() + _ = yym16 + if false { + } else if z.HasExtensions() && z.EncExt(yy15) { + } else if yym16 { + z.EncBinaryMarshal(yy15) + } else if !yym16 && z.IsJSONHandle() { + z.EncJSONMarshal(yy15) + } else { + z.EncFallback(yy15) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestCondition) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestCondition) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "type": + if r.TryDecodeAsNil() { + x.Type = "" + } else { + x.Type = RequestConditionType(r.DecodeString()) + } + case "reason": + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + case "message": + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + case "lastUpdateTime": + if r.TryDecodeAsNil() { + x.LastUpdateTime = pkg1_unversioned.Time{} + } else { + yyv7 := &x.LastUpdateTime + yym8 := z.DecBinary() + _ = yym8 + if false { + } else if z.HasExtensions() && z.DecExt(yyv7) { + } else if yym8 { + z.DecBinaryUnmarshal(yyv7) + } else if !yym8 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv7) + } else { + z.DecFallback(yyv7, false) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestCondition) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Type = "" + } else { + x.Type = RequestConditionType(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LastUpdateTime = pkg1_unversioned.Time{} + } else { + yyv13 := &x.LastUpdateTime + yym14 := z.DecBinary() + _ = yym14 + if false { + } else if z.HasExtensions() && z.DecExt(yyv13) { + } else if yym14 { + z.DecBinaryUnmarshal(yyv13) + } else if !yym14 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv13) + } else { + z.DecFallback(yyv13, false) + } + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestList) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[1] = len(x.Items) != 0 + yyq2[2] = x.Kind != "" + yyq2[3] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ListMeta + yym5 := z.EncBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.EncExt(yy4) { + } else { + z.EncFallback(yy4) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ListMeta + yym7 := z.EncBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.EncExt(yy6) { + } else { + z.EncFallback(yy6) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Items == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceCertificateSigningRequest(([]CertificateSigningRequest)(x.Items), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("items")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceCertificateSigningRequest(([]CertificateSigningRequest)(x.Items), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestList) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv4 := &x.ListMeta + yym5 := z.DecBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.DecExt(yyv4) { + } else { + z.DecFallback(yyv4, false) + } + } + case "items": + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv6 := &x.Items + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSliceCertificateSigningRequest((*[]CertificateSigningRequest)(yyv6), d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv11 := &x.ListMeta + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else { + z.DecFallback(yyv11, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv13 := &x.Items + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSliceCertificateSigningRequest((*[]CertificateSigningRequest)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) encSliceCertificateSigningRequestCondition(v []CertificateSigningRequestCondition, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceCertificateSigningRequestCondition(v *[]CertificateSigningRequestCondition, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []CertificateSigningRequestCondition{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 72) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]CertificateSigningRequestCondition, yyrl1) + } + } else { + yyv1 = make([]CertificateSigningRequestCondition, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, CertificateSigningRequestCondition{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, CertificateSigningRequestCondition{}) // var yyz1 CertificateSigningRequestCondition + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []CertificateSigningRequestCondition{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer1234) encSliceCertificateSigningRequest(v []CertificateSigningRequest, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceCertificateSigningRequest(v *[]CertificateSigningRequest, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []CertificateSigningRequest{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 368) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]CertificateSigningRequest, yyrl1) + } + } else { + yyv1 = make([]CertificateSigningRequest, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, CertificateSigningRequest{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, CertificateSigningRequest{}) // var yyz1 CertificateSigningRequest + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []CertificateSigningRequest{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.go new file mode 100644 index 000000000000..c0eb47b1f06f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/types.go @@ -0,0 +1,85 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" +) + +// +genclient=true +// +nonNamespaced=true + +// Describes a certificate signing request +type CertificateSigningRequest struct { + unversioned.TypeMeta `json:",inline"` + api.ObjectMeta `json:"metadata,omitempty"` + + // The certificate request itself and any additonal information. + Spec CertificateSigningRequestSpec `json:"spec,omitempty"` + + // Derived information about the request. + Status CertificateSigningRequestStatus `json:"status,omitempty"` +} + +// This information is immutable after the request is created. Only the Request +// and ExtraInfo fields can be set on creation, other fields are derived by +// Kubernetes and cannot be modified by users. +type CertificateSigningRequestSpec struct { + // Base64-encoded PKCS#10 CSR data + Request []byte `json:"request"` + + // Information about the requesting user (if relevant) + // See user.Info interface for details + Username string `json:"username,omitempty"` + UID string `json:"uid,omitempty"` + Groups []string `json:"groups,omitempty"` +} + +type CertificateSigningRequestStatus struct { + // Conditions applied to the request, such as approval or denial. + Conditions []CertificateSigningRequestCondition `json:"conditions,omitempty"` + + // If request was approved, the controller will place the issued certificate here. + Certificate []byte `json:"certificate,omitempty"` +} + +type RequestConditionType string + +// These are the possible conditions for a certificate request. +const ( + CertificateApproved RequestConditionType = "Approved" + CertificateDenied RequestConditionType = "Denied" +) + +type CertificateSigningRequestCondition struct { + // request approval state, currently Approved or Denied. + Type RequestConditionType `json:"type"` + // brief reason for the request state + Reason string `json:"reason,omitempty"` + // human readable message with details about the request state + Message string `json:"message,omitempty"` + // timestamp for the last update to this condition + LastUpdateTime unversioned.Time `json:"lastUpdateTime,omitempty"` +} + +type CertificateSigningRequestList struct { + unversioned.TypeMeta `json:",inline"` + unversioned.ListMeta `json:"metadata,omitempty"` + + Items []CertificateSigningRequest `json:"items,omitempty"` +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/conversion.go new file mode 100644 index 000000000000..0b933b25990a --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/conversion.go @@ -0,0 +1,23 @@ +/* +Copyright 2016 The Kubernetes 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 v1alpha1 + +import "k8s.io/kubernetes/pkg/runtime" + +func addConversionFuncs(scheme *runtime.Scheme) { + // Add non-generated conversion functions here. Currently there are none. +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/doc.go new file mode 100644 index 000000000000..3528c164f9aa --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/certificates + +package v1alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.pb.go new file mode 100644 index 000000000000..6740dc3a6507 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.pb.go @@ -0,0 +1,1258 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// Code generated by protoc-gen-gogo. +// source: k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.proto +// DO NOT EDIT! + +/* + Package v1alpha1 is a generated protocol buffer package. + + It is generated from these files: + k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.proto + + It has these top-level messages: + CertificateSigningRequest + CertificateSigningRequestCondition + CertificateSigningRequestList + CertificateSigningRequestSpec + CertificateSigningRequestStatus +*/ +package v1alpha1 + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +import strings "strings" +import reflect "reflect" + +import io "io" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +func (m *CertificateSigningRequest) Reset() { *m = CertificateSigningRequest{} } +func (*CertificateSigningRequest) ProtoMessage() {} + +func (m *CertificateSigningRequestCondition) Reset() { *m = CertificateSigningRequestCondition{} } +func (*CertificateSigningRequestCondition) ProtoMessage() {} + +func (m *CertificateSigningRequestList) Reset() { *m = CertificateSigningRequestList{} } +func (*CertificateSigningRequestList) ProtoMessage() {} + +func (m *CertificateSigningRequestSpec) Reset() { *m = CertificateSigningRequestSpec{} } +func (*CertificateSigningRequestSpec) ProtoMessage() {} + +func (m *CertificateSigningRequestStatus) Reset() { *m = CertificateSigningRequestStatus{} } +func (*CertificateSigningRequestStatus) ProtoMessage() {} + +func init() { + proto.RegisterType((*CertificateSigningRequest)(nil), "k8s.io.kubernetes.pkg.apis.certificates.v1alpha1.CertificateSigningRequest") + proto.RegisterType((*CertificateSigningRequestCondition)(nil), "k8s.io.kubernetes.pkg.apis.certificates.v1alpha1.CertificateSigningRequestCondition") + proto.RegisterType((*CertificateSigningRequestList)(nil), "k8s.io.kubernetes.pkg.apis.certificates.v1alpha1.CertificateSigningRequestList") + proto.RegisterType((*CertificateSigningRequestSpec)(nil), "k8s.io.kubernetes.pkg.apis.certificates.v1alpha1.CertificateSigningRequestSpec") + proto.RegisterType((*CertificateSigningRequestStatus)(nil), "k8s.io.kubernetes.pkg.apis.certificates.v1alpha1.CertificateSigningRequestStatus") +} +func (m *CertificateSigningRequest) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *CertificateSigningRequest) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) + n1, err := m.ObjectMeta.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n1 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(m.Spec.Size())) + n2, err := m.Spec.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n2 + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(m.Status.Size())) + n3, err := m.Status.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n3 + return i, nil +} + +func (m *CertificateSigningRequestCondition) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *CertificateSigningRequestCondition) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Type))) + i += copy(data[i:], m.Type) + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Reason))) + i += copy(data[i:], m.Reason) + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Message))) + i += copy(data[i:], m.Message) + data[i] = 0x22 + i++ + i = encodeVarintGenerated(data, i, uint64(m.LastUpdateTime.Size())) + n4, err := m.LastUpdateTime.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n4 + return i, nil +} + +func (m *CertificateSigningRequestList) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *CertificateSigningRequestList) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) + n5, err := m.ListMeta.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n5 + if len(m.Items) > 0 { + for _, msg := range m.Items { + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(msg.Size())) + n, err := msg.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + +func (m *CertificateSigningRequestSpec) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *CertificateSigningRequestSpec) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if m.Request != nil { + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Request))) + i += copy(data[i:], m.Request) + } + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Username))) + i += copy(data[i:], m.Username) + data[i] = 0x1a + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.UID))) + i += copy(data[i:], m.UID) + if len(m.Groups) > 0 { + for _, s := range m.Groups { + data[i] = 0x22 + i++ + l = len(s) + for l >= 1<<7 { + data[i] = uint8(uint64(l)&0x7f | 0x80) + l >>= 7 + i++ + } + data[i] = uint8(l) + i++ + i += copy(data[i:], s) + } + } + return i, nil +} + +func (m *CertificateSigningRequestStatus) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *CertificateSigningRequestStatus) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + if len(m.Conditions) > 0 { + for _, msg := range m.Conditions { + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(msg.Size())) + n, err := msg.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n + } + } + if m.Certificate != nil { + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Certificate))) + i += copy(data[i:], m.Certificate) + } + return i, nil +} + +func encodeFixed64Generated(data []byte, offset int, v uint64) int { + data[offset] = uint8(v) + data[offset+1] = uint8(v >> 8) + data[offset+2] = uint8(v >> 16) + data[offset+3] = uint8(v >> 24) + data[offset+4] = uint8(v >> 32) + data[offset+5] = uint8(v >> 40) + data[offset+6] = uint8(v >> 48) + data[offset+7] = uint8(v >> 56) + return offset + 8 +} +func encodeFixed32Generated(data []byte, offset int, v uint32) int { + data[offset] = uint8(v) + data[offset+1] = uint8(v >> 8) + data[offset+2] = uint8(v >> 16) + data[offset+3] = uint8(v >> 24) + return offset + 4 +} +func encodeVarintGenerated(data []byte, offset int, v uint64) int { + for v >= 1<<7 { + data[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + data[offset] = uint8(v) + return offset + 1 +} +func (m *CertificateSigningRequest) Size() (n int) { + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Spec.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = m.Status.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *CertificateSigningRequestCondition) Size() (n int) { + var l int + _ = l + l = len(m.Type) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Reason) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Message) + n += 1 + l + sovGenerated(uint64(l)) + l = m.LastUpdateTime.Size() + n += 1 + l + sovGenerated(uint64(l)) + return n +} + +func (m *CertificateSigningRequestList) Size() (n int) { + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CertificateSigningRequestSpec) Size() (n int) { + var l int + _ = l + if m.Request != nil { + l = len(m.Request) + n += 1 + l + sovGenerated(uint64(l)) + } + l = len(m.Username) + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.UID) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Groups) > 0 { + for _, s := range m.Groups { + l = len(s) + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + +func (m *CertificateSigningRequestStatus) Size() (n int) { + var l int + _ = l + if len(m.Conditions) > 0 { + for _, e := range m.Conditions { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + if m.Certificate != nil { + l = len(m.Certificate) + n += 1 + l + sovGenerated(uint64(l)) + } + return n +} + +func sovGenerated(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} +func sozGenerated(x uint64) (n int) { + return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (this *CertificateSigningRequest) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequest{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "CertificateSigningRequestSpec", "CertificateSigningRequestSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "CertificateSigningRequestStatus", "CertificateSigningRequestStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequestCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `LastUpdateTime:` + strings.Replace(strings.Replace(this.LastUpdateTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequestList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "CertificateSigningRequest", "CertificateSigningRequest", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequestSpec{`, + `Request:` + valueToStringGenerated(this.Request) + `,`, + `Username:` + fmt.Sprintf("%v", this.Username) + `,`, + `UID:` + fmt.Sprintf("%v", this.UID) + `,`, + `Groups:` + fmt.Sprintf("%v", this.Groups) + `,`, + `}`, + }, "") + return s +} +func (this *CertificateSigningRequestStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CertificateSigningRequestStatus{`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "CertificateSigningRequestCondition", "CertificateSigningRequestCondition", 1), `&`, ``, 1) + `,`, + `Certificate:` + valueToStringGenerated(this.Certificate) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} +func (m *CertificateSigningRequest) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Spec.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Status.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestCondition) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestCondition: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestCondition: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Type = RequestConditionType(data[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Reason = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Message = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field LastUpdateTime", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.LastUpdateTime.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestList) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, CertificateSigningRequest{}) + if err := m.Items[len(m.Items)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestSpec) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestSpec: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestSpec: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Request = append(m.Request[:0], data[iNdEx:postIndex]...) + if m.Request == nil { + m.Request = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Username", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Username = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.UID = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Groups", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Groups = append(m.Groups, string(data[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CertificateSigningRequestStatus) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CertificateSigningRequestStatus: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CertificateSigningRequestStatus: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Conditions", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Conditions = append(m.Conditions, CertificateSigningRequestCondition{}) + if err := m.Conditions[len(m.Conditions)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + byteLen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + byteLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Certificate = append(m.Certificate[:0], data[iNdEx:postIndex]...) + if m.Certificate == nil { + m.Certificate = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenerated(data []byte) (n int, err error) { + l := len(data) + iNdEx := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if data[iNdEx-1] < 0x80 { + break + } + } + return iNdEx, nil + case 1: + iNdEx += 8 + return iNdEx, nil + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + iNdEx += length + if length < 0 { + return 0, ErrInvalidLengthGenerated + } + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenerated + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipGenerated(data[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + } + return iNdEx, nil + case 4: + return iNdEx, nil + case 5: + iNdEx += 4 + return iNdEx, nil + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + } + panic("unreachable") +} + +var ( + ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") +) diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.proto new file mode 100644 index 000000000000..5e8250b13900 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/generated.proto @@ -0,0 +1,87 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + + +// This file was autogenerated by go-to-protobuf. Do not edit it manually! + +syntax = 'proto2'; + +package k8s.io.kubernetes.pkg.apis.certificates.v1alpha1; + +import "k8s.io/kubernetes/pkg/api/resource/generated.proto"; +import "k8s.io/kubernetes/pkg/api/unversioned/generated.proto"; +import "k8s.io/kubernetes/pkg/api/v1/generated.proto"; +import "k8s.io/kubernetes/pkg/runtime/generated.proto"; +import "k8s.io/kubernetes/pkg/util/intstr/generated.proto"; + +// Package-wide variables from generator "generated". +option go_package = "v1alpha1"; + +// Describes a certificate signing request +message CertificateSigningRequest { + optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; + + // The certificate request itself and any additonal information. + optional CertificateSigningRequestSpec spec = 2; + + // Derived information about the request. + optional CertificateSigningRequestStatus status = 3; +} + +message CertificateSigningRequestCondition { + // request approval state, currently Approved or Denied. + optional string type = 1; + + // brief reason for the request state + optional string reason = 2; + + // human readable message with details about the request state + optional string message = 3; + + // timestamp for the last update to this condition + optional k8s.io.kubernetes.pkg.api.unversioned.Time lastUpdateTime = 4; +} + +message CertificateSigningRequestList { + optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; + + repeated CertificateSigningRequest items = 2; +} + +// This information is immutable after the request is created. Only the Request +// and ExtraInfo fields can be set on creation, other fields are derived by +// Kubernetes and cannot be modified by users. +message CertificateSigningRequestSpec { + // Base64-encoded PKCS#10 CSR data + optional bytes request = 1; + + // Information about the requesting user (if relevant) + // See user.Info interface for details + optional string username = 2; + + optional string uid = 3; + + repeated string groups = 4; +} + +message CertificateSigningRequestStatus { + // Conditions applied to the request, such as approval or denial. + repeated CertificateSigningRequestCondition conditions = 1; + + // If request was approved, the controller will place the issued certificate here. + optional bytes certificate = 2; +} + diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/register.go new file mode 100644 index 000000000000..7b841c0b5485 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/register.go @@ -0,0 +1,62 @@ +/* +Copyright 2016 The Kubernetes 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 v1alpha1 + +import ( + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" + "k8s.io/kubernetes/pkg/runtime" + versionedwatch "k8s.io/kubernetes/pkg/watch/versioned" +) + +// GroupName is the group name use in this package +const GroupName = "certificates" + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: "v1alpha1"} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) unversioned.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns back a Group qualified GroupResource +func Resource(resource string) unversioned.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +func AddToScheme(scheme *runtime.Scheme) { + addKnownTypes(scheme) + // addDefaultingFuncs(scheme) + addConversionFuncs(scheme) +} + +// Adds the list of known types to api.Scheme. +func addKnownTypes(scheme *runtime.Scheme) { + scheme.AddKnownTypes(SchemeGroupVersion, + &CertificateSigningRequest{}, + &CertificateSigningRequestList{}, + &v1.ListOptions{}, + &v1.DeleteOptions{}, + ) + + // Add the watch version that applies + versionedwatch.AddToGroupVersion(scheme, SchemeGroupVersion) +} + +func (obj *CertificateSigningRequest) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *CertificateSigningRequestList) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.generated.go new file mode 100644 index 000000000000..3efa7c6fce53 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.generated.go @@ -0,0 +1,1956 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package v1alpha1 + +import ( + "errors" + "fmt" + codec1978 "github.com/ugorji/go/codec" + pkg1_unversioned "k8s.io/kubernetes/pkg/api/unversioned" + pkg2_v1 "k8s.io/kubernetes/pkg/api/v1" + pkg3_types "k8s.io/kubernetes/pkg/types" + "reflect" + "runtime" + time "time" +) + +const ( + // ----- content types ---- + codecSelferC_UTF81234 = 1 + codecSelferC_RAW1234 = 0 + // ----- value types used ---- + codecSelferValueTypeArray1234 = 10 + codecSelferValueTypeMap1234 = 9 + // ----- containerStateValues ---- + codecSelfer_containerMapKey1234 = 2 + codecSelfer_containerMapValue1234 = 3 + codecSelfer_containerMapEnd1234 = 4 + codecSelfer_containerArrayElem1234 = 6 + codecSelfer_containerArrayEnd1234 = 7 +) + +var ( + codecSelferBitsize1234 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr1234 = errors.New(`only encoded map or array can be decoded into a struct`) +) + +type codecSelfer1234 struct{} + +func init() { + if codec1978.GenVersion != 5 { + _, file, _, _ := runtime.Caller(0) + err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", + 5, codec1978.GenVersion, file) + panic(err) + } + if false { // reference the types, but skip this branch at build/run time + var v0 pkg1_unversioned.TypeMeta + var v1 pkg2_v1.ObjectMeta + var v2 pkg3_types.UID + var v3 time.Time + _, _, _, _ = v0, v1, v2, v3 + } +} + +func (x *CertificateSigningRequest) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [5]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[1] = true + yyq2[2] = true + yyq2[3] = x.Kind != "" + yyq2[4] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(5) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ObjectMeta + yy4.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ObjectMeta + yy6.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yy9 := &x.Spec + yy9.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("spec")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy11 := &x.Spec + yy11.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yy14 := &x.Status + yy14.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("status")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy16 := &x.Status + yy16.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym20 := z.EncBinary() + _ = yym20 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym22 := z.EncBinary() + _ = yym22 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym23 := z.EncBinary() + _ = yym23 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequest) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequest) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_v1.ObjectMeta{} + } else { + yyv4 := &x.ObjectMeta + yyv4.CodecDecodeSelf(d) + } + case "spec": + if r.TryDecodeAsNil() { + x.Spec = CertificateSigningRequestSpec{} + } else { + yyv5 := &x.Spec + yyv5.CodecDecodeSelf(d) + } + case "status": + if r.TryDecodeAsNil() { + x.Status = CertificateSigningRequestStatus{} + } else { + yyv6 := &x.Status + yyv6.CodecDecodeSelf(d) + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequest) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_v1.ObjectMeta{} + } else { + yyv10 := &x.ObjectMeta + yyv10.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Spec = CertificateSigningRequestSpec{} + } else { + yyv11 := &x.Spec + yyv11.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Status = CertificateSigningRequestStatus{} + } else { + yyv12 := &x.Status + yyv12.CodecDecodeSelf(d) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestSpec) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = x.Username != "" + yyq2[2] = x.UID != "" + yyq2[3] = len(x.Groups) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.Request == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Request)) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("request")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Request == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Request)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Username)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("username")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Username)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.UID)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("uid")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.UID)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + if x.Groups == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + z.F.EncSliceStringV(x.Groups, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("groups")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Groups == nil { + r.EncodeNil() + } else { + yym14 := z.EncBinary() + _ = yym14 + if false { + } else { + z.F.EncSliceStringV(x.Groups, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestSpec) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "request": + if r.TryDecodeAsNil() { + x.Request = nil + } else { + yyv4 := &x.Request + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + *yyv4 = r.DecodeBytes(*(*[]byte)(yyv4), false, false) + } + } + case "username": + if r.TryDecodeAsNil() { + x.Username = "" + } else { + x.Username = string(r.DecodeString()) + } + case "uid": + if r.TryDecodeAsNil() { + x.UID = "" + } else { + x.UID = string(r.DecodeString()) + } + case "groups": + if r.TryDecodeAsNil() { + x.Groups = nil + } else { + yyv8 := &x.Groups + yym9 := z.DecBinary() + _ = yym9 + if false { + } else { + z.F.DecSliceStringX(yyv8, false, d) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Request = nil + } else { + yyv11 := &x.Request + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *yyv11 = r.DecodeBytes(*(*[]byte)(yyv11), false, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Username = "" + } else { + x.Username = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.UID = "" + } else { + x.UID = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Groups = nil + } else { + yyv15 := &x.Groups + yym16 := z.DecBinary() + _ = yym16 + if false { + } else { + z.F.DecSliceStringX(yyv15, false, d) + } + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestStatus) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [2]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = len(x.Conditions) != 0 + yyq2[1] = len(x.Certificate) != 0 + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(2) + } else { + yynn2 = 0 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + if x.Conditions == nil { + r.EncodeNil() + } else { + yym4 := z.EncBinary() + _ = yym4 + if false { + } else { + h.encSliceCertificateSigningRequestCondition(([]CertificateSigningRequestCondition)(x.Conditions), e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("conditions")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Conditions == nil { + r.EncodeNil() + } else { + yym5 := z.EncBinary() + _ = yym5 + if false { + } else { + h.encSliceCertificateSigningRequestCondition(([]CertificateSigningRequestCondition)(x.Conditions), e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + if x.Certificate == nil { + r.EncodeNil() + } else { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Certificate)) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("certificate")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Certificate == nil { + r.EncodeNil() + } else { + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeStringBytes(codecSelferC_RAW1234, []byte(x.Certificate)) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestStatus) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "conditions": + if r.TryDecodeAsNil() { + x.Conditions = nil + } else { + yyv4 := &x.Conditions + yym5 := z.DecBinary() + _ = yym5 + if false { + } else { + h.decSliceCertificateSigningRequestCondition((*[]CertificateSigningRequestCondition)(yyv4), d) + } + } + case "certificate": + if r.TryDecodeAsNil() { + x.Certificate = nil + } else { + yyv6 := &x.Certificate + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + *yyv6 = r.DecodeBytes(*(*[]byte)(yyv6), false, false) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj8 int + var yyb8 bool + var yyhl8 bool = l >= 0 + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Conditions = nil + } else { + yyv9 := &x.Conditions + yym10 := z.DecBinary() + _ = yym10 + if false { + } else { + h.decSliceCertificateSigningRequestCondition((*[]CertificateSigningRequestCondition)(yyv9), d) + } + } + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Certificate = nil + } else { + yyv11 := &x.Certificate + yym12 := z.DecBinary() + _ = yym12 + if false { + } else { + *yyv11 = r.DecodeBytes(*(*[]byte)(yyv11), false, false) + } + } + for { + yyj8++ + if yyhl8 { + yyb8 = yyj8 > l + } else { + yyb8 = r.CheckBreak() + } + if yyb8 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj8-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x RequestConditionType) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x)) + } +} + +func (x *RequestConditionType) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + *((*string)(x)) = r.DecodeString() + } +} + +func (x *CertificateSigningRequestCondition) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[1] = x.Reason != "" + yyq2[2] = x.Message != "" + yyq2[3] = true + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + x.Type.CodecEncodeSelf(e) + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("type")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + x.Type.CodecEncodeSelf(e) + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[1] { + yym7 := z.EncBinary() + _ = yym7 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[1] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("reason")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym8 := z.EncBinary() + _ = yym8 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Reason)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("message")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym11 := z.EncBinary() + _ = yym11 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Message)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yy13 := &x.LastUpdateTime + yym14 := z.EncBinary() + _ = yym14 + if false { + } else if z.HasExtensions() && z.EncExt(yy13) { + } else if yym14 { + z.EncBinaryMarshal(yy13) + } else if !yym14 && z.IsJSONHandle() { + z.EncJSONMarshal(yy13) + } else { + z.EncFallback(yy13) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("lastUpdateTime")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy15 := &x.LastUpdateTime + yym16 := z.EncBinary() + _ = yym16 + if false { + } else if z.HasExtensions() && z.EncExt(yy15) { + } else if yym16 { + z.EncBinaryMarshal(yy15) + } else if !yym16 && z.IsJSONHandle() { + z.EncJSONMarshal(yy15) + } else { + z.EncFallback(yy15) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestCondition) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestCondition) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "type": + if r.TryDecodeAsNil() { + x.Type = "" + } else { + x.Type = RequestConditionType(r.DecodeString()) + } + case "reason": + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + case "message": + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + case "lastUpdateTime": + if r.TryDecodeAsNil() { + x.LastUpdateTime = pkg1_unversioned.Time{} + } else { + yyv7 := &x.LastUpdateTime + yym8 := z.DecBinary() + _ = yym8 + if false { + } else if z.HasExtensions() && z.DecExt(yyv7) { + } else if yym8 { + z.DecBinaryUnmarshal(yyv7) + } else if !yym8 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv7) + } else { + z.DecFallback(yyv7, false) + } + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestCondition) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj9 int + var yyb9 bool + var yyhl9 bool = l >= 0 + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Type = "" + } else { + x.Type = RequestConditionType(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Reason = "" + } else { + x.Reason = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Message = "" + } else { + x.Message = string(r.DecodeString()) + } + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.LastUpdateTime = pkg1_unversioned.Time{} + } else { + yyv13 := &x.LastUpdateTime + yym14 := z.DecBinary() + _ = yym14 + if false { + } else if z.HasExtensions() && z.DecExt(yyv13) { + } else if yym14 { + z.DecBinaryUnmarshal(yyv13) + } else if !yym14 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv13) + } else { + z.DecFallback(yyv13, false) + } + } + for { + yyj9++ + if yyhl9 { + yyb9 = yyj9 > l + } else { + yyb9 = r.CheckBreak() + } + if yyb9 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj9-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *CertificateSigningRequestList) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[2] = x.Kind != "" + yyq2[3] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ListMeta + yym5 := z.EncBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.EncExt(yy4) { + } else { + z.EncFallback(yy4) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ListMeta + yym7 := z.EncBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.EncExt(yy6) { + } else { + z.EncFallback(yy6) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceCertificateSigningRequest(([]CertificateSigningRequest)(x.Items), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("items")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceCertificateSigningRequest(([]CertificateSigningRequest)(x.Items), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *CertificateSigningRequestList) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *CertificateSigningRequestList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv4 := &x.ListMeta + yym5 := z.DecBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.DecExt(yyv4) { + } else { + z.DecFallback(yyv4, false) + } + } + case "items": + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv6 := &x.Items + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSliceCertificateSigningRequest((*[]CertificateSigningRequest)(yyv6), d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *CertificateSigningRequestList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv11 := &x.ListMeta + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else { + z.DecFallback(yyv11, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv13 := &x.Items + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSliceCertificateSigningRequest((*[]CertificateSigningRequest)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) encSliceCertificateSigningRequestCondition(v []CertificateSigningRequestCondition, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceCertificateSigningRequestCondition(v *[]CertificateSigningRequestCondition, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []CertificateSigningRequestCondition{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 72) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]CertificateSigningRequestCondition, yyrl1) + } + } else { + yyv1 = make([]CertificateSigningRequestCondition, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, CertificateSigningRequestCondition{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, CertificateSigningRequestCondition{}) // var yyz1 CertificateSigningRequestCondition + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequestCondition{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []CertificateSigningRequestCondition{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} + +func (x codecSelfer1234) encSliceCertificateSigningRequest(v []CertificateSigningRequest, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceCertificateSigningRequest(v *[]CertificateSigningRequest, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []CertificateSigningRequest{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 368) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]CertificateSigningRequest, yyrl1) + } + } else { + yyv1 = make([]CertificateSigningRequest, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, CertificateSigningRequest{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, CertificateSigningRequest{}) // var yyz1 CertificateSigningRequest + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = CertificateSigningRequest{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []CertificateSigningRequest{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.go new file mode 100644 index 000000000000..b882f1e2c63f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types.go @@ -0,0 +1,85 @@ +/* +Copyright 2016 The Kubernetes 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 v1alpha1 + +import ( + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" +) + +// +genclient=true +// +nonNamespaced=true + +// Describes a certificate signing request +type CertificateSigningRequest struct { + unversioned.TypeMeta `json:",inline"` + v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // The certificate request itself and any additonal information. + Spec CertificateSigningRequestSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` + + // Derived information about the request. + Status CertificateSigningRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` +} + +// This information is immutable after the request is created. Only the Request +// and ExtraInfo fields can be set on creation, other fields are derived by +// Kubernetes and cannot be modified by users. +type CertificateSigningRequestSpec struct { + // Base64-encoded PKCS#10 CSR data + Request []byte `json:"request" protobuf:"bytes,1,opt,name=request"` + + // Information about the requesting user (if relevant) + // See user.Info interface for details + Username string `json:"username,omitempty" protobuf:"bytes,2,opt,name=username"` + UID string `json:"uid,omitempty" protobuf:"bytes,3,opt,name=uid"` + Groups []string `json:"groups,omitempty" protobuf:"bytes,4,rep,name=groups"` +} + +type CertificateSigningRequestStatus struct { + // Conditions applied to the request, such as approval or denial. + Conditions []CertificateSigningRequestCondition `json:"conditions,omitempty" protobuf:"bytes,1,rep,name=conditions"` + + // If request was approved, the controller will place the issued certificate here. + Certificate []byte `json:"certificate,omitempty" protobuf:"bytes,2,opt,name=certificate"` +} + +type RequestConditionType string + +// These are the possible conditions for a certificate request. +const ( + CertificateApproved RequestConditionType = "Approved" + CertificateDenied RequestConditionType = "Denied" +) + +type CertificateSigningRequestCondition struct { + // request approval state, currently Approved or Denied. + Type RequestConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=RequestConditionType"` + // brief reason for the request state + Reason string `json:"reason,omitempty" protobuf:"bytes,2,opt,name=reason"` + // human readable message with details about the request state + Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"` + // timestamp for the last update to this condition + LastUpdateTime unversioned.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,4,opt,name=lastUpdateTime"` +} + +type CertificateSigningRequestList struct { + unversioned.TypeMeta `json:",inline"` + unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + Items []CertificateSigningRequest `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types_swagger_doc_generated.go new file mode 100644 index 000000000000..47b3b2821f95 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/types_swagger_doc_generated.go @@ -0,0 +1,70 @@ +/* +Copyright 2016 The Kubernetes 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 v1alpha1 + +// This file contains a collection of methods that can be used from go-restful to +// generate Swagger API documentation for its models. Please read this PR for more +// information on the implementation: https://github.com/emicklei/go-restful/pull/215 +// +// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if +// they are on one line! For multiple line or blocks that you want to ignore use ---. +// Any context after a --- is ignored. +// +// Those methods can be generated by using hack/update-generated-swagger-docs.sh + +// AUTO-GENERATED FUNCTIONS START HERE +var map_CertificateSigningRequest = map[string]string{ + "": "Describes a certificate signing request", + "spec": "The certificate request itself and any additonal information.", + "status": "Derived information about the request.", +} + +func (CertificateSigningRequest) SwaggerDoc() map[string]string { + return map_CertificateSigningRequest +} + +var map_CertificateSigningRequestCondition = map[string]string{ + "type": "request approval state, currently Approved or Denied.", + "reason": "brief reason for the request state", + "message": "human readable message with details about the request state", + "lastUpdateTime": "timestamp for the last update to this condition", +} + +func (CertificateSigningRequestCondition) SwaggerDoc() map[string]string { + return map_CertificateSigningRequestCondition +} + +var map_CertificateSigningRequestSpec = map[string]string{ + "": "This information is immutable after the request is created. Only the Request and ExtraInfo fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.", + "request": "Base64-encoded PKCS#10 CSR data", + "username": "Information about the requesting user (if relevant) See user.Info interface for details", +} + +func (CertificateSigningRequestSpec) SwaggerDoc() map[string]string { + return map_CertificateSigningRequestSpec +} + +var map_CertificateSigningRequestStatus = map[string]string{ + "conditions": "Conditions applied to the request, such as approval or denial.", + "certificate": "If request was approved, the controller will place the issued certificate here.", +} + +func (CertificateSigningRequestStatus) SwaggerDoc() map[string]string { + return map_CertificateSigningRequestStatus +} + +// AUTO-GENERATED FUNCTIONS END HERE diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.conversion.go new file mode 100644 index 000000000000..454a98bf3b27 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.conversion.go @@ -0,0 +1,237 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by conversion-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + certificates "k8s.io/kubernetes/pkg/apis/certificates" + conversion "k8s.io/kubernetes/pkg/conversion" +) + +func init() { + if err := api.Scheme.AddGeneratedConversionFuncs( + Convert_v1alpha1_CertificateSigningRequest_To_certificates_CertificateSigningRequest, + Convert_certificates_CertificateSigningRequest_To_v1alpha1_CertificateSigningRequest, + Convert_v1alpha1_CertificateSigningRequestCondition_To_certificates_CertificateSigningRequestCondition, + Convert_certificates_CertificateSigningRequestCondition_To_v1alpha1_CertificateSigningRequestCondition, + Convert_v1alpha1_CertificateSigningRequestList_To_certificates_CertificateSigningRequestList, + Convert_certificates_CertificateSigningRequestList_To_v1alpha1_CertificateSigningRequestList, + Convert_v1alpha1_CertificateSigningRequestSpec_To_certificates_CertificateSigningRequestSpec, + Convert_certificates_CertificateSigningRequestSpec_To_v1alpha1_CertificateSigningRequestSpec, + Convert_v1alpha1_CertificateSigningRequestStatus_To_certificates_CertificateSigningRequestStatus, + Convert_certificates_CertificateSigningRequestStatus_To_v1alpha1_CertificateSigningRequestStatus, + ); err != nil { + // if one of the conversion functions is malformed, detect it immediately. + panic(err) + } +} + +func autoConvert_v1alpha1_CertificateSigningRequest_To_certificates_CertificateSigningRequest(in *CertificateSigningRequest, out *certificates.CertificateSigningRequest, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil { + return err + } + if err := Convert_v1alpha1_CertificateSigningRequestSpec_To_certificates_CertificateSigningRequestSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_v1alpha1_CertificateSigningRequestStatus_To_certificates_CertificateSigningRequestStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_CertificateSigningRequest_To_certificates_CertificateSigningRequest(in *CertificateSigningRequest, out *certificates.CertificateSigningRequest, s conversion.Scope) error { + return autoConvert_v1alpha1_CertificateSigningRequest_To_certificates_CertificateSigningRequest(in, out, s) +} + +func autoConvert_certificates_CertificateSigningRequest_To_v1alpha1_CertificateSigningRequest(in *certificates.CertificateSigningRequest, out *CertificateSigningRequest, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil { + return err + } + if err := Convert_certificates_CertificateSigningRequestSpec_To_v1alpha1_CertificateSigningRequestSpec(&in.Spec, &out.Spec, s); err != nil { + return err + } + if err := Convert_certificates_CertificateSigningRequestStatus_To_v1alpha1_CertificateSigningRequestStatus(&in.Status, &out.Status, s); err != nil { + return err + } + return nil +} + +func Convert_certificates_CertificateSigningRequest_To_v1alpha1_CertificateSigningRequest(in *certificates.CertificateSigningRequest, out *CertificateSigningRequest, s conversion.Scope) error { + return autoConvert_certificates_CertificateSigningRequest_To_v1alpha1_CertificateSigningRequest(in, out, s) +} + +func autoConvert_v1alpha1_CertificateSigningRequestCondition_To_certificates_CertificateSigningRequestCondition(in *CertificateSigningRequestCondition, out *certificates.CertificateSigningRequestCondition, s conversion.Scope) error { + out.Type = certificates.RequestConditionType(in.Type) + out.Reason = in.Reason + out.Message = in.Message + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastUpdateTime, &out.LastUpdateTime, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_CertificateSigningRequestCondition_To_certificates_CertificateSigningRequestCondition(in *CertificateSigningRequestCondition, out *certificates.CertificateSigningRequestCondition, s conversion.Scope) error { + return autoConvert_v1alpha1_CertificateSigningRequestCondition_To_certificates_CertificateSigningRequestCondition(in, out, s) +} + +func autoConvert_certificates_CertificateSigningRequestCondition_To_v1alpha1_CertificateSigningRequestCondition(in *certificates.CertificateSigningRequestCondition, out *CertificateSigningRequestCondition, s conversion.Scope) error { + out.Type = RequestConditionType(in.Type) + out.Reason = in.Reason + out.Message = in.Message + if err := api.Convert_unversioned_Time_To_unversioned_Time(&in.LastUpdateTime, &out.LastUpdateTime, s); err != nil { + return err + } + return nil +} + +func Convert_certificates_CertificateSigningRequestCondition_To_v1alpha1_CertificateSigningRequestCondition(in *certificates.CertificateSigningRequestCondition, out *CertificateSigningRequestCondition, s conversion.Scope) error { + return autoConvert_certificates_CertificateSigningRequestCondition_To_v1alpha1_CertificateSigningRequestCondition(in, out, s) +} + +func autoConvert_v1alpha1_CertificateSigningRequestList_To_certificates_CertificateSigningRequestList(in *CertificateSigningRequestList, out *certificates.CertificateSigningRequestList, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_unversioned_ListMeta_To_unversioned_ListMeta(&in.ListMeta, &out.ListMeta, s); err != nil { + return err + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]certificates.CertificateSigningRequest, len(*in)) + for i := range *in { + if err := Convert_v1alpha1_CertificateSigningRequest_To_certificates_CertificateSigningRequest(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_v1alpha1_CertificateSigningRequestList_To_certificates_CertificateSigningRequestList(in *CertificateSigningRequestList, out *certificates.CertificateSigningRequestList, s conversion.Scope) error { + return autoConvert_v1alpha1_CertificateSigningRequestList_To_certificates_CertificateSigningRequestList(in, out, s) +} + +func autoConvert_certificates_CertificateSigningRequestList_To_v1alpha1_CertificateSigningRequestList(in *certificates.CertificateSigningRequestList, out *CertificateSigningRequestList, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_unversioned_ListMeta_To_unversioned_ListMeta(&in.ListMeta, &out.ListMeta, s); err != nil { + return err + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CertificateSigningRequest, len(*in)) + for i := range *in { + if err := Convert_certificates_CertificateSigningRequest_To_v1alpha1_CertificateSigningRequest(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_certificates_CertificateSigningRequestList_To_v1alpha1_CertificateSigningRequestList(in *certificates.CertificateSigningRequestList, out *CertificateSigningRequestList, s conversion.Scope) error { + return autoConvert_certificates_CertificateSigningRequestList_To_v1alpha1_CertificateSigningRequestList(in, out, s) +} + +func autoConvert_v1alpha1_CertificateSigningRequestSpec_To_certificates_CertificateSigningRequestSpec(in *CertificateSigningRequestSpec, out *certificates.CertificateSigningRequestSpec, s conversion.Scope) error { + if err := conversion.Convert_Slice_byte_To_Slice_byte(&in.Request, &out.Request, s); err != nil { + return err + } + out.Username = in.Username + out.UID = in.UID + out.Groups = in.Groups + return nil +} + +func Convert_v1alpha1_CertificateSigningRequestSpec_To_certificates_CertificateSigningRequestSpec(in *CertificateSigningRequestSpec, out *certificates.CertificateSigningRequestSpec, s conversion.Scope) error { + return autoConvert_v1alpha1_CertificateSigningRequestSpec_To_certificates_CertificateSigningRequestSpec(in, out, s) +} + +func autoConvert_certificates_CertificateSigningRequestSpec_To_v1alpha1_CertificateSigningRequestSpec(in *certificates.CertificateSigningRequestSpec, out *CertificateSigningRequestSpec, s conversion.Scope) error { + if err := conversion.Convert_Slice_byte_To_Slice_byte(&in.Request, &out.Request, s); err != nil { + return err + } + out.Username = in.Username + out.UID = in.UID + out.Groups = in.Groups + return nil +} + +func Convert_certificates_CertificateSigningRequestSpec_To_v1alpha1_CertificateSigningRequestSpec(in *certificates.CertificateSigningRequestSpec, out *CertificateSigningRequestSpec, s conversion.Scope) error { + return autoConvert_certificates_CertificateSigningRequestSpec_To_v1alpha1_CertificateSigningRequestSpec(in, out, s) +} + +func autoConvert_v1alpha1_CertificateSigningRequestStatus_To_certificates_CertificateSigningRequestStatus(in *CertificateSigningRequestStatus, out *certificates.CertificateSigningRequestStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]certificates.CertificateSigningRequestCondition, len(*in)) + for i := range *in { + if err := Convert_v1alpha1_CertificateSigningRequestCondition_To_certificates_CertificateSigningRequestCondition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if err := conversion.Convert_Slice_byte_To_Slice_byte(&in.Certificate, &out.Certificate, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_CertificateSigningRequestStatus_To_certificates_CertificateSigningRequestStatus(in *CertificateSigningRequestStatus, out *certificates.CertificateSigningRequestStatus, s conversion.Scope) error { + return autoConvert_v1alpha1_CertificateSigningRequestStatus_To_certificates_CertificateSigningRequestStatus(in, out, s) +} + +func autoConvert_certificates_CertificateSigningRequestStatus_To_v1alpha1_CertificateSigningRequestStatus(in *certificates.CertificateSigningRequestStatus, out *CertificateSigningRequestStatus, s conversion.Scope) error { + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]CertificateSigningRequestCondition, len(*in)) + for i := range *in { + if err := Convert_certificates_CertificateSigningRequestCondition_To_v1alpha1_CertificateSigningRequestCondition(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if err := conversion.Convert_Slice_byte_To_Slice_byte(&in.Certificate, &out.Certificate, s); err != nil { + return err + } + return nil +} + +func Convert_certificates_CertificateSigningRequestStatus_To_v1alpha1_CertificateSigningRequestStatus(in *certificates.CertificateSigningRequestStatus, out *CertificateSigningRequestStatus, s conversion.Scope) error { + return autoConvert_certificates_CertificateSigningRequestStatus_To_v1alpha1_CertificateSigningRequestStatus(in, out, s) +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..0c69630a2dcf --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,142 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequest, InType: reflect.TypeOf(func() *CertificateSigningRequest { var x *CertificateSigningRequest; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestCondition, InType: reflect.TypeOf(func() *CertificateSigningRequestCondition { var x *CertificateSigningRequestCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestList, InType: reflect.TypeOf(func() *CertificateSigningRequestList { var x *CertificateSigningRequestList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestSpec, InType: reflect.TypeOf(func() *CertificateSigningRequestSpec { var x *CertificateSigningRequestSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_CertificateSigningRequestStatus, InType: reflect.TypeOf(func() *CertificateSigningRequestStatus { var x *CertificateSigningRequestStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1alpha1_CertificateSigningRequest(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequest) + out := out.(*CertificateSigningRequest) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1alpha1_CertificateSigningRequestSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1alpha1_CertificateSigningRequestStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1alpha1_CertificateSigningRequestCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestCondition) + out := out.(*CertificateSigningRequestCondition) + out.Type = in.Type + out.Reason = in.Reason + out.Message = in.Message + out.LastUpdateTime = in.LastUpdateTime.DeepCopy() + return nil + } +} + +func DeepCopy_v1alpha1_CertificateSigningRequestList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestList) + out := out.(*CertificateSigningRequestList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CertificateSigningRequest, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_CertificateSigningRequest(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_CertificateSigningRequestSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestSpec) + out := out.(*CertificateSigningRequestSpec) + if in.Request != nil { + in, out := &in.Request, &out.Request + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Request = nil + } + out.Username = in.Username + out.UID = in.UID + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_CertificateSigningRequestStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestStatus) + out := out.(*CertificateSigningRequestStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]CertificateSigningRequestCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_CertificateSigningRequestCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Certificate != nil { + in, out := &in.Certificate, &out.Certificate + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Certificate = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/validation/validation.go new file mode 100644 index 000000000000..b62573844858 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/validation/validation.go @@ -0,0 +1,63 @@ +/* +Copyright 2016 The Kubernetes 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 validation + +import ( + "fmt" + + apivalidation "k8s.io/kubernetes/pkg/api/validation" + "k8s.io/kubernetes/pkg/apis/certificates" + certutil "k8s.io/kubernetes/pkg/util/certificates" + "k8s.io/kubernetes/pkg/util/validation/field" +) + +// validateCSR validates the signature and formatting of a base64-wrapped, +// PEM-encoded PKCS#10 certificate signing request. If this is invalid, we must +// not accept the CSR for further processing. +func validateCSR(obj *certificates.CertificateSigningRequest) error { + csr, err := certutil.ParseCertificateRequestObject(obj) + if err != nil { + return err + } + // check that the signature is valid + err = csr.CheckSignature() + if err != nil { + return err + } + return nil +} + +// We don't care what you call your certificate requests. +func ValidateCertificateRequestName(name string, prefix bool) []string { + return nil +} + +func ValidateCertificateSigningRequest(csr *certificates.CertificateSigningRequest) field.ErrorList { + isNamespaced := false + allErrs := apivalidation.ValidateObjectMeta(&csr.ObjectMeta, isNamespaced, ValidateCertificateRequestName, field.NewPath("metadata")) + err := validateCSR(csr) + if err != nil { + allErrs = append(allErrs, field.Invalid(field.NewPath("request"), csr.Spec.Request, fmt.Sprintf("%v", err))) + } + return allErrs +} + +func ValidateCertificateSigningRequestUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList { + validationErrorList := ValidateCertificateSigningRequest(newCSR) + metaUpdateErrorList := apivalidation.ValidateObjectMetaUpdate(&newCSR.ObjectMeta, &oldCSR.ObjectMeta, field.NewPath("metadata")) + return append(validationErrorList, metaUpdateErrorList...) +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/certificates/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/certificates/zz_generated.deepcopy.go new file mode 100644 index 000000000000..49ad9ad84acc --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/certificates/zz_generated.deepcopy.go @@ -0,0 +1,141 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package certificates + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_certificates_CertificateSigningRequest, InType: reflect.TypeOf(func() *CertificateSigningRequest { var x *CertificateSigningRequest; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_certificates_CertificateSigningRequestCondition, InType: reflect.TypeOf(func() *CertificateSigningRequestCondition { var x *CertificateSigningRequestCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_certificates_CertificateSigningRequestList, InType: reflect.TypeOf(func() *CertificateSigningRequestList { var x *CertificateSigningRequestList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_certificates_CertificateSigningRequestSpec, InType: reflect.TypeOf(func() *CertificateSigningRequestSpec { var x *CertificateSigningRequestSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_certificates_CertificateSigningRequestStatus, InType: reflect.TypeOf(func() *CertificateSigningRequestStatus { var x *CertificateSigningRequestStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_certificates_CertificateSigningRequest(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequest) + out := out.(*CertificateSigningRequest) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_certificates_CertificateSigningRequestSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_certificates_CertificateSigningRequestStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_certificates_CertificateSigningRequestCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestCondition) + out := out.(*CertificateSigningRequestCondition) + out.Type = in.Type + out.Reason = in.Reason + out.Message = in.Message + out.LastUpdateTime = in.LastUpdateTime.DeepCopy() + return nil + } +} + +func DeepCopy_certificates_CertificateSigningRequestList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestList) + out := out.(*CertificateSigningRequestList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CertificateSigningRequest, len(*in)) + for i := range *in { + if err := DeepCopy_certificates_CertificateSigningRequest(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_certificates_CertificateSigningRequestSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestSpec) + out := out.(*CertificateSigningRequestSpec) + if in.Request != nil { + in, out := &in.Request, &out.Request + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Request = nil + } + out.Username = in.Username + out.UID = in.UID + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Groups = nil + } + return nil + } +} + +func DeepCopy_certificates_CertificateSigningRequestStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CertificateSigningRequestStatus) + out := out.(*CertificateSigningRequestStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]CertificateSigningRequestCondition, len(*in)) + for i := range *in { + if err := DeepCopy_certificates_CertificateSigningRequestCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.Certificate != nil { + in, out := &in.Certificate, &out.Certificate + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Certificate = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/deep_copy_generated.go deleted file mode 100644 index f80c22e9b6b0..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/deep_copy_generated.go +++ /dev/null @@ -1,374 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package componentconfig - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_componentconfig_IPVar, - DeepCopy_componentconfig_KubeControllerManagerConfiguration, - DeepCopy_componentconfig_KubeProxyConfiguration, - DeepCopy_componentconfig_KubeSchedulerConfiguration, - DeepCopy_componentconfig_KubeletConfiguration, - DeepCopy_componentconfig_LeaderElectionConfiguration, - DeepCopy_componentconfig_PersistentVolumeRecyclerConfiguration, - DeepCopy_componentconfig_PortRangeVar, - DeepCopy_componentconfig_VolumeConfiguration, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_componentconfig_IPVar(in IPVar, out *IPVar, c *conversion.Cloner) error { - if in.Val != nil { - in, out := in.Val, &out.Val - *out = new(string) - **out = *in - } else { - out.Val = nil - } - return nil -} - -func DeepCopy_componentconfig_KubeControllerManagerConfiguration(in KubeControllerManagerConfiguration, out *KubeControllerManagerConfiguration, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Port = in.Port - out.Address = in.Address - out.CloudProvider = in.CloudProvider - out.CloudConfigFile = in.CloudConfigFile - out.ConcurrentEndpointSyncs = in.ConcurrentEndpointSyncs - out.ConcurrentRSSyncs = in.ConcurrentRSSyncs - out.ConcurrentRCSyncs = in.ConcurrentRCSyncs - out.ConcurrentResourceQuotaSyncs = in.ConcurrentResourceQuotaSyncs - out.ConcurrentDeploymentSyncs = in.ConcurrentDeploymentSyncs - out.ConcurrentDaemonSetSyncs = in.ConcurrentDaemonSetSyncs - out.ConcurrentJobSyncs = in.ConcurrentJobSyncs - out.ConcurrentNamespaceSyncs = in.ConcurrentNamespaceSyncs - out.LookupCacheSizeForRC = in.LookupCacheSizeForRC - out.LookupCacheSizeForRS = in.LookupCacheSizeForRS - out.LookupCacheSizeForDaemonSet = in.LookupCacheSizeForDaemonSet - if err := unversioned.DeepCopy_unversioned_Duration(in.ServiceSyncPeriod, &out.ServiceSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.NodeSyncPeriod, &out.NodeSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.ResourceQuotaSyncPeriod, &out.ResourceQuotaSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.NamespaceSyncPeriod, &out.NamespaceSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.PVClaimBinderSyncPeriod, &out.PVClaimBinderSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.MinResyncPeriod, &out.MinResyncPeriod, c); err != nil { - return err - } - out.TerminatedPodGCThreshold = in.TerminatedPodGCThreshold - if err := unversioned.DeepCopy_unversioned_Duration(in.HorizontalPodAutoscalerSyncPeriod, &out.HorizontalPodAutoscalerSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.DeploymentControllerSyncPeriod, &out.DeploymentControllerSyncPeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.PodEvictionTimeout, &out.PodEvictionTimeout, c); err != nil { - return err - } - out.DeletingPodsQps = in.DeletingPodsQps - out.DeletingPodsBurst = in.DeletingPodsBurst - if err := unversioned.DeepCopy_unversioned_Duration(in.NodeMonitorGracePeriod, &out.NodeMonitorGracePeriod, c); err != nil { - return err - } - out.RegisterRetryCount = in.RegisterRetryCount - if err := unversioned.DeepCopy_unversioned_Duration(in.NodeStartupGracePeriod, &out.NodeStartupGracePeriod, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.NodeMonitorPeriod, &out.NodeMonitorPeriod, c); err != nil { - return err - } - out.ServiceAccountKeyFile = in.ServiceAccountKeyFile - out.EnableProfiling = in.EnableProfiling - out.ClusterName = in.ClusterName - out.ClusterCIDR = in.ClusterCIDR - out.ServiceCIDR = in.ServiceCIDR - out.NodeCIDRMaskSize = in.NodeCIDRMaskSize - out.AllocateNodeCIDRs = in.AllocateNodeCIDRs - out.ConfigureCloudRoutes = in.ConfigureCloudRoutes - out.RootCAFile = in.RootCAFile - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = in.KubeAPIBurst - if err := DeepCopy_componentconfig_LeaderElectionConfiguration(in.LeaderElection, &out.LeaderElection, c); err != nil { - return err - } - if err := DeepCopy_componentconfig_VolumeConfiguration(in.VolumeConfiguration, &out.VolumeConfiguration, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.ControllerStartInterval, &out.ControllerStartInterval, c); err != nil { - return err - } - out.EnableGarbageCollector = in.EnableGarbageCollector - return nil -} - -func DeepCopy_componentconfig_KubeProxyConfiguration(in KubeProxyConfiguration, out *KubeProxyConfiguration, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.BindAddress = in.BindAddress - out.ClusterCIDR = in.ClusterCIDR - out.HealthzBindAddress = in.HealthzBindAddress - out.HealthzPort = in.HealthzPort - out.HostnameOverride = in.HostnameOverride - if in.IPTablesMasqueradeBit != nil { - in, out := in.IPTablesMasqueradeBit, &out.IPTablesMasqueradeBit - *out = new(int32) - **out = *in - } else { - out.IPTablesMasqueradeBit = nil - } - if err := unversioned.DeepCopy_unversioned_Duration(in.IPTablesSyncPeriod, &out.IPTablesSyncPeriod, c); err != nil { - return err - } - out.KubeconfigPath = in.KubeconfigPath - out.MasqueradeAll = in.MasqueradeAll - out.Master = in.Master - if in.OOMScoreAdj != nil { - in, out := in.OOMScoreAdj, &out.OOMScoreAdj - *out = new(int32) - **out = *in - } else { - out.OOMScoreAdj = nil - } - out.Mode = in.Mode - out.PortRange = in.PortRange - out.ResourceContainer = in.ResourceContainer - if err := unversioned.DeepCopy_unversioned_Duration(in.UDPIdleTimeout, &out.UDPIdleTimeout, c); err != nil { - return err - } - out.ConntrackMax = in.ConntrackMax - out.ConntrackMaxPerCore = in.ConntrackMaxPerCore - if err := unversioned.DeepCopy_unversioned_Duration(in.ConntrackTCPEstablishedTimeout, &out.ConntrackTCPEstablishedTimeout, c); err != nil { - return err - } - return nil -} - -func DeepCopy_componentconfig_KubeSchedulerConfiguration(in KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Port = in.Port - out.Address = in.Address - out.AlgorithmProvider = in.AlgorithmProvider - out.PolicyConfigFile = in.PolicyConfigFile - out.EnableProfiling = in.EnableProfiling - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = in.KubeAPIBurst - out.SchedulerName = in.SchedulerName - out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight - out.FailureDomains = in.FailureDomains - if err := DeepCopy_componentconfig_LeaderElectionConfiguration(in.LeaderElection, &out.LeaderElection, c); err != nil { - return err - } - return nil -} - -func DeepCopy_componentconfig_KubeletConfiguration(in KubeletConfiguration, out *KubeletConfiguration, c *conversion.Cloner) error { - out.Config = in.Config - if err := unversioned.DeepCopy_unversioned_Duration(in.SyncFrequency, &out.SyncFrequency, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.FileCheckFrequency, &out.FileCheckFrequency, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.HTTPCheckFrequency, &out.HTTPCheckFrequency, c); err != nil { - return err - } - out.ManifestURL = in.ManifestURL - out.ManifestURLHeader = in.ManifestURLHeader - out.EnableServer = in.EnableServer - out.Address = in.Address - out.Port = in.Port - out.ReadOnlyPort = in.ReadOnlyPort - out.TLSCertFile = in.TLSCertFile - out.TLSPrivateKeyFile = in.TLSPrivateKeyFile - out.CertDirectory = in.CertDirectory - out.HostnameOverride = in.HostnameOverride - out.PodInfraContainerImage = in.PodInfraContainerImage - out.DockerEndpoint = in.DockerEndpoint - out.RootDirectory = in.RootDirectory - out.SeccompProfileRoot = in.SeccompProfileRoot - out.AllowPrivileged = in.AllowPrivileged - out.HostNetworkSources = in.HostNetworkSources - out.HostPIDSources = in.HostPIDSources - out.HostIPCSources = in.HostIPCSources - out.RegistryPullQPS = in.RegistryPullQPS - out.RegistryBurst = in.RegistryBurst - out.EventRecordQPS = in.EventRecordQPS - out.EventBurst = in.EventBurst - out.EnableDebuggingHandlers = in.EnableDebuggingHandlers - if err := unversioned.DeepCopy_unversioned_Duration(in.MinimumGCAge, &out.MinimumGCAge, c); err != nil { - return err - } - out.MaxPerPodContainerCount = in.MaxPerPodContainerCount - out.MaxContainerCount = in.MaxContainerCount - out.CAdvisorPort = in.CAdvisorPort - out.HealthzPort = in.HealthzPort - out.HealthzBindAddress = in.HealthzBindAddress - out.OOMScoreAdj = in.OOMScoreAdj - out.RegisterNode = in.RegisterNode - out.ClusterDomain = in.ClusterDomain - out.MasterServiceNamespace = in.MasterServiceNamespace - out.ClusterDNS = in.ClusterDNS - if err := unversioned.DeepCopy_unversioned_Duration(in.StreamingConnectionIdleTimeout, &out.StreamingConnectionIdleTimeout, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.NodeStatusUpdateFrequency, &out.NodeStatusUpdateFrequency, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.ImageMinimumGCAge, &out.ImageMinimumGCAge, c); err != nil { - return err - } - out.ImageGCHighThresholdPercent = in.ImageGCHighThresholdPercent - out.ImageGCLowThresholdPercent = in.ImageGCLowThresholdPercent - out.LowDiskSpaceThresholdMB = in.LowDiskSpaceThresholdMB - if err := unversioned.DeepCopy_unversioned_Duration(in.VolumeStatsAggPeriod, &out.VolumeStatsAggPeriod, c); err != nil { - return err - } - out.NetworkPluginName = in.NetworkPluginName - out.NetworkPluginDir = in.NetworkPluginDir - out.VolumePluginDir = in.VolumePluginDir - out.CloudProvider = in.CloudProvider - out.CloudConfigFile = in.CloudConfigFile - out.KubeletCgroups = in.KubeletCgroups - out.RuntimeCgroups = in.RuntimeCgroups - out.SystemCgroups = in.SystemCgroups - out.CgroupRoot = in.CgroupRoot - out.ContainerRuntime = in.ContainerRuntime - if err := unversioned.DeepCopy_unversioned_Duration(in.RuntimeRequestTimeout, &out.RuntimeRequestTimeout, c); err != nil { - return err - } - out.RktPath = in.RktPath - out.RktAPIEndpoint = in.RktAPIEndpoint - out.RktStage1Image = in.RktStage1Image - out.LockFilePath = in.LockFilePath - out.ExitOnLockContention = in.ExitOnLockContention - out.ConfigureCBR0 = in.ConfigureCBR0 - out.HairpinMode = in.HairpinMode - out.BabysitDaemons = in.BabysitDaemons - out.MaxPods = in.MaxPods - out.NvidiaGPUs = in.NvidiaGPUs - out.DockerExecHandlerName = in.DockerExecHandlerName - out.PodCIDR = in.PodCIDR - out.ResolverConfig = in.ResolverConfig - out.CPUCFSQuota = in.CPUCFSQuota - out.Containerized = in.Containerized - out.MaxOpenFiles = in.MaxOpenFiles - out.ReconcileCIDR = in.ReconcileCIDR - out.RegisterSchedulable = in.RegisterSchedulable - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = in.KubeAPIBurst - out.SerializeImagePulls = in.SerializeImagePulls - out.ExperimentalFlannelOverlay = in.ExperimentalFlannelOverlay - if err := unversioned.DeepCopy_unversioned_Duration(in.OutOfDiskTransitionFrequency, &out.OutOfDiskTransitionFrequency, c); err != nil { - return err - } - out.NodeIP = in.NodeIP - if in.NodeLabels != nil { - in, out := in.NodeLabels, &out.NodeLabels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.NodeLabels = nil - } - out.NonMasqueradeCIDR = in.NonMasqueradeCIDR - out.EnableCustomMetrics = in.EnableCustomMetrics - out.EvictionHard = in.EvictionHard - out.EvictionSoft = in.EvictionSoft - out.EvictionSoftGracePeriod = in.EvictionSoftGracePeriod - if err := unversioned.DeepCopy_unversioned_Duration(in.EvictionPressureTransitionPeriod, &out.EvictionPressureTransitionPeriod, c); err != nil { - return err - } - out.EvictionMaxPodGracePeriod = in.EvictionMaxPodGracePeriod - out.PodsPerCore = in.PodsPerCore - out.EnableControllerAttachDetach = in.EnableControllerAttachDetach - return nil -} - -func DeepCopy_componentconfig_LeaderElectionConfiguration(in LeaderElectionConfiguration, out *LeaderElectionConfiguration, c *conversion.Cloner) error { - out.LeaderElect = in.LeaderElect - if err := unversioned.DeepCopy_unversioned_Duration(in.LeaseDuration, &out.LeaseDuration, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.RenewDeadline, &out.RenewDeadline, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.RetryPeriod, &out.RetryPeriod, c); err != nil { - return err - } - return nil -} - -func DeepCopy_componentconfig_PersistentVolumeRecyclerConfiguration(in PersistentVolumeRecyclerConfiguration, out *PersistentVolumeRecyclerConfiguration, c *conversion.Cloner) error { - out.MaximumRetry = in.MaximumRetry - out.MinimumTimeoutNFS = in.MinimumTimeoutNFS - out.PodTemplateFilePathNFS = in.PodTemplateFilePathNFS - out.IncrementTimeoutNFS = in.IncrementTimeoutNFS - out.PodTemplateFilePathHostPath = in.PodTemplateFilePathHostPath - out.MinimumTimeoutHostPath = in.MinimumTimeoutHostPath - out.IncrementTimeoutHostPath = in.IncrementTimeoutHostPath - return nil -} - -func DeepCopy_componentconfig_PortRangeVar(in PortRangeVar, out *PortRangeVar, c *conversion.Cloner) error { - if in.Val != nil { - in, out := in.Val, &out.Val - *out = new(string) - **out = *in - } else { - out.Val = nil - } - return nil -} - -func DeepCopy_componentconfig_VolumeConfiguration(in VolumeConfiguration, out *VolumeConfiguration, c *conversion.Cloner) error { - out.EnableHostPathProvisioning = in.EnableHostPathProvisioning - out.EnableDynamicProvisioning = in.EnableDynamicProvisioning - if err := DeepCopy_componentconfig_PersistentVolumeRecyclerConfiguration(in.PersistentVolumeRecyclerConfiguration, &out.PersistentVolumeRecyclerConfiguration, c); err != nil { - return err - } - out.FlexVolumePluginDir = in.FlexVolumePluginDir - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/doc.go new file mode 100644 index 000000000000..d044b16db391 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package componentconfig diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/helpers.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/helpers.go index edd9c7975935..43b625b7ec00 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/install/install.go index ec55542737da..1a8b0cd1266c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/register.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/register.go index 0666c5431799..f27bf1390ff1 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -46,5 +46,10 @@ func addKnownTypes(scheme *runtime.Scheme) { scheme.AddKnownTypes(SchemeGroupVersion, &KubeProxyConfiguration{}, &KubeSchedulerConfiguration{}, + &KubeletConfiguration{}, ) } + +func (obj *KubeProxyConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *KubeSchedulerConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *KubeletConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go index 029f24fd538c..a856d572732d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( "fmt" codec1978 "github.com/ugorji/go/codec" pkg1_unversioned "k8s.io/kubernetes/pkg/api/unversioned" + pkg2_config "k8s.io/kubernetes/pkg/util/config" "reflect" "runtime" time "time" @@ -62,8 +63,9 @@ func init() { } if false { // reference the types, but skip this branch at build/run time var v0 pkg1_unversioned.TypeMeta - var v1 time.Duration - _, _ = v0, v1 + var v1 pkg2_config.ConfigurationMap + var v2 time.Duration + _, _, _ = v0, v1, v2 } } @@ -374,7 +376,7 @@ func (x *KubeProxyConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeletCgroups")) + r.EncodeString(codecSelferC_UTF81234, string("resourceContainer")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym50 := z.EncBinary() _ = yym50 @@ -693,7 +695,7 @@ func (x *KubeProxyConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Deco } else { x.PortRange = string(r.DecodeString()) } - case "kubeletCgroups": + case "resourceContainer": if r.TryDecodeAsNil() { x.ResourceContainer = "" } else { @@ -1216,31 +1218,35 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [91]bool + var yyq2 [97]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[48] = x.CloudProvider != "" yyq2[49] = x.CloudConfigFile != "" yyq2[50] = x.KubeletCgroups != "" - yyq2[51] = x.RuntimeCgroups != "" - yyq2[52] = x.SystemCgroups != "" - yyq2[53] = x.CgroupRoot != "" - yyq2[55] = true - yyq2[56] = x.RktPath != "" - yyq2[57] = x.RktAPIEndpoint != "" - yyq2[58] = x.RktStage1Image != "" - yyq2[79] = true - yyq2[80] = x.NodeIP != "" - yyq2[84] = x.EvictionHard != "" - yyq2[85] = x.EvictionSoft != "" - yyq2[86] = x.EvictionSoftGracePeriod != "" - yyq2[87] = true - yyq2[88] = x.EvictionMaxPodGracePeriod != 0 + yyq2[51] = x.CgroupsPerQOS != false + yyq2[52] = x.RuntimeCgroups != "" + yyq2[53] = x.SystemCgroups != "" + yyq2[54] = x.CgroupRoot != "" + yyq2[56] = true + yyq2[57] = x.RktPath != "" + yyq2[58] = x.RktAPIEndpoint != "" + yyq2[59] = x.RktStage1Image != "" + yyq2[80] = true + yyq2[81] = x.NodeIP != "" + yyq2[85] = x.EvictionHard != "" + yyq2[86] = x.EvictionSoft != "" + yyq2[87] = x.EvictionSoftGracePeriod != "" + yyq2[88] = true + yyq2[89] = x.EvictionMaxPodGracePeriod != 0 + yyq2[90] = x.EvictionMinimumReclaim != "" + yyq2[95] = x.Kind != "" + yyq2[96] = x.APIVersion != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(91) + r.EncodeArrayStart(97) } else { - yynn2 = 74 + yynn2 = 76 for _, b := range yyq2 { if b { yynn2++ @@ -1431,7 +1437,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym34 if false { } else { - r.EncodeUint(uint64(x.Port)) + r.EncodeInt(int64(x.Port)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) @@ -1441,7 +1447,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym35 if false { } else { - r.EncodeUint(uint64(x.Port)) + r.EncodeInt(int64(x.Port)) } } if yyr2 || yy2arr2 { @@ -1450,7 +1456,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym37 if false { } else { - r.EncodeUint(uint64(x.ReadOnlyPort)) + r.EncodeInt(int64(x.ReadOnlyPort)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) @@ -1460,7 +1466,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym38 if false { } else { - r.EncodeUint(uint64(x.ReadOnlyPort)) + r.EncodeInt(int64(x.ReadOnlyPort)) } } if yyr2 || yy2arr2 { @@ -1473,7 +1479,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("tLSCertFile")) + r.EncodeString(codecSelferC_UTF81234, string("tlsCertFile")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym41 := z.EncBinary() _ = yym41 @@ -1492,7 +1498,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("tLSPrivateKeyFile")) + r.EncodeString(codecSelferC_UTF81234, string("tlsPrivateKeyFile")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym44 := z.EncBinary() _ = yym44 @@ -1636,59 +1642,83 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym67 := z.EncBinary() - _ = yym67 - if false { + if x.HostNetworkSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostNetworkSources)) + yym67 := z.EncBinary() + _ = yym67 + if false { + } else { + z.F.EncSliceStringV(x.HostNetworkSources, false, e) + } } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("hostNetworkSources")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym68 := z.EncBinary() - _ = yym68 - if false { + if x.HostNetworkSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostNetworkSources)) + yym68 := z.EncBinary() + _ = yym68 + if false { + } else { + z.F.EncSliceStringV(x.HostNetworkSources, false, e) + } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym70 := z.EncBinary() - _ = yym70 - if false { + if x.HostPIDSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostPIDSources)) + yym70 := z.EncBinary() + _ = yym70 + if false { + } else { + z.F.EncSliceStringV(x.HostPIDSources, false, e) + } } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("hostPIDSources")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym71 := z.EncBinary() - _ = yym71 - if false { + if x.HostPIDSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostPIDSources)) + yym71 := z.EncBinary() + _ = yym71 + if false { + } else { + z.F.EncSliceStringV(x.HostPIDSources, false, e) + } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym73 := z.EncBinary() - _ = yym73 - if false { + if x.HostIPCSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostIPCSources)) + yym73 := z.EncBinary() + _ = yym73 + if false { + } else { + z.F.EncSliceStringV(x.HostIPCSources, false, e) + } } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("hostIPCSources")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym74 := z.EncBinary() - _ = yym74 - if false { + if x.HostIPCSources == nil { + r.EncodeNil() } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HostIPCSources)) + yym74 := z.EncBinary() + _ = yym74 + if false { + } else { + z.F.EncSliceStringV(x.HostIPCSources, false, e) + } } } if yyr2 || yy2arr2 { @@ -1697,7 +1727,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym76 if false { } else { - r.EncodeFloat64(float64(x.RegistryPullQPS)) + r.EncodeInt(int64(x.RegistryPullQPS)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) @@ -1707,7 +1737,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym77 if false { } else { - r.EncodeFloat64(float64(x.RegistryPullQPS)) + r.EncodeInt(int64(x.RegistryPullQPS)) } } if yyr2 || yy2arr2 { @@ -1735,7 +1765,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym82 if false { } else { - r.EncodeFloat32(float32(x.EventRecordQPS)) + r.EncodeInt(int64(x.EventRecordQPS)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) @@ -1745,7 +1775,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym83 if false { } else { - r.EncodeFloat32(float32(x.EventRecordQPS)) + r.EncodeInt(int64(x.EventRecordQPS)) } } if yyr2 || yy2arr2 { @@ -1857,7 +1887,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym102 if false { } else { - r.EncodeUint(uint64(x.CAdvisorPort)) + r.EncodeInt(int64(x.CAdvisorPort)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) @@ -1867,7 +1897,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym103 if false { } else { - r.EncodeUint(uint64(x.CAdvisorPort)) + r.EncodeInt(int64(x.CAdvisorPort)) } } if yyr2 || yy2arr2 { @@ -2307,21 +2337,21 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym173 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.RuntimeCgroups)) + r.EncodeBool(bool(x.CgroupsPerQOS)) } } else { - r.EncodeString(codecSelferC_UTF81234, "") + r.EncodeBool(false) } } else { if yyq2[51] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("runtimeCgroups")) + r.EncodeString(codecSelferC_UTF81234, string("CgroupsPerQOS")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym174 := z.EncBinary() _ = yym174 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.RuntimeCgroups)) + r.EncodeBool(bool(x.CgroupsPerQOS)) } } } @@ -2332,7 +2362,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym176 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.SystemCgroups)) + r.EncodeString(codecSelferC_UTF81234, string(x.RuntimeCgroups)) } } else { r.EncodeString(codecSelferC_UTF81234, "") @@ -2340,13 +2370,13 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[52] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("systemContainer")) + r.EncodeString(codecSelferC_UTF81234, string("runtimeCgroups")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym177 := z.EncBinary() _ = yym177 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.SystemCgroups)) + r.EncodeString(codecSelferC_UTF81234, string(x.RuntimeCgroups)) } } } @@ -2357,7 +2387,7 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym179 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.CgroupRoot)) + r.EncodeString(codecSelferC_UTF81234, string(x.SystemCgroups)) } } else { r.EncodeString(codecSelferC_UTF81234, "") @@ -2365,11 +2395,36 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } else { if yyq2[53] { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("cgroupRoot")) + r.EncodeString(codecSelferC_UTF81234, string("systemCgroups")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym180 := z.EncBinary() _ = yym180 if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.SystemCgroups)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[54] { + yym182 := z.EncBinary() + _ = yym182 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.CgroupRoot)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[54] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("cgroupRoot")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym183 := z.EncBinary() + _ = yym183 + if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.CgroupRoot)) } @@ -2377,8 +2432,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym182 := z.EncBinary() - _ = yym182 + yym185 := z.EncBinary() + _ = yym185 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ContainerRuntime)) @@ -2387,8 +2442,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("containerRuntime")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym183 := z.EncBinary() - _ = yym183 + yym186 := z.EncBinary() + _ = yym186 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ContainerRuntime)) @@ -2396,42 +2451,42 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[55] { - yy185 := &x.RuntimeRequestTimeout - yym186 := z.EncBinary() - _ = yym186 + if yyq2[56] { + yy188 := &x.RuntimeRequestTimeout + yym189 := z.EncBinary() + _ = yym189 if false { - } else if z.HasExtensions() && z.EncExt(yy185) { - } else if !yym186 && z.IsJSONHandle() { - z.EncJSONMarshal(yy185) + } else if z.HasExtensions() && z.EncExt(yy188) { + } else if !yym189 && z.IsJSONHandle() { + z.EncJSONMarshal(yy188) } else { - z.EncFallback(yy185) + z.EncFallback(yy188) } } else { r.EncodeNil() } } else { - if yyq2[55] { + if yyq2[56] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("runtimeRequestTimeout")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy187 := &x.RuntimeRequestTimeout - yym188 := z.EncBinary() - _ = yym188 + yy190 := &x.RuntimeRequestTimeout + yym191 := z.EncBinary() + _ = yym191 if false { - } else if z.HasExtensions() && z.EncExt(yy187) { - } else if !yym188 && z.IsJSONHandle() { - z.EncJSONMarshal(yy187) + } else if z.HasExtensions() && z.EncExt(yy190) { + } else if !yym191 && z.IsJSONHandle() { + z.EncJSONMarshal(yy190) } else { - z.EncFallback(yy187) + z.EncFallback(yy190) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[56] { - yym190 := z.EncBinary() - _ = yym190 + if yyq2[57] { + yym193 := z.EncBinary() + _ = yym193 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktPath)) @@ -2440,12 +2495,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[56] { + if yyq2[57] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("rktPath")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym191 := z.EncBinary() - _ = yym191 + yym194 := z.EncBinary() + _ = yym194 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktPath)) @@ -2454,9 +2509,9 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[57] { - yym193 := z.EncBinary() - _ = yym193 + if yyq2[58] { + yym196 := z.EncBinary() + _ = yym196 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktAPIEndpoint)) @@ -2465,12 +2520,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[57] { + if yyq2[58] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("rktAPIEndpoint")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym194 := z.EncBinary() - _ = yym194 + yym197 := z.EncBinary() + _ = yym197 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktAPIEndpoint)) @@ -2479,9 +2534,9 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[58] { - yym196 := z.EncBinary() - _ = yym196 + if yyq2[59] { + yym199 := z.EncBinary() + _ = yym199 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktStage1Image)) @@ -2490,54 +2545,35 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[58] { + if yyq2[59] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("rktStage1Image")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym197 := z.EncBinary() - _ = yym197 + yym200 := z.EncBinary() + _ = yym200 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RktStage1Image)) } } } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym199 := z.EncBinary() - _ = yym199 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.LockFilePath)) - } - } else { - z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("lockFilePath")) - z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym200 := z.EncBinary() - _ = yym200 - if false { - } else { - r.EncodeString(codecSelferC_UTF81234, string(x.LockFilePath)) - } - } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym202 := z.EncBinary() _ = yym202 if false { } else { - r.EncodeBool(bool(x.ExitOnLockContention)) + r.EncodeString(codecSelferC_UTF81234, string(x.LockFilePath)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("exitOnLockContention")) + r.EncodeString(codecSelferC_UTF81234, string("lockFilePath")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym203 := z.EncBinary() _ = yym203 if false { } else { - r.EncodeBool(bool(x.ExitOnLockContention)) + r.EncodeString(codecSelferC_UTF81234, string(x.LockFilePath)) } } if yyr2 || yy2arr2 { @@ -2546,17 +2582,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym205 if false { } else { - r.EncodeBool(bool(x.ConfigureCBR0)) + r.EncodeBool(bool(x.ExitOnLockContention)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("configureCbr0")) + r.EncodeString(codecSelferC_UTF81234, string("exitOnLockContention")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym206 := z.EncBinary() _ = yym206 if false { } else { - r.EncodeBool(bool(x.ConfigureCBR0)) + r.EncodeBool(bool(x.ExitOnLockContention)) } } if yyr2 || yy2arr2 { @@ -2565,17 +2601,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym208 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) + r.EncodeBool(bool(x.ConfigureCBR0)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("hairpinMode")) + r.EncodeString(codecSelferC_UTF81234, string("configureCbr0")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym209 := z.EncBinary() _ = yym209 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) + r.EncodeBool(bool(x.ConfigureCBR0)) } } if yyr2 || yy2arr2 { @@ -2584,17 +2620,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym211 if false { } else { - r.EncodeBool(bool(x.BabysitDaemons)) + r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("babysitDaemons")) + r.EncodeString(codecSelferC_UTF81234, string("hairpinMode")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym212 := z.EncBinary() _ = yym212 if false { } else { - r.EncodeBool(bool(x.BabysitDaemons)) + r.EncodeString(codecSelferC_UTF81234, string(x.HairpinMode)) } } if yyr2 || yy2arr2 { @@ -2603,17 +2639,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym214 if false { } else { - r.EncodeInt(int64(x.MaxPods)) + r.EncodeBool(bool(x.BabysitDaemons)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("maxPods")) + r.EncodeString(codecSelferC_UTF81234, string("babysitDaemons")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym215 := z.EncBinary() _ = yym215 if false { } else { - r.EncodeInt(int64(x.MaxPods)) + r.EncodeBool(bool(x.BabysitDaemons)) } } if yyr2 || yy2arr2 { @@ -2622,17 +2658,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym217 if false { } else { - r.EncodeInt(int64(x.NvidiaGPUs)) + r.EncodeInt(int64(x.MaxPods)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("nvidiaGPUs")) + r.EncodeString(codecSelferC_UTF81234, string("maxPods")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym218 := z.EncBinary() _ = yym218 if false { } else { - r.EncodeInt(int64(x.NvidiaGPUs)) + r.EncodeInt(int64(x.MaxPods)) } } if yyr2 || yy2arr2 { @@ -2641,17 +2677,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym220 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) + r.EncodeInt(int64(x.NvidiaGPUs)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("dockerExecHandlerName")) + r.EncodeString(codecSelferC_UTF81234, string("nvidiaGPUs")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym221 := z.EncBinary() _ = yym221 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) + r.EncodeInt(int64(x.NvidiaGPUs)) } } if yyr2 || yy2arr2 { @@ -2660,17 +2696,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym223 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) + r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("podCIDR")) + r.EncodeString(codecSelferC_UTF81234, string("dockerExecHandlerName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym224 := z.EncBinary() _ = yym224 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) + r.EncodeString(codecSelferC_UTF81234, string(x.DockerExecHandlerName)) } } if yyr2 || yy2arr2 { @@ -2679,17 +2715,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym226 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) + r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("resolvConf")) + r.EncodeString(codecSelferC_UTF81234, string("podCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym227 := z.EncBinary() _ = yym227 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) + r.EncodeString(codecSelferC_UTF81234, string(x.PodCIDR)) } } if yyr2 || yy2arr2 { @@ -2698,17 +2734,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym229 if false { } else { - r.EncodeBool(bool(x.CPUCFSQuota)) + r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("cpuCFSQuota")) + r.EncodeString(codecSelferC_UTF81234, string("resolvConf")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym230 := z.EncBinary() _ = yym230 if false { } else { - r.EncodeBool(bool(x.CPUCFSQuota)) + r.EncodeString(codecSelferC_UTF81234, string(x.ResolverConfig)) } } if yyr2 || yy2arr2 { @@ -2717,17 +2753,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym232 if false { } else { - r.EncodeBool(bool(x.Containerized)) + r.EncodeBool(bool(x.CPUCFSQuota)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("containerized")) + r.EncodeString(codecSelferC_UTF81234, string("cpuCFSQuota")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym233 := z.EncBinary() _ = yym233 if false { } else { - r.EncodeBool(bool(x.Containerized)) + r.EncodeBool(bool(x.CPUCFSQuota)) } } if yyr2 || yy2arr2 { @@ -2736,17 +2772,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym235 if false { } else { - r.EncodeUint(uint64(x.MaxOpenFiles)) + r.EncodeBool(bool(x.Containerized)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("maxOpenFiles")) + r.EncodeString(codecSelferC_UTF81234, string("containerized")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym236 := z.EncBinary() _ = yym236 if false { } else { - r.EncodeUint(uint64(x.MaxOpenFiles)) + r.EncodeBool(bool(x.Containerized)) } } if yyr2 || yy2arr2 { @@ -2755,17 +2791,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym238 if false { } else { - r.EncodeBool(bool(x.ReconcileCIDR)) + r.EncodeInt(int64(x.MaxOpenFiles)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("reconcileCIDR")) + r.EncodeString(codecSelferC_UTF81234, string("maxOpenFiles")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym239 := z.EncBinary() _ = yym239 if false { } else { - r.EncodeBool(bool(x.ReconcileCIDR)) + r.EncodeInt(int64(x.MaxOpenFiles)) } } if yyr2 || yy2arr2 { @@ -2774,17 +2810,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym241 if false { } else { - r.EncodeBool(bool(x.RegisterSchedulable)) + r.EncodeBool(bool(x.ReconcileCIDR)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("registerSchedulable")) + r.EncodeString(codecSelferC_UTF81234, string("reconcileCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym242 := z.EncBinary() _ = yym242 if false { } else { - r.EncodeBool(bool(x.RegisterSchedulable)) + r.EncodeBool(bool(x.ReconcileCIDR)) } } if yyr2 || yy2arr2 { @@ -2793,17 +2829,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym244 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) + r.EncodeBool(bool(x.RegisterSchedulable)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("contentType")) + r.EncodeString(codecSelferC_UTF81234, string("registerSchedulable")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym245 := z.EncBinary() _ = yym245 if false { } else { - r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) + r.EncodeBool(bool(x.RegisterSchedulable)) } } if yyr2 || yy2arr2 { @@ -2812,17 +2848,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym247 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) + r.EncodeString(codecSelferC_UTF81234, string("contentType")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym248 := z.EncBinary() _ = yym248 if false { } else { - r.EncodeFloat32(float32(x.KubeAPIQPS)) + r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) } } if yyr2 || yy2arr2 { @@ -2831,17 +2867,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym250 if false { } else { - r.EncodeInt(int64(x.KubeAPIBurst)) + r.EncodeInt(int64(x.KubeAPIQPS)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("kubeAPIBurst")) + r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym251 := z.EncBinary() _ = yym251 if false { } else { - r.EncodeInt(int64(x.KubeAPIBurst)) + r.EncodeInt(int64(x.KubeAPIQPS)) } } if yyr2 || yy2arr2 { @@ -2850,17 +2886,17 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym253 if false { } else { - r.EncodeBool(bool(x.SerializeImagePulls)) + r.EncodeInt(int64(x.KubeAPIBurst)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("serializeImagePulls")) + r.EncodeString(codecSelferC_UTF81234, string("kubeAPIBurst")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym254 := z.EncBinary() _ = yym254 if false { } else { - r.EncodeBool(bool(x.SerializeImagePulls)) + r.EncodeInt(int64(x.KubeAPIBurst)) } } if yyr2 || yy2arr2 { @@ -2869,57 +2905,76 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { _ = yym256 if false { } else { - r.EncodeBool(bool(x.ExperimentalFlannelOverlay)) + r.EncodeBool(bool(x.SerializeImagePulls)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("experimentalFlannelOverlay")) + r.EncodeString(codecSelferC_UTF81234, string("serializeImagePulls")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym257 := z.EncBinary() _ = yym257 if false { + } else { + r.EncodeBool(bool(x.SerializeImagePulls)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym259 := z.EncBinary() + _ = yym259 + if false { + } else { + r.EncodeBool(bool(x.ExperimentalFlannelOverlay)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("experimentalFlannelOverlay")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym260 := z.EncBinary() + _ = yym260 + if false { } else { r.EncodeBool(bool(x.ExperimentalFlannelOverlay)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[79] { - yy259 := &x.OutOfDiskTransitionFrequency - yym260 := z.EncBinary() - _ = yym260 + if yyq2[80] { + yy262 := &x.OutOfDiskTransitionFrequency + yym263 := z.EncBinary() + _ = yym263 if false { - } else if z.HasExtensions() && z.EncExt(yy259) { - } else if !yym260 && z.IsJSONHandle() { - z.EncJSONMarshal(yy259) + } else if z.HasExtensions() && z.EncExt(yy262) { + } else if !yym263 && z.IsJSONHandle() { + z.EncJSONMarshal(yy262) } else { - z.EncFallback(yy259) + z.EncFallback(yy262) } } else { r.EncodeNil() } } else { - if yyq2[79] { + if yyq2[80] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("outOfDiskTransitionFrequency")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy261 := &x.OutOfDiskTransitionFrequency - yym262 := z.EncBinary() - _ = yym262 + yy264 := &x.OutOfDiskTransitionFrequency + yym265 := z.EncBinary() + _ = yym265 if false { - } else if z.HasExtensions() && z.EncExt(yy261) { - } else if !yym262 && z.IsJSONHandle() { - z.EncJSONMarshal(yy261) + } else if z.HasExtensions() && z.EncExt(yy264) { + } else if !yym265 && z.IsJSONHandle() { + z.EncJSONMarshal(yy264) } else { - z.EncFallback(yy261) + z.EncFallback(yy264) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[80] { - yym264 := z.EncBinary() - _ = yym264 + if yyq2[81] { + yym267 := z.EncBinary() + _ = yym267 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NodeIP)) @@ -2928,12 +2983,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[80] { + if yyq2[81] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeIP")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym265 := z.EncBinary() - _ = yym265 + yym268 := z.EncBinary() + _ = yym268 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NodeIP)) @@ -2945,8 +3000,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { if x.NodeLabels == nil { r.EncodeNil() } else { - yym267 := z.EncBinary() - _ = yym267 + yym270 := z.EncBinary() + _ = yym270 if false { } else { z.F.EncMapStringStringV(x.NodeLabels, false, e) @@ -2959,8 +3014,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { if x.NodeLabels == nil { r.EncodeNil() } else { - yym268 := z.EncBinary() - _ = yym268 + yym271 := z.EncBinary() + _ = yym271 if false { } else { z.F.EncMapStringStringV(x.NodeLabels, false, e) @@ -2969,8 +3024,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym270 := z.EncBinary() - _ = yym270 + yym273 := z.EncBinary() + _ = yym273 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NonMasqueradeCIDR)) @@ -2979,8 +3034,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nonMasqueradeCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym271 := z.EncBinary() - _ = yym271 + yym274 := z.EncBinary() + _ = yym274 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.NonMasqueradeCIDR)) @@ -2988,8 +3043,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym273 := z.EncBinary() - _ = yym273 + yym276 := z.EncBinary() + _ = yym276 if false { } else { r.EncodeBool(bool(x.EnableCustomMetrics)) @@ -2998,8 +3053,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("enableCustomMetrics")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym274 := z.EncBinary() - _ = yym274 + yym277 := z.EncBinary() + _ = yym277 if false { } else { r.EncodeBool(bool(x.EnableCustomMetrics)) @@ -3007,9 +3062,9 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[84] { - yym276 := z.EncBinary() - _ = yym276 + if yyq2[85] { + yym279 := z.EncBinary() + _ = yym279 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionHard)) @@ -3018,12 +3073,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[84] { + if yyq2[85] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("evictionHard")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym277 := z.EncBinary() - _ = yym277 + yym280 := z.EncBinary() + _ = yym280 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionHard)) @@ -3032,9 +3087,9 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[85] { - yym279 := z.EncBinary() - _ = yym279 + if yyq2[86] { + yym282 := z.EncBinary() + _ = yym282 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionSoft)) @@ -3043,12 +3098,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[85] { + if yyq2[86] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("evictionSoft")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym280 := z.EncBinary() - _ = yym280 + yym283 := z.EncBinary() + _ = yym283 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionSoft)) @@ -3057,9 +3112,9 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[86] { - yym282 := z.EncBinary() - _ = yym282 + if yyq2[87] { + yym285 := z.EncBinary() + _ = yym285 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionSoftGracePeriod)) @@ -3068,12 +3123,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[86] { + if yyq2[87] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("evictionSoftGracePeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym283 := z.EncBinary() - _ = yym283 + yym286 := z.EncBinary() + _ = yym286 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.EvictionSoftGracePeriod)) @@ -3082,42 +3137,42 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[87] { - yy285 := &x.EvictionPressureTransitionPeriod - yym286 := z.EncBinary() - _ = yym286 + if yyq2[88] { + yy288 := &x.EvictionPressureTransitionPeriod + yym289 := z.EncBinary() + _ = yym289 if false { - } else if z.HasExtensions() && z.EncExt(yy285) { - } else if !yym286 && z.IsJSONHandle() { - z.EncJSONMarshal(yy285) + } else if z.HasExtensions() && z.EncExt(yy288) { + } else if !yym289 && z.IsJSONHandle() { + z.EncJSONMarshal(yy288) } else { - z.EncFallback(yy285) + z.EncFallback(yy288) } } else { r.EncodeNil() } } else { - if yyq2[87] { + if yyq2[88] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("evictionPressureTransitionPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy287 := &x.EvictionPressureTransitionPeriod - yym288 := z.EncBinary() - _ = yym288 + yy290 := &x.EvictionPressureTransitionPeriod + yym291 := z.EncBinary() + _ = yym291 if false { - } else if z.HasExtensions() && z.EncExt(yy287) { - } else if !yym288 && z.IsJSONHandle() { - z.EncJSONMarshal(yy287) + } else if z.HasExtensions() && z.EncExt(yy290) { + } else if !yym291 && z.IsJSONHandle() { + z.EncJSONMarshal(yy290) } else { - z.EncFallback(yy287) + z.EncFallback(yy290) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[88] { - yym290 := z.EncBinary() - _ = yym290 + if yyq2[89] { + yym293 := z.EncBinary() + _ = yym293 if false { } else { r.EncodeInt(int64(x.EvictionMaxPodGracePeriod)) @@ -3126,12 +3181,12 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { r.EncodeInt(0) } } else { - if yyq2[88] { + if yyq2[89] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("evictionMaxPodGracePeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym291 := z.EncBinary() - _ = yym291 + yym294 := z.EncBinary() + _ = yym294 if false { } else { r.EncodeInt(int64(x.EvictionMaxPodGracePeriod)) @@ -3140,8 +3195,33 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym293 := z.EncBinary() - _ = yym293 + if yyq2[90] { + yym296 := z.EncBinary() + _ = yym296 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.EvictionMinimumReclaim)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[90] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("evictionMinimumReclaim")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym297 := z.EncBinary() + _ = yym297 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.EvictionMinimumReclaim)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym299 := z.EncBinary() + _ = yym299 if false { } else { r.EncodeInt(int64(x.PodsPerCore)) @@ -3150,8 +3230,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("podsPerCore")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym294 := z.EncBinary() - _ = yym294 + yym300 := z.EncBinary() + _ = yym300 if false { } else { r.EncodeInt(int64(x.PodsPerCore)) @@ -3159,8 +3239,8 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym296 := z.EncBinary() - _ = yym296 + yym302 := z.EncBinary() + _ = yym302 if false { } else { r.EncodeBool(bool(x.EnableControllerAttachDetach)) @@ -3169,13 +3249,121 @@ func (x *KubeletConfiguration) CodecEncodeSelf(e *codec1978.Encoder) { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("enableControllerAttachDetach")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym297 := z.EncBinary() - _ = yym297 + yym303 := z.EncBinary() + _ = yym303 if false { } else { r.EncodeBool(bool(x.EnableControllerAttachDetach)) } } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.SystemReserved == nil { + r.EncodeNil() + } else { + yym305 := z.EncBinary() + _ = yym305 + if false { + } else if z.HasExtensions() && z.EncExt(x.SystemReserved) { + } else { + h.encconfig_ConfigurationMap((pkg2_config.ConfigurationMap)(x.SystemReserved), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("systemReserved")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.SystemReserved == nil { + r.EncodeNil() + } else { + yym306 := z.EncBinary() + _ = yym306 + if false { + } else if z.HasExtensions() && z.EncExt(x.SystemReserved) { + } else { + h.encconfig_ConfigurationMap((pkg2_config.ConfigurationMap)(x.SystemReserved), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.KubeReserved == nil { + r.EncodeNil() + } else { + yym308 := z.EncBinary() + _ = yym308 + if false { + } else if z.HasExtensions() && z.EncExt(x.KubeReserved) { + } else { + h.encconfig_ConfigurationMap((pkg2_config.ConfigurationMap)(x.KubeReserved), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kubeReserved")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.KubeReserved == nil { + r.EncodeNil() + } else { + yym309 := z.EncBinary() + _ = yym309 + if false { + } else if z.HasExtensions() && z.EncExt(x.KubeReserved) { + } else { + h.encconfig_ConfigurationMap((pkg2_config.ConfigurationMap)(x.KubeReserved), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[95] { + yym311 := z.EncBinary() + _ = yym311 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[95] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym312 := z.EncBinary() + _ = yym312 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[96] { + yym314 := z.EncBinary() + _ = yym314 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[96] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym315 := z.EncBinary() + _ = yym315 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { @@ -3316,21 +3504,21 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.Port = 0 } else { - x.Port = uint(r.DecodeUint(codecSelferBitsize1234)) + x.Port = int32(r.DecodeInt(32)) } case "readOnlyPort": if r.TryDecodeAsNil() { x.ReadOnlyPort = 0 } else { - x.ReadOnlyPort = uint(r.DecodeUint(codecSelferBitsize1234)) + x.ReadOnlyPort = int32(r.DecodeInt(32)) } - case "tLSCertFile": + case "tlsCertFile": if r.TryDecodeAsNil() { x.TLSCertFile = "" } else { x.TLSCertFile = string(r.DecodeString()) } - case "tLSPrivateKeyFile": + case "tlsPrivateKeyFile": if r.TryDecodeAsNil() { x.TLSPrivateKeyFile = "" } else { @@ -3380,27 +3568,45 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode } case "hostNetworkSources": if r.TryDecodeAsNil() { - x.HostNetworkSources = "" + x.HostNetworkSources = nil } else { - x.HostNetworkSources = string(r.DecodeString()) + yyv26 := &x.HostNetworkSources + yym27 := z.DecBinary() + _ = yym27 + if false { + } else { + z.F.DecSliceStringX(yyv26, false, d) + } } case "hostPIDSources": if r.TryDecodeAsNil() { - x.HostPIDSources = "" + x.HostPIDSources = nil } else { - x.HostPIDSources = string(r.DecodeString()) + yyv28 := &x.HostPIDSources + yym29 := z.DecBinary() + _ = yym29 + if false { + } else { + z.F.DecSliceStringX(yyv28, false, d) + } } case "hostIPCSources": if r.TryDecodeAsNil() { - x.HostIPCSources = "" + x.HostIPCSources = nil } else { - x.HostIPCSources = string(r.DecodeString()) + yyv30 := &x.HostIPCSources + yym31 := z.DecBinary() + _ = yym31 + if false { + } else { + z.F.DecSliceStringX(yyv30, false, d) + } } case "registryPullQPS": if r.TryDecodeAsNil() { x.RegistryPullQPS = 0 } else { - x.RegistryPullQPS = float64(r.DecodeFloat(false)) + x.RegistryPullQPS = int32(r.DecodeInt(32)) } case "registryBurst": if r.TryDecodeAsNil() { @@ -3412,7 +3618,7 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.EventRecordQPS = 0 } else { - x.EventRecordQPS = float32(r.DecodeFloat(true)) + x.EventRecordQPS = int32(r.DecodeInt(32)) } case "eventBurst": if r.TryDecodeAsNil() { @@ -3430,15 +3636,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.MinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv34 := &x.MinimumGCAge - yym35 := z.DecBinary() - _ = yym35 + yyv37 := &x.MinimumGCAge + yym38 := z.DecBinary() + _ = yym38 if false { - } else if z.HasExtensions() && z.DecExt(yyv34) { - } else if !yym35 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv34) + } else if z.HasExtensions() && z.DecExt(yyv37) { + } else if !yym38 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv37) } else { - z.DecFallback(yyv34, false) + z.DecFallback(yyv37, false) } } case "maxPerPodContainerCount": @@ -3457,7 +3663,7 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.CAdvisorPort = 0 } else { - x.CAdvisorPort = uint(r.DecodeUint(codecSelferBitsize1234)) + x.CAdvisorPort = int32(r.DecodeInt(32)) } case "healthzPort": if r.TryDecodeAsNil() { @@ -3505,45 +3711,45 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.StreamingConnectionIdleTimeout = pkg1_unversioned.Duration{} } else { - yyv46 := &x.StreamingConnectionIdleTimeout - yym47 := z.DecBinary() - _ = yym47 + yyv49 := &x.StreamingConnectionIdleTimeout + yym50 := z.DecBinary() + _ = yym50 if false { - } else if z.HasExtensions() && z.DecExt(yyv46) { - } else if !yym47 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv46) + } else if z.HasExtensions() && z.DecExt(yyv49) { + } else if !yym50 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv49) } else { - z.DecFallback(yyv46, false) + z.DecFallback(yyv49, false) } } case "nodeStatusUpdateFrequency": if r.TryDecodeAsNil() { x.NodeStatusUpdateFrequency = pkg1_unversioned.Duration{} } else { - yyv48 := &x.NodeStatusUpdateFrequency - yym49 := z.DecBinary() - _ = yym49 + yyv51 := &x.NodeStatusUpdateFrequency + yym52 := z.DecBinary() + _ = yym52 if false { - } else if z.HasExtensions() && z.DecExt(yyv48) { - } else if !yym49 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv48) + } else if z.HasExtensions() && z.DecExt(yyv51) { + } else if !yym52 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv51) } else { - z.DecFallback(yyv48, false) + z.DecFallback(yyv51, false) } } case "imageMinimumGCAge": if r.TryDecodeAsNil() { x.ImageMinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv50 := &x.ImageMinimumGCAge - yym51 := z.DecBinary() - _ = yym51 + yyv53 := &x.ImageMinimumGCAge + yym54 := z.DecBinary() + _ = yym54 if false { - } else if z.HasExtensions() && z.DecExt(yyv50) { - } else if !yym51 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv50) + } else if z.HasExtensions() && z.DecExt(yyv53) { + } else if !yym54 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv53) } else { - z.DecFallback(yyv50, false) + z.DecFallback(yyv53, false) } } case "imageGCHighThresholdPercent": @@ -3568,15 +3774,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.VolumeStatsAggPeriod = pkg1_unversioned.Duration{} } else { - yyv55 := &x.VolumeStatsAggPeriod - yym56 := z.DecBinary() - _ = yym56 + yyv58 := &x.VolumeStatsAggPeriod + yym59 := z.DecBinary() + _ = yym59 if false { - } else if z.HasExtensions() && z.DecExt(yyv55) { - } else if !yym56 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv55) + } else if z.HasExtensions() && z.DecExt(yyv58) { + } else if !yym59 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv58) } else { - z.DecFallback(yyv55, false) + z.DecFallback(yyv58, false) } } case "networkPluginName": @@ -3615,13 +3821,19 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode } else { x.KubeletCgroups = string(r.DecodeString()) } + case "CgroupsPerQOS": + if r.TryDecodeAsNil() { + x.CgroupsPerQOS = false + } else { + x.CgroupsPerQOS = bool(r.DecodeBool()) + } case "runtimeCgroups": if r.TryDecodeAsNil() { x.RuntimeCgroups = "" } else { x.RuntimeCgroups = string(r.DecodeString()) } - case "systemContainer": + case "systemCgroups": if r.TryDecodeAsNil() { x.SystemCgroups = "" } else { @@ -3643,15 +3855,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.RuntimeRequestTimeout = pkg1_unversioned.Duration{} } else { - yyv67 := &x.RuntimeRequestTimeout - yym68 := z.DecBinary() - _ = yym68 + yyv71 := &x.RuntimeRequestTimeout + yym72 := z.DecBinary() + _ = yym72 if false { - } else if z.HasExtensions() && z.DecExt(yyv67) { - } else if !yym68 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv67) + } else if z.HasExtensions() && z.DecExt(yyv71) { + } else if !yym72 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv71) } else { - z.DecFallback(yyv67, false) + z.DecFallback(yyv71, false) } } case "rktPath": @@ -3748,7 +3960,7 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.MaxOpenFiles = 0 } else { - x.MaxOpenFiles = uint64(r.DecodeUint(64)) + x.MaxOpenFiles = int64(r.DecodeInt(64)) } case "reconcileCIDR": if r.TryDecodeAsNil() { @@ -3772,7 +3984,7 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.KubeAPIQPS = 0 } else { - x.KubeAPIQPS = float32(r.DecodeFloat(true)) + x.KubeAPIQPS = int32(r.DecodeInt(32)) } case "kubeAPIBurst": if r.TryDecodeAsNil() { @@ -3796,15 +4008,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.OutOfDiskTransitionFrequency = pkg1_unversioned.Duration{} } else { - yyv92 := &x.OutOfDiskTransitionFrequency - yym93 := z.DecBinary() - _ = yym93 + yyv96 := &x.OutOfDiskTransitionFrequency + yym97 := z.DecBinary() + _ = yym97 if false { - } else if z.HasExtensions() && z.DecExt(yyv92) { - } else if !yym93 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv92) + } else if z.HasExtensions() && z.DecExt(yyv96) { + } else if !yym97 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv96) } else { - z.DecFallback(yyv92, false) + z.DecFallback(yyv96, false) } } case "nodeIP": @@ -3817,12 +4029,12 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.NodeLabels = nil } else { - yyv95 := &x.NodeLabels - yym96 := z.DecBinary() - _ = yym96 + yyv99 := &x.NodeLabels + yym100 := z.DecBinary() + _ = yym100 if false { } else { - z.F.DecMapStringStringX(yyv95, false, d) + z.F.DecMapStringStringX(yyv99, false, d) } } case "nonMasqueradeCIDR": @@ -3859,15 +4071,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode if r.TryDecodeAsNil() { x.EvictionPressureTransitionPeriod = pkg1_unversioned.Duration{} } else { - yyv102 := &x.EvictionPressureTransitionPeriod - yym103 := z.DecBinary() - _ = yym103 + yyv106 := &x.EvictionPressureTransitionPeriod + yym107 := z.DecBinary() + _ = yym107 if false { - } else if z.HasExtensions() && z.DecExt(yyv102) { - } else if !yym103 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv102) + } else if z.HasExtensions() && z.DecExt(yyv106) { + } else if !yym107 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv106) } else { - z.DecFallback(yyv102, false) + z.DecFallback(yyv106, false) } } case "evictionMaxPodGracePeriod": @@ -3876,6 +4088,12 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode } else { x.EvictionMaxPodGracePeriod = int32(r.DecodeInt(32)) } + case "evictionMinimumReclaim": + if r.TryDecodeAsNil() { + x.EvictionMinimumReclaim = "" + } else { + x.EvictionMinimumReclaim = string(r.DecodeString()) + } case "podsPerCore": if r.TryDecodeAsNil() { x.PodsPerCore = 0 @@ -3888,6 +4106,44 @@ func (x *KubeletConfiguration) codecDecodeSelfFromMap(l int, d *codec1978.Decode } else { x.EnableControllerAttachDetach = bool(r.DecodeBool()) } + case "systemReserved": + if r.TryDecodeAsNil() { + x.SystemReserved = nil + } else { + yyv112 := &x.SystemReserved + yym113 := z.DecBinary() + _ = yym113 + if false { + } else if z.HasExtensions() && z.DecExt(yyv112) { + } else { + h.decconfig_ConfigurationMap((*pkg2_config.ConfigurationMap)(yyv112), d) + } + } + case "kubeReserved": + if r.TryDecodeAsNil() { + x.KubeReserved = nil + } else { + yyv114 := &x.KubeReserved + yym115 := z.DecBinary() + _ = yym115 + if false { + } else if z.HasExtensions() && z.DecExt(yyv114) { + } else { + h.decconfig_ConfigurationMap((*pkg2_config.ConfigurationMap)(yyv114), d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 @@ -3899,16 +4155,16 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj107 int - var yyb107 bool - var yyhl107 bool = l >= 0 - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + var yyj118 int + var yyb118 bool + var yyhl118 bool = l >= 0 + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3918,13 +4174,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Config = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3932,24 +4188,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.SyncFrequency = pkg1_unversioned.Duration{} } else { - yyv109 := &x.SyncFrequency - yym110 := z.DecBinary() - _ = yym110 + yyv120 := &x.SyncFrequency + yym121 := z.DecBinary() + _ = yym121 if false { - } else if z.HasExtensions() && z.DecExt(yyv109) { - } else if !yym110 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv109) + } else if z.HasExtensions() && z.DecExt(yyv120) { + } else if !yym121 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv120) } else { - z.DecFallback(yyv109, false) + z.DecFallback(yyv120, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3957,24 +4213,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.FileCheckFrequency = pkg1_unversioned.Duration{} } else { - yyv111 := &x.FileCheckFrequency - yym112 := z.DecBinary() - _ = yym112 + yyv122 := &x.FileCheckFrequency + yym123 := z.DecBinary() + _ = yym123 if false { - } else if z.HasExtensions() && z.DecExt(yyv111) { - } else if !yym112 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv111) + } else if z.HasExtensions() && z.DecExt(yyv122) { + } else if !yym123 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv122) } else { - z.DecFallback(yyv111, false) + z.DecFallback(yyv122, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -3982,24 +4238,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.HTTPCheckFrequency = pkg1_unversioned.Duration{} } else { - yyv113 := &x.HTTPCheckFrequency - yym114 := z.DecBinary() - _ = yym114 + yyv124 := &x.HTTPCheckFrequency + yym125 := z.DecBinary() + _ = yym125 if false { - } else if z.HasExtensions() && z.DecExt(yyv113) { - } else if !yym114 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv113) + } else if z.HasExtensions() && z.DecExt(yyv124) { + } else if !yym125 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv124) } else { - z.DecFallback(yyv113, false) + z.DecFallback(yyv124, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4009,13 +4265,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ManifestURL = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4025,13 +4281,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ManifestURLHeader = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4041,13 +4297,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableServer = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4057,13 +4313,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Address = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4071,15 +4327,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.Port = 0 } else { - x.Port = uint(r.DecodeUint(codecSelferBitsize1234)) + x.Port = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4087,15 +4343,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.ReadOnlyPort = 0 } else { - x.ReadOnlyPort = uint(r.DecodeUint(codecSelferBitsize1234)) + x.ReadOnlyPort = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4105,13 +4361,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.TLSCertFile = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4121,13 +4377,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.TLSPrivateKeyFile = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4137,13 +4393,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CertDirectory = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4153,13 +4409,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HostnameOverride = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4169,13 +4425,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.PodInfraContainerImage = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4185,13 +4441,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.DockerEndpoint = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4201,13 +4457,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RootDirectory = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4217,13 +4473,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.SeccompProfileRoot = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4233,61 +4489,79 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.AllowPrivileged = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.HostNetworkSources = "" + x.HostNetworkSources = nil } else { - x.HostNetworkSources = string(r.DecodeString()) + yyv141 := &x.HostNetworkSources + yym142 := z.DecBinary() + _ = yym142 + if false { + } else { + z.F.DecSliceStringX(yyv141, false, d) + } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.HostPIDSources = "" + x.HostPIDSources = nil } else { - x.HostPIDSources = string(r.DecodeString()) + yyv143 := &x.HostPIDSources + yym144 := z.DecBinary() + _ = yym144 + if false { + } else { + z.F.DecSliceStringX(yyv143, false, d) + } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { - x.HostIPCSources = "" + x.HostIPCSources = nil } else { - x.HostIPCSources = string(r.DecodeString()) + yyv145 := &x.HostIPCSources + yym146 := z.DecBinary() + _ = yym146 + if false { + } else { + z.F.DecSliceStringX(yyv145, false, d) + } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4295,15 +4569,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.RegistryPullQPS = 0 } else { - x.RegistryPullQPS = float64(r.DecodeFloat(false)) + x.RegistryPullQPS = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4313,13 +4587,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegistryBurst = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4327,15 +4601,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.EventRecordQPS = 0 } else { - x.EventRecordQPS = float32(r.DecodeFloat(true)) + x.EventRecordQPS = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4345,13 +4619,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EventBurst = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4361,13 +4635,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableDebuggingHandlers = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4375,24 +4649,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.MinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv138 := &x.MinimumGCAge - yym139 := z.DecBinary() - _ = yym139 + yyv152 := &x.MinimumGCAge + yym153 := z.DecBinary() + _ = yym153 if false { - } else if z.HasExtensions() && z.DecExt(yyv138) { - } else if !yym139 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv138) + } else if z.HasExtensions() && z.DecExt(yyv152) { + } else if !yym153 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv152) } else { - z.DecFallback(yyv138, false) + z.DecFallback(yyv152, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4402,13 +4676,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxPerPodContainerCount = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4418,13 +4692,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxContainerCount = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4432,15 +4706,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.CAdvisorPort = 0 } else { - x.CAdvisorPort = uint(r.DecodeUint(codecSelferBitsize1234)) + x.CAdvisorPort = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4450,13 +4724,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HealthzPort = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4466,13 +4740,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HealthzBindAddress = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4482,13 +4756,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.OOMScoreAdj = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4498,13 +4772,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegisterNode = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4514,13 +4788,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ClusterDomain = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4530,13 +4804,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MasterServiceNamespace = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4546,13 +4820,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ClusterDNS = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4560,24 +4834,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.StreamingConnectionIdleTimeout = pkg1_unversioned.Duration{} } else { - yyv150 := &x.StreamingConnectionIdleTimeout - yym151 := z.DecBinary() - _ = yym151 + yyv164 := &x.StreamingConnectionIdleTimeout + yym165 := z.DecBinary() + _ = yym165 if false { - } else if z.HasExtensions() && z.DecExt(yyv150) { - } else if !yym151 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv150) + } else if z.HasExtensions() && z.DecExt(yyv164) { + } else if !yym165 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv164) } else { - z.DecFallback(yyv150, false) + z.DecFallback(yyv164, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4585,24 +4859,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.NodeStatusUpdateFrequency = pkg1_unversioned.Duration{} } else { - yyv152 := &x.NodeStatusUpdateFrequency - yym153 := z.DecBinary() - _ = yym153 + yyv166 := &x.NodeStatusUpdateFrequency + yym167 := z.DecBinary() + _ = yym167 if false { - } else if z.HasExtensions() && z.DecExt(yyv152) { - } else if !yym153 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv152) + } else if z.HasExtensions() && z.DecExt(yyv166) { + } else if !yym167 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv166) } else { - z.DecFallback(yyv152, false) + z.DecFallback(yyv166, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4610,24 +4884,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.ImageMinimumGCAge = pkg1_unversioned.Duration{} } else { - yyv154 := &x.ImageMinimumGCAge - yym155 := z.DecBinary() - _ = yym155 + yyv168 := &x.ImageMinimumGCAge + yym169 := z.DecBinary() + _ = yym169 if false { - } else if z.HasExtensions() && z.DecExt(yyv154) { - } else if !yym155 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv154) + } else if z.HasExtensions() && z.DecExt(yyv168) { + } else if !yym169 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv168) } else { - z.DecFallback(yyv154, false) + z.DecFallback(yyv168, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4637,13 +4911,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ImageGCHighThresholdPercent = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4653,13 +4927,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ImageGCLowThresholdPercent = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4669,13 +4943,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.LowDiskSpaceThresholdMB = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4683,24 +4957,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.VolumeStatsAggPeriod = pkg1_unversioned.Duration{} } else { - yyv159 := &x.VolumeStatsAggPeriod - yym160 := z.DecBinary() - _ = yym160 + yyv173 := &x.VolumeStatsAggPeriod + yym174 := z.DecBinary() + _ = yym174 if false { - } else if z.HasExtensions() && z.DecExt(yyv159) { - } else if !yym160 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv159) + } else if z.HasExtensions() && z.DecExt(yyv173) { + } else if !yym174 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv173) } else { - z.DecFallback(yyv159, false) + z.DecFallback(yyv173, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4710,13 +4984,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NetworkPluginName = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4726,13 +5000,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NetworkPluginDir = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4742,13 +5016,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.VolumePluginDir = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4758,13 +5032,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CloudProvider = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4774,13 +5048,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CloudConfigFile = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4790,13 +5064,29 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.KubeletCgroups = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.CgroupsPerQOS = false + } else { + x.CgroupsPerQOS = bool(r.DecodeBool()) + } + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4806,13 +5096,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RuntimeCgroups = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4822,13 +5112,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.SystemCgroups = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4838,13 +5128,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CgroupRoot = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4854,13 +5144,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ContainerRuntime = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4868,24 +5158,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.RuntimeRequestTimeout = pkg1_unversioned.Duration{} } else { - yyv171 := &x.RuntimeRequestTimeout - yym172 := z.DecBinary() - _ = yym172 + yyv186 := &x.RuntimeRequestTimeout + yym187 := z.DecBinary() + _ = yym187 if false { - } else if z.HasExtensions() && z.DecExt(yyv171) { - } else if !yym172 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv171) + } else if z.HasExtensions() && z.DecExt(yyv186) { + } else if !yym187 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv186) } else { - z.DecFallback(yyv171, false) + z.DecFallback(yyv186, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4895,13 +5185,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RktPath = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4911,13 +5201,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RktAPIEndpoint = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4927,13 +5217,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RktStage1Image = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4943,13 +5233,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.LockFilePath = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4959,13 +5249,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ExitOnLockContention = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4975,13 +5265,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ConfigureCBR0 = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -4991,13 +5281,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.HairpinMode = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5007,13 +5297,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.BabysitDaemons = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5023,13 +5313,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.MaxPods = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5039,13 +5329,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NvidiaGPUs = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5055,13 +5345,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.DockerExecHandlerName = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5071,13 +5361,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.PodCIDR = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5087,13 +5377,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ResolverConfig = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5103,13 +5393,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.CPUCFSQuota = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5119,13 +5409,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.Containerized = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5133,15 +5423,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.MaxOpenFiles = 0 } else { - x.MaxOpenFiles = uint64(r.DecodeUint(64)) + x.MaxOpenFiles = int64(r.DecodeInt(64)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5151,13 +5441,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ReconcileCIDR = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5167,13 +5457,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.RegisterSchedulable = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5183,13 +5473,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ContentType = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5197,15 +5487,15 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.KubeAPIQPS = 0 } else { - x.KubeAPIQPS = float32(r.DecodeFloat(true)) + x.KubeAPIQPS = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5215,13 +5505,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.KubeAPIBurst = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5231,13 +5521,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.SerializeImagePulls = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5247,13 +5537,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.ExperimentalFlannelOverlay = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5261,24 +5551,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.OutOfDiskTransitionFrequency = pkg1_unversioned.Duration{} } else { - yyv196 := &x.OutOfDiskTransitionFrequency - yym197 := z.DecBinary() - _ = yym197 + yyv211 := &x.OutOfDiskTransitionFrequency + yym212 := z.DecBinary() + _ = yym212 if false { - } else if z.HasExtensions() && z.DecExt(yyv196) { - } else if !yym197 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv196) + } else if z.HasExtensions() && z.DecExt(yyv211) { + } else if !yym212 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv211) } else { - z.DecFallback(yyv196, false) + z.DecFallback(yyv211, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5288,13 +5578,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NodeIP = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5302,21 +5592,21 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.NodeLabels = nil } else { - yyv199 := &x.NodeLabels - yym200 := z.DecBinary() - _ = yym200 + yyv214 := &x.NodeLabels + yym215 := z.DecBinary() + _ = yym215 if false { } else { - z.F.DecMapStringStringX(yyv199, false, d) + z.F.DecMapStringStringX(yyv214, false, d) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5326,13 +5616,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.NonMasqueradeCIDR = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5342,13 +5632,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableCustomMetrics = bool(r.DecodeBool()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5358,13 +5648,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EvictionHard = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5374,13 +5664,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EvictionSoft = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5390,13 +5680,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EvictionSoftGracePeriod = string(r.DecodeString()) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5404,24 +5694,24 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco if r.TryDecodeAsNil() { x.EvictionPressureTransitionPeriod = pkg1_unversioned.Duration{} } else { - yyv206 := &x.EvictionPressureTransitionPeriod - yym207 := z.DecBinary() - _ = yym207 + yyv221 := &x.EvictionPressureTransitionPeriod + yym222 := z.DecBinary() + _ = yym222 if false { - } else if z.HasExtensions() && z.DecExt(yyv206) { - } else if !yym207 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv206) + } else if z.HasExtensions() && z.DecExt(yyv221) { + } else if !yym222 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv221) } else { - z.DecFallback(yyv206, false) + z.DecFallback(yyv221, false) } } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5431,13 +5721,29 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EvictionMaxPodGracePeriod = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.EvictionMinimumReclaim = "" } else { - yyb107 = r.CheckBreak() + x.EvictionMinimumReclaim = string(r.DecodeString()) } - if yyb107 { + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5447,13 +5753,13 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.PodsPerCore = int32(r.DecodeInt(32)) } - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -5463,18 +5769,96 @@ func (x *KubeletConfiguration) codecDecodeSelfFromArray(l int, d *codec1978.Deco } else { x.EnableControllerAttachDetach = bool(r.DecodeBool()) } + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.SystemReserved = nil + } else { + yyv227 := &x.SystemReserved + yym228 := z.DecBinary() + _ = yym228 + if false { + } else if z.HasExtensions() && z.DecExt(yyv227) { + } else { + h.decconfig_ConfigurationMap((*pkg2_config.ConfigurationMap)(yyv227), d) + } + } + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.KubeReserved = nil + } else { + yyv229 := &x.KubeReserved + yym230 := z.DecBinary() + _ = yym230 + if false { + } else if z.HasExtensions() && z.DecExt(yyv229) { + } else { + h.decconfig_ConfigurationMap((*pkg2_config.ConfigurationMap)(yyv229), d) + } + } + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l + } else { + yyb118 = r.CheckBreak() + } + if yyb118 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } for { - yyj107++ - if yyhl107 { - yyb107 = yyj107 > l + yyj118++ + if yyhl118 { + yyb118 = yyj118 > l } else { - yyb107 = r.CheckBreak() + yyb118 = r.CheckBreak() } - if yyb107 { + if yyb118 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj107-1, "") + z.DecStructFieldNotFound(yyj118-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -6559,16 +6943,16 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray - var yyq2 [49]bool + var yyq2 [53]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false - yyq2[47] = x.Kind != "" - yyq2[48] = x.APIVersion != "" + yyq2[51] = x.Kind != "" + yyq2[52] = x.APIVersion != "" var yynn2 int if yyr2 || yy2arr2 { - r.EncodeArrayStart(49) + r.EncodeArrayStart(53) } else { - yynn2 = 47 + yynn2 = 51 for _, b := range yyq2 { if b { yynn2++ @@ -6811,17 +7195,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym40 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForRC)) + r.EncodeInt(int64(x.ConcurrentSATokenSyncs)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRC")) + r.EncodeString(codecSelferC_UTF81234, string("concurrentSATokenSyncs")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym41 := z.EncBinary() _ = yym41 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForRC)) + r.EncodeInt(int64(x.ConcurrentSATokenSyncs)) } } if yyr2 || yy2arr2 { @@ -6830,17 +7214,17 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym43 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForRS)) + r.EncodeInt(int64(x.LookupCacheSizeForRC)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRS")) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRC")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym44 := z.EncBinary() _ = yym44 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForRS)) + r.EncodeInt(int64(x.LookupCacheSizeForRC)) } } if yyr2 || yy2arr2 { @@ -6849,49 +7233,55 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode _ = yym46 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) + r.EncodeInt(int64(x.LookupCacheSizeForRS)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForDaemonSet")) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForRS")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym47 := z.EncBinary() _ = yym47 if false { } else { - r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) + r.EncodeInt(int64(x.LookupCacheSizeForRS)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy49 := &x.ServiceSyncPeriod - yym50 := z.EncBinary() - _ = yym50 + yym49 := z.EncBinary() + _ = yym49 if false { - } else if z.HasExtensions() && z.EncExt(yy49) { - } else if !yym50 && z.IsJSONHandle() { - z.EncJSONMarshal(yy49) } else { - z.EncFallback(yy49) + r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) - r.EncodeString(codecSelferC_UTF81234, string("serviceSyncPeriod")) + r.EncodeString(codecSelferC_UTF81234, string("lookupCacheSizeForDaemonSet")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy51 := &x.ServiceSyncPeriod - yym52 := z.EncBinary() - _ = yym52 + yym50 := z.EncBinary() + _ = yym50 if false { - } else if z.HasExtensions() && z.EncExt(yy51) { - } else if !yym52 && z.IsJSONHandle() { - z.EncJSONMarshal(yy51) } else { - z.EncFallback(yy51) + r.EncodeInt(int64(x.LookupCacheSizeForDaemonSet)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy54 := &x.NodeSyncPeriod + yy52 := &x.ServiceSyncPeriod + yym53 := z.EncBinary() + _ = yym53 + if false { + } else if z.HasExtensions() && z.EncExt(yy52) { + } else if !yym53 && z.IsJSONHandle() { + z.EncJSONMarshal(yy52) + } else { + z.EncFallback(yy52) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("serviceSyncPeriod")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy54 := &x.ServiceSyncPeriod yym55 := z.EncBinary() _ = yym55 if false { @@ -6901,24 +7291,24 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy54) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy57 := &x.NodeSyncPeriod + yym58 := z.EncBinary() + _ = yym58 + if false { + } else if z.HasExtensions() && z.EncExt(yy57) { + } else if !yym58 && z.IsJSONHandle() { + z.EncJSONMarshal(yy57) + } else { + z.EncFallback(yy57) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy56 := &x.NodeSyncPeriod - yym57 := z.EncBinary() - _ = yym57 - if false { - } else if z.HasExtensions() && z.EncExt(yy56) { - } else if !yym57 && z.IsJSONHandle() { - z.EncJSONMarshal(yy56) - } else { - z.EncFallback(yy56) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy59 := &x.ResourceQuotaSyncPeriod + yy59 := &x.NodeSyncPeriod yym60 := z.EncBinary() _ = yym60 if false { @@ -6928,24 +7318,24 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy59) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy62 := &x.ResourceQuotaSyncPeriod + yym63 := z.EncBinary() + _ = yym63 + if false { + } else if z.HasExtensions() && z.EncExt(yy62) { + } else if !yym63 && z.IsJSONHandle() { + z.EncJSONMarshal(yy62) + } else { + z.EncFallback(yy62) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("resourceQuotaSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy61 := &x.ResourceQuotaSyncPeriod - yym62 := z.EncBinary() - _ = yym62 - if false { - } else if z.HasExtensions() && z.EncExt(yy61) { - } else if !yym62 && z.IsJSONHandle() { - z.EncJSONMarshal(yy61) - } else { - z.EncFallback(yy61) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy64 := &x.NamespaceSyncPeriod + yy64 := &x.ResourceQuotaSyncPeriod yym65 := z.EncBinary() _ = yym65 if false { @@ -6955,24 +7345,24 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy64) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy67 := &x.NamespaceSyncPeriod + yym68 := z.EncBinary() + _ = yym68 + if false { + } else if z.HasExtensions() && z.EncExt(yy67) { + } else if !yym68 && z.IsJSONHandle() { + z.EncJSONMarshal(yy67) + } else { + z.EncFallback(yy67) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("namespaceSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy66 := &x.NamespaceSyncPeriod - yym67 := z.EncBinary() - _ = yym67 - if false { - } else if z.HasExtensions() && z.EncExt(yy66) { - } else if !yym67 && z.IsJSONHandle() { - z.EncJSONMarshal(yy66) - } else { - z.EncFallback(yy66) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy69 := &x.PVClaimBinderSyncPeriod + yy69 := &x.NamespaceSyncPeriod yym70 := z.EncBinary() _ = yym70 if false { @@ -6982,24 +7372,24 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy69) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy72 := &x.PVClaimBinderSyncPeriod + yym73 := z.EncBinary() + _ = yym73 + if false { + } else if z.HasExtensions() && z.EncExt(yy72) { + } else if !yym73 && z.IsJSONHandle() { + z.EncJSONMarshal(yy72) + } else { + z.EncFallback(yy72) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("pvClaimBinderSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy71 := &x.PVClaimBinderSyncPeriod - yym72 := z.EncBinary() - _ = yym72 - if false { - } else if z.HasExtensions() && z.EncExt(yy71) { - } else if !yym72 && z.IsJSONHandle() { - z.EncJSONMarshal(yy71) - } else { - z.EncFallback(yy71) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy74 := &x.MinResyncPeriod + yy74 := &x.PVClaimBinderSyncPeriod yym75 := z.EncBinary() _ = yym75 if false { @@ -7009,25 +7399,38 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy74) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy77 := &x.MinResyncPeriod + yym78 := z.EncBinary() + _ = yym78 + if false { + } else if z.HasExtensions() && z.EncExt(yy77) { + } else if !yym78 && z.IsJSONHandle() { + z.EncJSONMarshal(yy77) + } else { + z.EncFallback(yy77) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("minResyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy76 := &x.MinResyncPeriod - yym77 := z.EncBinary() - _ = yym77 + yy79 := &x.MinResyncPeriod + yym80 := z.EncBinary() + _ = yym80 if false { - } else if z.HasExtensions() && z.EncExt(yy76) { - } else if !yym77 && z.IsJSONHandle() { - z.EncJSONMarshal(yy76) + } else if z.HasExtensions() && z.EncExt(yy79) { + } else if !yym80 && z.IsJSONHandle() { + z.EncJSONMarshal(yy79) } else { - z.EncFallback(yy76) + z.EncFallback(yy79) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym79 := z.EncBinary() - _ = yym79 + yym82 := z.EncBinary() + _ = yym82 if false { } else { r.EncodeInt(int64(x.TerminatedPodGCThreshold)) @@ -7036,8 +7439,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("terminatedPodGCThreshold")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym80 := z.EncBinary() - _ = yym80 + yym83 := z.EncBinary() + _ = yym83 if false { } else { r.EncodeInt(int64(x.TerminatedPodGCThreshold)) @@ -7045,34 +7448,21 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy82 := &x.HorizontalPodAutoscalerSyncPeriod - yym83 := z.EncBinary() - _ = yym83 + yy85 := &x.HorizontalPodAutoscalerSyncPeriod + yym86 := z.EncBinary() + _ = yym86 if false { - } else if z.HasExtensions() && z.EncExt(yy82) { - } else if !yym83 && z.IsJSONHandle() { - z.EncJSONMarshal(yy82) + } else if z.HasExtensions() && z.EncExt(yy85) { + } else if !yym86 && z.IsJSONHandle() { + z.EncJSONMarshal(yy85) } else { - z.EncFallback(yy82) + z.EncFallback(yy85) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("horizontalPodAutoscalerSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy84 := &x.HorizontalPodAutoscalerSyncPeriod - yym85 := z.EncBinary() - _ = yym85 - if false { - } else if z.HasExtensions() && z.EncExt(yy84) { - } else if !yym85 && z.IsJSONHandle() { - z.EncJSONMarshal(yy84) - } else { - z.EncFallback(yy84) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy87 := &x.DeploymentControllerSyncPeriod + yy87 := &x.HorizontalPodAutoscalerSyncPeriod yym88 := z.EncBinary() _ = yym88 if false { @@ -7082,24 +7472,24 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy87) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy90 := &x.DeploymentControllerSyncPeriod + yym91 := z.EncBinary() + _ = yym91 + if false { + } else if z.HasExtensions() && z.EncExt(yy90) { + } else if !yym91 && z.IsJSONHandle() { + z.EncJSONMarshal(yy90) + } else { + z.EncFallback(yy90) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("deploymentControllerSyncPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy89 := &x.DeploymentControllerSyncPeriod - yym90 := z.EncBinary() - _ = yym90 - if false { - } else if z.HasExtensions() && z.EncExt(yy89) { - } else if !yym90 && z.IsJSONHandle() { - z.EncJSONMarshal(yy89) - } else { - z.EncFallback(yy89) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy92 := &x.PodEvictionTimeout + yy92 := &x.DeploymentControllerSyncPeriod yym93 := z.EncBinary() _ = yym93 if false { @@ -7109,25 +7499,38 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy92) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy95 := &x.PodEvictionTimeout + yym96 := z.EncBinary() + _ = yym96 + if false { + } else if z.HasExtensions() && z.EncExt(yy95) { + } else if !yym96 && z.IsJSONHandle() { + z.EncJSONMarshal(yy95) + } else { + z.EncFallback(yy95) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("podEvictionTimeout")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy94 := &x.PodEvictionTimeout - yym95 := z.EncBinary() - _ = yym95 + yy97 := &x.PodEvictionTimeout + yym98 := z.EncBinary() + _ = yym98 if false { - } else if z.HasExtensions() && z.EncExt(yy94) { - } else if !yym95 && z.IsJSONHandle() { - z.EncJSONMarshal(yy94) + } else if z.HasExtensions() && z.EncExt(yy97) { + } else if !yym98 && z.IsJSONHandle() { + z.EncJSONMarshal(yy97) } else { - z.EncFallback(yy94) + z.EncFallback(yy97) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym97 := z.EncBinary() - _ = yym97 + yym100 := z.EncBinary() + _ = yym100 if false { } else { r.EncodeFloat32(float32(x.DeletingPodsQps)) @@ -7136,8 +7539,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("deletingPodsQps")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym98 := z.EncBinary() - _ = yym98 + yym101 := z.EncBinary() + _ = yym101 if false { } else { r.EncodeFloat32(float32(x.DeletingPodsQps)) @@ -7145,8 +7548,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym100 := z.EncBinary() - _ = yym100 + yym103 := z.EncBinary() + _ = yym103 if false { } else { r.EncodeInt(int64(x.DeletingPodsBurst)) @@ -7155,8 +7558,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("deletingPodsBurst")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym101 := z.EncBinary() - _ = yym101 + yym104 := z.EncBinary() + _ = yym104 if false { } else { r.EncodeInt(int64(x.DeletingPodsBurst)) @@ -7164,35 +7567,35 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy103 := &x.NodeMonitorGracePeriod - yym104 := z.EncBinary() - _ = yym104 + yy106 := &x.NodeMonitorGracePeriod + yym107 := z.EncBinary() + _ = yym107 if false { - } else if z.HasExtensions() && z.EncExt(yy103) { - } else if !yym104 && z.IsJSONHandle() { - z.EncJSONMarshal(yy103) + } else if z.HasExtensions() && z.EncExt(yy106) { + } else if !yym107 && z.IsJSONHandle() { + z.EncJSONMarshal(yy106) } else { - z.EncFallback(yy103) + z.EncFallback(yy106) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeMonitorGracePeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy105 := &x.NodeMonitorGracePeriod - yym106 := z.EncBinary() - _ = yym106 + yy108 := &x.NodeMonitorGracePeriod + yym109 := z.EncBinary() + _ = yym109 if false { - } else if z.HasExtensions() && z.EncExt(yy105) { - } else if !yym106 && z.IsJSONHandle() { - z.EncJSONMarshal(yy105) + } else if z.HasExtensions() && z.EncExt(yy108) { + } else if !yym109 && z.IsJSONHandle() { + z.EncJSONMarshal(yy108) } else { - z.EncFallback(yy105) + z.EncFallback(yy108) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym108 := z.EncBinary() - _ = yym108 + yym111 := z.EncBinary() + _ = yym111 if false { } else { r.EncodeInt(int64(x.RegisterRetryCount)) @@ -7201,8 +7604,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("registerRetryCount")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym109 := z.EncBinary() - _ = yym109 + yym112 := z.EncBinary() + _ = yym112 if false { } else { r.EncodeInt(int64(x.RegisterRetryCount)) @@ -7210,34 +7613,21 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy111 := &x.NodeStartupGracePeriod - yym112 := z.EncBinary() - _ = yym112 + yy114 := &x.NodeStartupGracePeriod + yym115 := z.EncBinary() + _ = yym115 if false { - } else if z.HasExtensions() && z.EncExt(yy111) { - } else if !yym112 && z.IsJSONHandle() { - z.EncJSONMarshal(yy111) + } else if z.HasExtensions() && z.EncExt(yy114) { + } else if !yym115 && z.IsJSONHandle() { + z.EncJSONMarshal(yy114) } else { - z.EncFallback(yy111) + z.EncFallback(yy114) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeStartupGracePeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy113 := &x.NodeStartupGracePeriod - yym114 := z.EncBinary() - _ = yym114 - if false { - } else if z.HasExtensions() && z.EncExt(yy113) { - } else if !yym114 && z.IsJSONHandle() { - z.EncJSONMarshal(yy113) - } else { - z.EncFallback(yy113) - } - } - if yyr2 || yy2arr2 { - z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy116 := &x.NodeMonitorPeriod + yy116 := &x.NodeStartupGracePeriod yym117 := z.EncBinary() _ = yym117 if false { @@ -7247,25 +7637,38 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } else { z.EncFallback(yy116) } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy119 := &x.NodeMonitorPeriod + yym120 := z.EncBinary() + _ = yym120 + if false { + } else if z.HasExtensions() && z.EncExt(yy119) { + } else if !yym120 && z.IsJSONHandle() { + z.EncJSONMarshal(yy119) + } else { + z.EncFallback(yy119) + } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeMonitorPeriod")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy118 := &x.NodeMonitorPeriod - yym119 := z.EncBinary() - _ = yym119 + yy121 := &x.NodeMonitorPeriod + yym122 := z.EncBinary() + _ = yym122 if false { - } else if z.HasExtensions() && z.EncExt(yy118) { - } else if !yym119 && z.IsJSONHandle() { - z.EncJSONMarshal(yy118) + } else if z.HasExtensions() && z.EncExt(yy121) { + } else if !yym122 && z.IsJSONHandle() { + z.EncJSONMarshal(yy121) } else { - z.EncFallback(yy118) + z.EncFallback(yy121) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym121 := z.EncBinary() - _ = yym121 + yym124 := z.EncBinary() + _ = yym124 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) @@ -7274,8 +7677,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("serviceAccountKeyFile")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym122 := z.EncBinary() - _ = yym122 + yym125 := z.EncBinary() + _ = yym125 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ServiceAccountKeyFile)) @@ -7283,8 +7686,46 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym124 := z.EncBinary() - _ = yym124 + yym127 := z.EncBinary() + _ = yym127 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterSigningCertFile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("clusterSigningCertFile")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym128 := z.EncBinary() + _ = yym128 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterSigningCertFile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym130 := z.EncBinary() + _ = yym130 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterSigningKeyFile)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("clusterSigningKeyFile")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym131 := z.EncBinary() + _ = yym131 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.ClusterSigningKeyFile)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym133 := z.EncBinary() + _ = yym133 if false { } else { r.EncodeBool(bool(x.EnableProfiling)) @@ -7293,8 +7734,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("enableProfiling")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym125 := z.EncBinary() - _ = yym125 + yym134 := z.EncBinary() + _ = yym134 if false { } else { r.EncodeBool(bool(x.EnableProfiling)) @@ -7302,8 +7743,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym127 := z.EncBinary() - _ = yym127 + yym136 := z.EncBinary() + _ = yym136 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) @@ -7312,8 +7753,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("clusterName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym128 := z.EncBinary() - _ = yym128 + yym137 := z.EncBinary() + _ = yym137 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ClusterName)) @@ -7321,8 +7762,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym130 := z.EncBinary() - _ = yym130 + yym139 := z.EncBinary() + _ = yym139 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) @@ -7331,8 +7772,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("clusterCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym131 := z.EncBinary() - _ = yym131 + yym140 := z.EncBinary() + _ = yym140 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ClusterCIDR)) @@ -7340,8 +7781,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym133 := z.EncBinary() - _ = yym133 + yym142 := z.EncBinary() + _ = yym142 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ServiceCIDR)) @@ -7350,8 +7791,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("serviceCIDR")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym134 := z.EncBinary() - _ = yym134 + yym143 := z.EncBinary() + _ = yym143 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ServiceCIDR)) @@ -7359,8 +7800,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym136 := z.EncBinary() - _ = yym136 + yym145 := z.EncBinary() + _ = yym145 if false { } else { r.EncodeInt(int64(x.NodeCIDRMaskSize)) @@ -7369,8 +7810,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("nodeCIDRMaskSize")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym137 := z.EncBinary() - _ = yym137 + yym146 := z.EncBinary() + _ = yym146 if false { } else { r.EncodeInt(int64(x.NodeCIDRMaskSize)) @@ -7378,8 +7819,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym139 := z.EncBinary() - _ = yym139 + yym148 := z.EncBinary() + _ = yym148 if false { } else { r.EncodeBool(bool(x.AllocateNodeCIDRs)) @@ -7388,8 +7829,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("allocateNodeCIDRs")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym140 := z.EncBinary() - _ = yym140 + yym149 := z.EncBinary() + _ = yym149 if false { } else { r.EncodeBool(bool(x.AllocateNodeCIDRs)) @@ -7397,8 +7838,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym142 := z.EncBinary() - _ = yym142 + yym151 := z.EncBinary() + _ = yym151 if false { } else { r.EncodeBool(bool(x.ConfigureCloudRoutes)) @@ -7407,8 +7848,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("configureCloudRoutes")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym143 := z.EncBinary() - _ = yym143 + yym152 := z.EncBinary() + _ = yym152 if false { } else { r.EncodeBool(bool(x.ConfigureCloudRoutes)) @@ -7416,8 +7857,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym145 := z.EncBinary() - _ = yym145 + yym154 := z.EncBinary() + _ = yym154 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) @@ -7426,8 +7867,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("rootCAFile")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym146 := z.EncBinary() - _ = yym146 + yym155 := z.EncBinary() + _ = yym155 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.RootCAFile)) @@ -7435,8 +7876,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym148 := z.EncBinary() - _ = yym148 + yym157 := z.EncBinary() + _ = yym157 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) @@ -7445,8 +7886,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("contentType")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym149 := z.EncBinary() - _ = yym149 + yym158 := z.EncBinary() + _ = yym158 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.ContentType)) @@ -7454,8 +7895,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym151 := z.EncBinary() - _ = yym151 + yym160 := z.EncBinary() + _ = yym160 if false { } else { r.EncodeFloat32(float32(x.KubeAPIQPS)) @@ -7464,8 +7905,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kubeAPIQPS")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym152 := z.EncBinary() - _ = yym152 + yym161 := z.EncBinary() + _ = yym161 if false { } else { r.EncodeFloat32(float32(x.KubeAPIQPS)) @@ -7473,8 +7914,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym154 := z.EncBinary() - _ = yym154 + yym163 := z.EncBinary() + _ = yym163 if false { } else { r.EncodeInt(int64(x.KubeAPIBurst)) @@ -7483,8 +7924,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kubeAPIBurst")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym155 := z.EncBinary() - _ = yym155 + yym164 := z.EncBinary() + _ = yym164 if false { } else { r.EncodeInt(int64(x.KubeAPIBurst)) @@ -7492,57 +7933,57 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy157 := &x.LeaderElection - yy157.CodecEncodeSelf(e) + yy166 := &x.LeaderElection + yy166.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("leaderElection")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy159 := &x.LeaderElection - yy159.CodecEncodeSelf(e) + yy168 := &x.LeaderElection + yy168.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy162 := &x.VolumeConfiguration - yy162.CodecEncodeSelf(e) + yy171 := &x.VolumeConfiguration + yy171.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("volumeConfiguration")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy164 := &x.VolumeConfiguration - yy164.CodecEncodeSelf(e) + yy173 := &x.VolumeConfiguration + yy173.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yy167 := &x.ControllerStartInterval - yym168 := z.EncBinary() - _ = yym168 + yy176 := &x.ControllerStartInterval + yym177 := z.EncBinary() + _ = yym177 if false { - } else if z.HasExtensions() && z.EncExt(yy167) { - } else if !yym168 && z.IsJSONHandle() { - z.EncJSONMarshal(yy167) + } else if z.HasExtensions() && z.EncExt(yy176) { + } else if !yym177 && z.IsJSONHandle() { + z.EncJSONMarshal(yy176) } else { - z.EncFallback(yy167) + z.EncFallback(yy176) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("controllerStartInterval")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yy169 := &x.ControllerStartInterval - yym170 := z.EncBinary() - _ = yym170 + yy178 := &x.ControllerStartInterval + yym179 := z.EncBinary() + _ = yym179 if false { - } else if z.HasExtensions() && z.EncExt(yy169) { - } else if !yym170 && z.IsJSONHandle() { - z.EncJSONMarshal(yy169) + } else if z.HasExtensions() && z.EncExt(yy178) { + } else if !yym179 && z.IsJSONHandle() { + z.EncJSONMarshal(yy178) } else { - z.EncFallback(yy169) + z.EncFallback(yy178) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - yym172 := z.EncBinary() - _ = yym172 + yym181 := z.EncBinary() + _ = yym181 if false { } else { r.EncodeBool(bool(x.EnableGarbageCollector)) @@ -7551,8 +7992,8 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("enableGarbageCollector")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym173 := z.EncBinary() - _ = yym173 + yym182 := z.EncBinary() + _ = yym182 if false { } else { r.EncodeBool(bool(x.EnableGarbageCollector)) @@ -7560,9 +8001,28 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[47] { - yym175 := z.EncBinary() - _ = yym175 + yym184 := z.EncBinary() + _ = yym184 + if false { + } else { + r.EncodeInt(int64(x.ConcurrentGCSyncs)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("concurrentGCSyncs")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym185 := z.EncBinary() + _ = yym185 + if false { + } else { + r.EncodeInt(int64(x.ConcurrentGCSyncs)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[51] { + yym187 := z.EncBinary() + _ = yym187 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -7571,12 +8031,12 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[47] { + if yyq2[51] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym176 := z.EncBinary() - _ = yym176 + yym188 := z.EncBinary() + _ = yym188 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) @@ -7585,9 +8045,9 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) - if yyq2[48] { - yym178 := z.EncBinary() - _ = yym178 + if yyq2[52] { + yym190 := z.EncBinary() + _ = yym190 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -7596,12 +8056,12 @@ func (x *KubeControllerManagerConfiguration) CodecEncodeSelf(e *codec1978.Encode r.EncodeString(codecSelferC_UTF81234, "") } } else { - if yyq2[48] { + if yyq2[52] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) - yym179 := z.EncBinary() - _ = yym179 + yym191 := z.EncBinary() + _ = yym191 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) @@ -7741,6 +8201,12 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co } else { x.ConcurrentNamespaceSyncs = int32(r.DecodeInt(32)) } + case "concurrentSATokenSyncs": + if r.TryDecodeAsNil() { + x.ConcurrentSATokenSyncs = 0 + } else { + x.ConcurrentSATokenSyncs = int32(r.DecodeInt(32)) + } case "lookupCacheSizeForRC": if r.TryDecodeAsNil() { x.LookupCacheSizeForRC = 0 @@ -7763,90 +8229,90 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.ServiceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv19 := &x.ServiceSyncPeriod - yym20 := z.DecBinary() - _ = yym20 + yyv20 := &x.ServiceSyncPeriod + yym21 := z.DecBinary() + _ = yym21 if false { - } else if z.HasExtensions() && z.DecExt(yyv19) { - } else if !yym20 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv19) + } else if z.HasExtensions() && z.DecExt(yyv20) { + } else if !yym21 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv20) } else { - z.DecFallback(yyv19, false) + z.DecFallback(yyv20, false) } } case "nodeSyncPeriod": if r.TryDecodeAsNil() { x.NodeSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv21 := &x.NodeSyncPeriod - yym22 := z.DecBinary() - _ = yym22 + yyv22 := &x.NodeSyncPeriod + yym23 := z.DecBinary() + _ = yym23 if false { - } else if z.HasExtensions() && z.DecExt(yyv21) { - } else if !yym22 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv21) + } else if z.HasExtensions() && z.DecExt(yyv22) { + } else if !yym23 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv22) } else { - z.DecFallback(yyv21, false) + z.DecFallback(yyv22, false) } } case "resourceQuotaSyncPeriod": if r.TryDecodeAsNil() { x.ResourceQuotaSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv23 := &x.ResourceQuotaSyncPeriod - yym24 := z.DecBinary() - _ = yym24 + yyv24 := &x.ResourceQuotaSyncPeriod + yym25 := z.DecBinary() + _ = yym25 if false { - } else if z.HasExtensions() && z.DecExt(yyv23) { - } else if !yym24 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv23) + } else if z.HasExtensions() && z.DecExt(yyv24) { + } else if !yym25 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv24) } else { - z.DecFallback(yyv23, false) + z.DecFallback(yyv24, false) } } case "namespaceSyncPeriod": if r.TryDecodeAsNil() { x.NamespaceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv25 := &x.NamespaceSyncPeriod - yym26 := z.DecBinary() - _ = yym26 + yyv26 := &x.NamespaceSyncPeriod + yym27 := z.DecBinary() + _ = yym27 if false { - } else if z.HasExtensions() && z.DecExt(yyv25) { - } else if !yym26 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv25) + } else if z.HasExtensions() && z.DecExt(yyv26) { + } else if !yym27 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv26) } else { - z.DecFallback(yyv25, false) + z.DecFallback(yyv26, false) } } case "pvClaimBinderSyncPeriod": if r.TryDecodeAsNil() { x.PVClaimBinderSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv27 := &x.PVClaimBinderSyncPeriod - yym28 := z.DecBinary() - _ = yym28 + yyv28 := &x.PVClaimBinderSyncPeriod + yym29 := z.DecBinary() + _ = yym29 if false { - } else if z.HasExtensions() && z.DecExt(yyv27) { - } else if !yym28 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv27) + } else if z.HasExtensions() && z.DecExt(yyv28) { + } else if !yym29 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv28) } else { - z.DecFallback(yyv27, false) + z.DecFallback(yyv28, false) } } case "minResyncPeriod": if r.TryDecodeAsNil() { x.MinResyncPeriod = pkg1_unversioned.Duration{} } else { - yyv29 := &x.MinResyncPeriod - yym30 := z.DecBinary() - _ = yym30 + yyv30 := &x.MinResyncPeriod + yym31 := z.DecBinary() + _ = yym31 if false { - } else if z.HasExtensions() && z.DecExt(yyv29) { - } else if !yym30 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv29) + } else if z.HasExtensions() && z.DecExt(yyv30) { + } else if !yym31 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv30) } else { - z.DecFallback(yyv29, false) + z.DecFallback(yyv30, false) } } case "terminatedPodGCThreshold": @@ -7859,45 +8325,45 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.HorizontalPodAutoscalerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv32 := &x.HorizontalPodAutoscalerSyncPeriod - yym33 := z.DecBinary() - _ = yym33 + yyv33 := &x.HorizontalPodAutoscalerSyncPeriod + yym34 := z.DecBinary() + _ = yym34 if false { - } else if z.HasExtensions() && z.DecExt(yyv32) { - } else if !yym33 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv32) + } else if z.HasExtensions() && z.DecExt(yyv33) { + } else if !yym34 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv33) } else { - z.DecFallback(yyv32, false) + z.DecFallback(yyv33, false) } } case "deploymentControllerSyncPeriod": if r.TryDecodeAsNil() { x.DeploymentControllerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv34 := &x.DeploymentControllerSyncPeriod - yym35 := z.DecBinary() - _ = yym35 + yyv35 := &x.DeploymentControllerSyncPeriod + yym36 := z.DecBinary() + _ = yym36 if false { - } else if z.HasExtensions() && z.DecExt(yyv34) { - } else if !yym35 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv34) + } else if z.HasExtensions() && z.DecExt(yyv35) { + } else if !yym36 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv35) } else { - z.DecFallback(yyv34, false) + z.DecFallback(yyv35, false) } } case "podEvictionTimeout": if r.TryDecodeAsNil() { x.PodEvictionTimeout = pkg1_unversioned.Duration{} } else { - yyv36 := &x.PodEvictionTimeout - yym37 := z.DecBinary() - _ = yym37 + yyv37 := &x.PodEvictionTimeout + yym38 := z.DecBinary() + _ = yym38 if false { - } else if z.HasExtensions() && z.DecExt(yyv36) { - } else if !yym37 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv36) + } else if z.HasExtensions() && z.DecExt(yyv37) { + } else if !yym38 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv37) } else { - z.DecFallback(yyv36, false) + z.DecFallback(yyv37, false) } } case "deletingPodsQps": @@ -7916,15 +8382,15 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.NodeMonitorGracePeriod = pkg1_unversioned.Duration{} } else { - yyv40 := &x.NodeMonitorGracePeriod - yym41 := z.DecBinary() - _ = yym41 + yyv41 := &x.NodeMonitorGracePeriod + yym42 := z.DecBinary() + _ = yym42 if false { - } else if z.HasExtensions() && z.DecExt(yyv40) { - } else if !yym41 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv40) + } else if z.HasExtensions() && z.DecExt(yyv41) { + } else if !yym42 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv41) } else { - z.DecFallback(yyv40, false) + z.DecFallback(yyv41, false) } } case "registerRetryCount": @@ -7937,30 +8403,30 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.NodeStartupGracePeriod = pkg1_unversioned.Duration{} } else { - yyv43 := &x.NodeStartupGracePeriod - yym44 := z.DecBinary() - _ = yym44 + yyv44 := &x.NodeStartupGracePeriod + yym45 := z.DecBinary() + _ = yym45 if false { - } else if z.HasExtensions() && z.DecExt(yyv43) { - } else if !yym44 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv43) + } else if z.HasExtensions() && z.DecExt(yyv44) { + } else if !yym45 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv44) } else { - z.DecFallback(yyv43, false) + z.DecFallback(yyv44, false) } } case "nodeMonitorPeriod": if r.TryDecodeAsNil() { x.NodeMonitorPeriod = pkg1_unversioned.Duration{} } else { - yyv45 := &x.NodeMonitorPeriod - yym46 := z.DecBinary() - _ = yym46 + yyv46 := &x.NodeMonitorPeriod + yym47 := z.DecBinary() + _ = yym47 if false { - } else if z.HasExtensions() && z.DecExt(yyv45) { - } else if !yym46 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv45) + } else if z.HasExtensions() && z.DecExt(yyv46) { + } else if !yym47 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv46) } else { - z.DecFallback(yyv45, false) + z.DecFallback(yyv46, false) } } case "serviceAccountKeyFile": @@ -7969,6 +8435,18 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co } else { x.ServiceAccountKeyFile = string(r.DecodeString()) } + case "clusterSigningCertFile": + if r.TryDecodeAsNil() { + x.ClusterSigningCertFile = "" + } else { + x.ClusterSigningCertFile = string(r.DecodeString()) + } + case "clusterSigningKeyFile": + if r.TryDecodeAsNil() { + x.ClusterSigningKeyFile = "" + } else { + x.ClusterSigningKeyFile = string(r.DecodeString()) + } case "enableProfiling": if r.TryDecodeAsNil() { x.EnableProfiling = false @@ -8039,29 +8517,29 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co if r.TryDecodeAsNil() { x.LeaderElection = LeaderElectionConfiguration{} } else { - yyv59 := &x.LeaderElection - yyv59.CodecDecodeSelf(d) + yyv62 := &x.LeaderElection + yyv62.CodecDecodeSelf(d) } case "volumeConfiguration": if r.TryDecodeAsNil() { x.VolumeConfiguration = VolumeConfiguration{} } else { - yyv60 := &x.VolumeConfiguration - yyv60.CodecDecodeSelf(d) + yyv63 := &x.VolumeConfiguration + yyv63.CodecDecodeSelf(d) } case "controllerStartInterval": if r.TryDecodeAsNil() { x.ControllerStartInterval = pkg1_unversioned.Duration{} } else { - yyv61 := &x.ControllerStartInterval - yym62 := z.DecBinary() - _ = yym62 + yyv64 := &x.ControllerStartInterval + yym65 := z.DecBinary() + _ = yym65 if false { - } else if z.HasExtensions() && z.DecExt(yyv61) { - } else if !yym62 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv61) + } else if z.HasExtensions() && z.DecExt(yyv64) { + } else if !yym65 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv64) } else { - z.DecFallback(yyv61, false) + z.DecFallback(yyv64, false) } } case "enableGarbageCollector": @@ -8070,6 +8548,12 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromMap(l int, d *co } else { x.EnableGarbageCollector = bool(r.DecodeBool()) } + case "concurrentGCSyncs": + if r.TryDecodeAsNil() { + x.ConcurrentGCSyncs = 0 + } else { + x.ConcurrentGCSyncs = int32(r.DecodeInt(32)) + } case "kind": if r.TryDecodeAsNil() { x.Kind = "" @@ -8093,16 +8577,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r - var yyj66 int - var yyb66 bool - var yyhl66 bool = l >= 0 - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + var yyj70 int + var yyb70 bool + var yyhl70 bool = l >= 0 + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8112,13 +8596,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Port = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8128,13 +8612,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Address = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8144,13 +8628,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.CloudProvider = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8160,13 +8644,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.CloudConfigFile = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8176,13 +8660,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentEndpointSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8192,13 +8676,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentRSSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8208,13 +8692,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentRCSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8224,13 +8708,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentResourceQuotaSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8240,13 +8724,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentDeploymentSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8256,13 +8740,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentDaemonSetSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8272,13 +8756,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentJobSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8288,13 +8772,29 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConcurrentNamespaceSyncs = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l + } else { + yyb70 = r.CheckBreak() + } + if yyb70 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ConcurrentSATokenSyncs = 0 + } else { + x.ConcurrentSATokenSyncs = int32(r.DecodeInt(32)) + } + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8304,13 +8804,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.LookupCacheSizeForRC = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8320,13 +8820,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.LookupCacheSizeForRS = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8336,13 +8836,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.LookupCacheSizeForDaemonSet = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8350,24 +8850,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.ServiceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv82 := &x.ServiceSyncPeriod - yym83 := z.DecBinary() - _ = yym83 + yyv87 := &x.ServiceSyncPeriod + yym88 := z.DecBinary() + _ = yym88 if false { - } else if z.HasExtensions() && z.DecExt(yyv82) { - } else if !yym83 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv82) + } else if z.HasExtensions() && z.DecExt(yyv87) { + } else if !yym88 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv87) } else { - z.DecFallback(yyv82, false) + z.DecFallback(yyv87, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8375,24 +8875,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv84 := &x.NodeSyncPeriod - yym85 := z.DecBinary() - _ = yym85 + yyv89 := &x.NodeSyncPeriod + yym90 := z.DecBinary() + _ = yym90 if false { - } else if z.HasExtensions() && z.DecExt(yyv84) { - } else if !yym85 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv84) + } else if z.HasExtensions() && z.DecExt(yyv89) { + } else if !yym90 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv89) } else { - z.DecFallback(yyv84, false) + z.DecFallback(yyv89, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8400,24 +8900,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.ResourceQuotaSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv86 := &x.ResourceQuotaSyncPeriod - yym87 := z.DecBinary() - _ = yym87 + yyv91 := &x.ResourceQuotaSyncPeriod + yym92 := z.DecBinary() + _ = yym92 if false { - } else if z.HasExtensions() && z.DecExt(yyv86) { - } else if !yym87 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv86) + } else if z.HasExtensions() && z.DecExt(yyv91) { + } else if !yym92 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv91) } else { - z.DecFallback(yyv86, false) + z.DecFallback(yyv91, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8425,24 +8925,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NamespaceSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv88 := &x.NamespaceSyncPeriod - yym89 := z.DecBinary() - _ = yym89 + yyv93 := &x.NamespaceSyncPeriod + yym94 := z.DecBinary() + _ = yym94 if false { - } else if z.HasExtensions() && z.DecExt(yyv88) { - } else if !yym89 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv88) + } else if z.HasExtensions() && z.DecExt(yyv93) { + } else if !yym94 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv93) } else { - z.DecFallback(yyv88, false) + z.DecFallback(yyv93, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8450,24 +8950,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.PVClaimBinderSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv90 := &x.PVClaimBinderSyncPeriod - yym91 := z.DecBinary() - _ = yym91 + yyv95 := &x.PVClaimBinderSyncPeriod + yym96 := z.DecBinary() + _ = yym96 if false { - } else if z.HasExtensions() && z.DecExt(yyv90) { - } else if !yym91 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv90) + } else if z.HasExtensions() && z.DecExt(yyv95) { + } else if !yym96 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv95) } else { - z.DecFallback(yyv90, false) + z.DecFallback(yyv95, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8475,24 +8975,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.MinResyncPeriod = pkg1_unversioned.Duration{} } else { - yyv92 := &x.MinResyncPeriod - yym93 := z.DecBinary() - _ = yym93 + yyv97 := &x.MinResyncPeriod + yym98 := z.DecBinary() + _ = yym98 if false { - } else if z.HasExtensions() && z.DecExt(yyv92) { - } else if !yym93 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv92) + } else if z.HasExtensions() && z.DecExt(yyv97) { + } else if !yym98 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv97) } else { - z.DecFallback(yyv92, false) + z.DecFallback(yyv97, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8502,13 +9002,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.TerminatedPodGCThreshold = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8516,24 +9016,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.HorizontalPodAutoscalerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv95 := &x.HorizontalPodAutoscalerSyncPeriod - yym96 := z.DecBinary() - _ = yym96 + yyv100 := &x.HorizontalPodAutoscalerSyncPeriod + yym101 := z.DecBinary() + _ = yym101 if false { - } else if z.HasExtensions() && z.DecExt(yyv95) { - } else if !yym96 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv95) + } else if z.HasExtensions() && z.DecExt(yyv100) { + } else if !yym101 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv100) } else { - z.DecFallback(yyv95, false) + z.DecFallback(yyv100, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8541,24 +9041,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.DeploymentControllerSyncPeriod = pkg1_unversioned.Duration{} } else { - yyv97 := &x.DeploymentControllerSyncPeriod - yym98 := z.DecBinary() - _ = yym98 + yyv102 := &x.DeploymentControllerSyncPeriod + yym103 := z.DecBinary() + _ = yym103 if false { - } else if z.HasExtensions() && z.DecExt(yyv97) { - } else if !yym98 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv97) + } else if z.HasExtensions() && z.DecExt(yyv102) { + } else if !yym103 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv102) } else { - z.DecFallback(yyv97, false) + z.DecFallback(yyv102, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8566,24 +9066,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.PodEvictionTimeout = pkg1_unversioned.Duration{} } else { - yyv99 := &x.PodEvictionTimeout - yym100 := z.DecBinary() - _ = yym100 + yyv104 := &x.PodEvictionTimeout + yym105 := z.DecBinary() + _ = yym105 if false { - } else if z.HasExtensions() && z.DecExt(yyv99) { - } else if !yym100 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv99) + } else if z.HasExtensions() && z.DecExt(yyv104) { + } else if !yym105 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv104) } else { - z.DecFallback(yyv99, false) + z.DecFallback(yyv104, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8593,13 +9093,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.DeletingPodsQps = float32(r.DecodeFloat(true)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8609,13 +9109,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.DeletingPodsBurst = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8623,24 +9123,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeMonitorGracePeriod = pkg1_unversioned.Duration{} } else { - yyv103 := &x.NodeMonitorGracePeriod - yym104 := z.DecBinary() - _ = yym104 + yyv108 := &x.NodeMonitorGracePeriod + yym109 := z.DecBinary() + _ = yym109 if false { - } else if z.HasExtensions() && z.DecExt(yyv103) { - } else if !yym104 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv103) + } else if z.HasExtensions() && z.DecExt(yyv108) { + } else if !yym109 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv108) } else { - z.DecFallback(yyv103, false) + z.DecFallback(yyv108, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8650,13 +9150,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.RegisterRetryCount = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8664,24 +9164,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeStartupGracePeriod = pkg1_unversioned.Duration{} } else { - yyv106 := &x.NodeStartupGracePeriod - yym107 := z.DecBinary() - _ = yym107 + yyv111 := &x.NodeStartupGracePeriod + yym112 := z.DecBinary() + _ = yym112 if false { - } else if z.HasExtensions() && z.DecExt(yyv106) { - } else if !yym107 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv106) + } else if z.HasExtensions() && z.DecExt(yyv111) { + } else if !yym112 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv111) } else { - z.DecFallback(yyv106, false) + z.DecFallback(yyv111, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8689,24 +9189,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.NodeMonitorPeriod = pkg1_unversioned.Duration{} } else { - yyv108 := &x.NodeMonitorPeriod - yym109 := z.DecBinary() - _ = yym109 + yyv113 := &x.NodeMonitorPeriod + yym114 := z.DecBinary() + _ = yym114 if false { - } else if z.HasExtensions() && z.DecExt(yyv108) { - } else if !yym109 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv108) + } else if z.HasExtensions() && z.DecExt(yyv113) { + } else if !yym114 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv113) } else { - z.DecFallback(yyv108, false) + z.DecFallback(yyv113, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8716,13 +9216,45 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ServiceAccountKeyFile = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l + } else { + yyb70 = r.CheckBreak() + } + if yyb70 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ClusterSigningCertFile = "" + } else { + x.ClusterSigningCertFile = string(r.DecodeString()) + } + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l + } else { + yyb70 = r.CheckBreak() + } + if yyb70 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ClusterSigningKeyFile = "" + } else { + x.ClusterSigningKeyFile = string(r.DecodeString()) + } + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8732,13 +9264,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.EnableProfiling = bool(r.DecodeBool()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8748,13 +9280,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ClusterName = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8764,13 +9296,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ClusterCIDR = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8780,13 +9312,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ServiceCIDR = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8796,13 +9328,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.NodeCIDRMaskSize = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8812,13 +9344,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.AllocateNodeCIDRs = bool(r.DecodeBool()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8828,13 +9360,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ConfigureCloudRoutes = bool(r.DecodeBool()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8844,13 +9376,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.RootCAFile = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8860,13 +9392,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.ContentType = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8876,13 +9408,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.KubeAPIQPS = float32(r.DecodeFloat(true)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8892,13 +9424,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.KubeAPIBurst = int32(r.DecodeInt(32)) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8906,16 +9438,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.LeaderElection = LeaderElectionConfiguration{} } else { - yyv122 := &x.LeaderElection - yyv122.CodecDecodeSelf(d) + yyv129 := &x.LeaderElection + yyv129.CodecDecodeSelf(d) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8923,16 +9455,16 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.VolumeConfiguration = VolumeConfiguration{} } else { - yyv123 := &x.VolumeConfiguration - yyv123.CodecDecodeSelf(d) + yyv130 := &x.VolumeConfiguration + yyv130.CodecDecodeSelf(d) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8940,24 +9472,24 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * if r.TryDecodeAsNil() { x.ControllerStartInterval = pkg1_unversioned.Duration{} } else { - yyv124 := &x.ControllerStartInterval - yym125 := z.DecBinary() - _ = yym125 + yyv131 := &x.ControllerStartInterval + yym132 := z.DecBinary() + _ = yym132 if false { - } else if z.HasExtensions() && z.DecExt(yyv124) { - } else if !yym125 && z.IsJSONHandle() { - z.DecJSONUnmarshal(yyv124) + } else if z.HasExtensions() && z.DecExt(yyv131) { + } else if !yym132 && z.IsJSONHandle() { + z.DecJSONUnmarshal(yyv131) } else { - z.DecFallback(yyv124, false) + z.DecFallback(yyv131, false) } } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8967,13 +9499,29 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.EnableGarbageCollector = bool(r.DecodeBool()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l + } else { + yyb70 = r.CheckBreak() + } + if yyb70 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ConcurrentGCSyncs = 0 + } else { + x.ConcurrentGCSyncs = int32(r.DecodeInt(32)) + } + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -8983,13 +9531,13 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * } else { x.Kind = string(r.DecodeString()) } - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } @@ -9000,17 +9548,17 @@ func (x *KubeControllerManagerConfiguration) codecDecodeSelfFromArray(l int, d * x.APIVersion = string(r.DecodeString()) } for { - yyj66++ - if yyhl66 { - yyb66 = yyj66 > l + yyj70++ + if yyhl70 { + yyb70 = yyj70 > l } else { - yyb66 = r.CheckBreak() + yyb70 = r.CheckBreak() } - if yyb66 { + if yyb70 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) - z.DecStructFieldNotFound(yyj66-1, "") + z.DecStructFieldNotFound(yyj70-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } @@ -9701,3 +10249,95 @@ func (x *PersistentVolumeRecyclerConfiguration) codecDecodeSelfFromArray(l int, } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } + +func (x codecSelfer1234) encconfig_ConfigurationMap(v pkg2_config.ConfigurationMap, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeMapStart(len(v)) + for yyk1, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + yym2 := z.EncBinary() + _ = yym2 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(yyk1)) + } + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym3 := z.EncBinary() + _ = yym3 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(yyv1)) + } + } + z.EncSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x codecSelfer1234) decconfig_ConfigurationMap(v *pkg2_config.ConfigurationMap, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyl1 := r.ReadMapStart() + yybh1 := z.DecBasicHandle() + if yyv1 == nil { + yyrl1, _ := z.DecInferLen(yyl1, yybh1.MaxInitLen, 32) + yyv1 = make(map[string]string, yyrl1) + *v = yyv1 + } + var yymk1 string + var yymv1 string + var yymg1 bool + if yybh1.MapValueReset { + } + if yyl1 > 0 { + for yyj1 := 0; yyj1 < yyl1; yyj1++ { + z.DecSendContainerState(codecSelfer_containerMapKey1234) + if r.TryDecodeAsNil() { + yymk1 = "" + } else { + yymk1 = string(r.DecodeString()) + } + + if yymg1 { + yymv1 = yyv1[yymk1] + } + z.DecSendContainerState(codecSelfer_containerMapValue1234) + if r.TryDecodeAsNil() { + yymv1 = "" + } else { + yymv1 = string(r.DecodeString()) + } + + if yyv1 != nil { + yyv1[yymk1] = yymv1 + } + } + } else if yyl1 < 0 { + for yyj1 := 0; !r.CheckBreak(); yyj1++ { + z.DecSendContainerState(codecSelfer_containerMapKey1234) + if r.TryDecodeAsNil() { + yymk1 = "" + } else { + yymk1 = string(r.DecodeString()) + } + + if yymg1 { + yymv1 = yyv1[yymk1] + } + z.DecSendContainerState(codecSelfer_containerMapValue1234) + if r.TryDecodeAsNil() { + yymv1 = "" + } else { + yymv1 = string(r.DecodeString()) + } + + if yyv1 != nil { + yyv1[yymk1] = yymv1 + } + } + } // else len==0: TODO: Should we clear map entries? + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.go index 070ac0e24cd2..39237520321a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,7 +16,10 @@ limitations under the License. package componentconfig -import "k8s.io/kubernetes/pkg/api/unversioned" +import ( + "k8s.io/kubernetes/pkg/api/unversioned" + utilconfig "k8s.io/kubernetes/pkg/util/config" +) type KubeProxyConfiguration struct { unversioned.TypeMeta @@ -58,7 +61,7 @@ type KubeProxyConfiguration struct { PortRange string `json:"portRange"` // resourceContainer is the absolute name of the resource-only container to create and run // the Kube-proxy in (Default: /kube-proxy). - ResourceContainer string `json:"kubeletCgroups"` + ResourceContainer string `json:"resourceContainer"` // udpIdleTimeout is how long an idle UDP connection will be kept open (e.g. '250ms', '2s'). // Must be greater than 0. Only applicable for proxyMode=userspace. UDPIdleTimeout unversioned.Duration `json:"udpTimeoutMilliseconds"` @@ -107,6 +110,8 @@ const ( // TODO: curate the ordering and structure of this config object type KubeletConfiguration struct { + unversioned.TypeMeta + // config is the path to the config file or directory of files Config string `json:"config"` // syncFrequency is the max period between synchronizing running @@ -128,19 +133,19 @@ type KubeletConfiguration struct { // for all interfaces) Address string `json:"address"` // port is the port for the Kubelet to serve on. - Port uint `json:"port"` + Port int32 `json:"port"` // readOnlyPort is the read-only port for the Kubelet to serve on with // no authentication/authorization (set to 0 to disable) - ReadOnlyPort uint `json:"readOnlyPort"` - // tLSCertFile is the file containing x509 Certificate for HTTPS. (CA cert, + ReadOnlyPort int32 `json:"readOnlyPort"` + // tlsCertFile is the file containing x509 Certificate for HTTPS. (CA cert, // if any, concatenated after server cert). If tlsCertFile and // tlsPrivateKeyFile are not provided, a self-signed certificate // and key are generated for the public address and saved to the directory // passed to certDir. - TLSCertFile string `json:"tLSCertFile"` - // tLSPrivateKeyFile is the ile containing x509 private key matching + TLSCertFile string `json:"tlsCertFile"` + // tlsPrivateKeyFile is the ile containing x509 private key matching // tlsCertFile. - TLSPrivateKeyFile string `json:"tLSPrivateKeyFile"` + TLSPrivateKeyFile string `json:"tlsPrivateKeyFile"` // certDirectory is the directory where the TLS certs are located (by // default /var/run/kubernetes). If tlsCertFile and tlsPrivateKeyFile // are provided, this flag will be ignored. @@ -162,24 +167,25 @@ type KubeletConfiguration struct { // Defaults to false. AllowPrivileged bool `json:"allowPrivileged"` // hostNetworkSources is a comma-separated list of sources from which the - // Kubelet allows pods to use of host network. Defaults to "*". - HostNetworkSources string `json:"hostNetworkSources"` + // Kubelet allows pods to use of host network. Defaults to "*". Valid + // options are "file", "http", "api", and "*" (all sources). + HostNetworkSources []string `json:"hostNetworkSources"` // hostPIDSources is a comma-separated list of sources from which the // Kubelet allows pods to use the host pid namespace. Defaults to "*". - HostPIDSources string `json:"hostPIDSources"` + HostPIDSources []string `json:"hostPIDSources"` // hostIPCSources is a comma-separated list of sources from which the // Kubelet allows pods to use the host ipc namespace. Defaults to "*". - HostIPCSources string `json:"hostIPCSources"` + HostIPCSources []string `json:"hostIPCSources"` // registryPullQPS is the limit of registry pulls per second. If 0, // unlimited. Set to 0 for no limit. Defaults to 5.0. - RegistryPullQPS float64 `json:"registryPullQPS"` + RegistryPullQPS int32 `json:"registryPullQPS"` // registryBurst is the maximum size of a bursty pulls, temporarily allows // pulls to burst to this number, while still not exceeding registryQps. - // Only used if registryQps > 0. + // Only used if registryQPS > 0. RegistryBurst int32 `json:"registryBurst"` // eventRecordQPS is the maximum event creations per second. If 0, there // is no limit enforced. - EventRecordQPS float32 `json:"eventRecordQPS"` + EventRecordQPS int32 `json:"eventRecordQPS"` // eventBurst is the maximum size of a bursty event records, temporarily // allows event records to burst to this number, while still not exceeding // event-qps. Only used if eventQps > 0 @@ -197,7 +203,7 @@ type KubeletConfiguration struct { // to retain globally. Each container takes up some disk space. MaxContainerCount int32 `json:"maxContainerCount"` // cAdvisorPort is the port of the localhost cAdvisor endpoint - CAdvisorPort uint `json:"cAdvisorPort"` + CAdvisorPort int32 `json:"cAdvisorPort"` // healthzPort is the port of the localhost healthz endpoint HealthzPort int32 `json:"healthzPort"` // healthzBindAddress is the IP address for the healthz server to serve @@ -226,7 +232,7 @@ type KubeletConfiguration struct { // status to master. Note: be cautious when changing the constant, it // must work with nodeMonitorGracePeriod in nodecontroller. NodeStatusUpdateFrequency unversioned.Duration `json:"nodeStatusUpdateFrequency"` - // minimumGCAge is the minimum age for a unused image before it is + // imageMinimumGCAge is the minimum age for a unused image before it is // garbage collected. ImageMinimumGCAge unversioned.Duration `json:"imageMinimumGCAge"` // imageGCHighThresholdPercent is the percent of disk usage after which @@ -257,14 +263,18 @@ type KubeletConfiguration struct { CloudConfigFile string `json:"cloudConfigFile,omitempty"` // KubeletCgroups is the absolute name of cgroups to isolate the kubelet in. KubeletCgroups string `json:"kubeletCgroups,omitempty"` + // Enable QoS based Cgroup hierarchy: top level cgroups for QoS Classes + // And all Burstable and BestEffort pods are brought up under their + // specific top level QoS cgroup. + CgroupsPerQOS bool `json:"CgroupsPerQOS,omitempty"` // Cgroups that container runtime is expected to be isolated in. RuntimeCgroups string `json:"runtimeCgroups,omitempty"` // SystemCgroups is absolute name of cgroups in which to place // all non-kernel processes that are not already in a container. Empty // for no container. Rolling back the flag requires a reboot. - SystemCgroups string `json:"systemContainer,omitempty"` - // cgroupRoot is the root cgroup to use for pods. This is handled by the - // container runtime on a best effort basis. + SystemCgroups string `json:"systemCgroups,omitempty"` + // CgroupRoot is the root cgroup to use for pods. + // If CgroupsPerQOS is enabled, this is the root of the QoS cgroup hierarchy. CgroupRoot string `json:"cgroupRoot,omitempty"` // containerRuntime is the container runtime to use. ContainerRuntime string `json:"containerRuntime"` @@ -323,7 +333,7 @@ type KubeletConfiguration struct { // containerized should be set to true if kubelet is running in a container. Containerized bool `json:"containerized"` // maxOpenFiles is Number of files that can be opened by Kubelet process. - MaxOpenFiles uint64 `json:"maxOpenFiles"` + MaxOpenFiles int64 `json:"maxOpenFiles"` // reconcileCIDR is Reconcile node CIDR with the CIDR specified by the // API server. No-op if register-node or configure-cbr0 is false. ReconcileCIDR bool `json:"reconcileCIDR"` @@ -333,7 +343,7 @@ type KubeletConfiguration struct { // contentType is contentType of requests sent to apiserver. ContentType string `json:"contentType"` // kubeAPIQPS is the QPS to use while talking with kubernetes apiserver - KubeAPIQPS float32 `json:"kubeAPIQPS"` + KubeAPIQPS int32 `json:"kubeAPIQPS"` // kubeAPIBurst is the burst to allow while talking with kubernetes // apiserver KubeAPIBurst int32 `json:"kubeAPIBurst"` @@ -368,12 +378,24 @@ type KubeletConfiguration struct { EvictionPressureTransitionPeriod unversioned.Duration `json:"evictionPressureTransitionPeriod,omitempty"` // Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met. EvictionMaxPodGracePeriod int32 `json:"evictionMaxPodGracePeriod,omitempty"` + // Comma-delimited list of minimum reclaims (e.g. imagefs.available=2Gi) that describes the minimum amount of resource the kubelet will reclaim when performing a pod eviction if that resource is under pressure. + EvictionMinimumReclaim string `json:"evictionMinimumReclaim,omitempty"` // Maximum number of pods per core. Cannot exceed MaxPods PodsPerCore int32 `json:"podsPerCore"` // enableControllerAttachDetach enables the Attach/Detach controller to // manage attachment/detachment of volumes scheduled to this node, and // disables kubelet from executing any attach/detach operations EnableControllerAttachDetach bool `json:"enableControllerAttachDetach"` + // A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs + // that describe resources reserved for non-kubernetes components. + // Currently only cpu and memory are supported. [default=none] + // See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. + SystemReserved utilconfig.ConfigurationMap `json:"systemReserved"` + // A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs + // that describe resources reserved for kubernetes system components. + // Currently only cpu and memory are supported. [default=none] + // See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. + KubeReserved utilconfig.ConfigurationMap `json:"kubeReserved"` } type KubeSchedulerConfiguration struct { @@ -476,6 +498,9 @@ type KubeControllerManagerConfiguration struct { // concurrentNamespaceSyncs is the number of namespace objects that are // allowed to sync concurrently. ConcurrentNamespaceSyncs int32 `json:"concurrentNamespaceSyncs"` + // concurrentSATokenSyncs is the number of service account token syncing operations + // that will be done concurrently. + ConcurrentSATokenSyncs int32 `json:"concurrentSATokenSyncs"` // lookupCacheSizeForRC is the size of lookup cache for replication controllers. // Larger number = more responsive replica management, but more MEM load. LookupCacheSizeForRC int32 `json:"lookupCacheSizeForRC"` @@ -518,11 +543,11 @@ type KubeControllerManagerConfiguration struct { // deletingPodsQps is the number of nodes per second on which pods are deleted in // case of node failure. DeletingPodsQps float32 `json:"deletingPodsQps"` - // deletingPodsBurst is the number of nodes on which pods are bursty deleted in + // DEPRECATED: deletingPodsBurst is the number of nodes on which pods are bursty deleted in // case of node failure. For more details look into RateLimiter. DeletingPodsBurst int32 `json:"deletingPodsBurst"` // nodeMontiorGracePeriod is the amount of time which we allow a running node to be - // unresponsive before marking it unhealty. Must be N times more than kubelet's + // unresponsive before marking it unhealthy. Must be N times more than kubelet's // nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet // to post node status. NodeMonitorGracePeriod unversioned.Duration `json:"nodeMonitorGracePeriod"` @@ -530,13 +555,19 @@ type KubeControllerManagerConfiguration struct { // Retry interval equals node-sync-period. RegisterRetryCount int32 `json:"registerRetryCount"` // nodeStartupGracePeriod is the amount of time which we allow starting a node to - // be unresponsive before marking it unhealty. + // be unresponsive before marking it unhealthy. NodeStartupGracePeriod unversioned.Duration `json:"nodeStartupGracePeriod"` // nodeMonitorPeriod is the period for syncing NodeStatus in NodeController. NodeMonitorPeriod unversioned.Duration `json:"nodeMonitorPeriod"` // serviceAccountKeyFile is the filename containing a PEM-encoded private RSA key // used to sign service account tokens. ServiceAccountKeyFile string `json:"serviceAccountKeyFile"` + // clusterSigningCertFile is the filename containing a PEM-encoded + // X509 CA certificate used to issue cluster-scoped certificates + ClusterSigningCertFile string `json:"clusterSigningCertFile"` + // clusterSigningCertFile is the filename containing a PEM-encoded + // RSA or ECDSA private key used to issue cluster-scoped certificates + ClusterSigningKeyFile string `json:"clusterSigningKeyFile"` // enableProfiling enables profiling via web interface host:port/debug/pprof/ EnableProfiling bool `json:"enableProfiling"` // clusterName is the instance prefix for the cluster. @@ -572,6 +603,9 @@ type KubeControllerManagerConfiguration struct { // corresponding flag of the kube-apiserver. WARNING: the generic garbage // collector is an alpha feature. EnableGarbageCollector bool `json:"enableGarbageCollector"` + // concurrentGCSyncs is the number of garbage collector workers that are + // allowed to sync concurrently. + ConcurrentGCSyncs int32 `json:"concurrentGCSyncs"` } // VolumeConfiguration contains *all* enumerated flags meant to configure all volume diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/conversion_generated.go deleted file mode 100644 index b49ff2af00d5..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/conversion_generated.go +++ /dev/null @@ -1,184 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by conversion-gen. Do not edit it manually! - -package v1alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - componentconfig "k8s.io/kubernetes/pkg/apis/componentconfig" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedConversionFuncs( - Convert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration, - Convert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration, - Convert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration, - Convert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration, - Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration, - Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration, - ); err != nil { - // if one of the conversion functions is malformed, detect it immediately. - panic(err) - } -} - -func autoConvert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in *KubeProxyConfiguration, out *componentconfig.KubeProxyConfiguration, s conversion.Scope) error { - SetDefaults_KubeProxyConfiguration(in) - if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { - return err - } - out.BindAddress = in.BindAddress - out.ClusterCIDR = in.ClusterCIDR - out.HealthzBindAddress = in.HealthzBindAddress - out.HealthzPort = in.HealthzPort - out.HostnameOverride = in.HostnameOverride - out.IPTablesMasqueradeBit = in.IPTablesMasqueradeBit - out.IPTablesSyncPeriod = in.IPTablesSyncPeriod - out.KubeconfigPath = in.KubeconfigPath - out.MasqueradeAll = in.MasqueradeAll - out.Master = in.Master - out.OOMScoreAdj = in.OOMScoreAdj - out.Mode = componentconfig.ProxyMode(in.Mode) - out.PortRange = in.PortRange - out.ResourceContainer = in.ResourceContainer - out.UDPIdleTimeout = in.UDPIdleTimeout - out.ConntrackMax = in.ConntrackMax - out.ConntrackMaxPerCore = in.ConntrackMaxPerCore - out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout - return nil -} - -func Convert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in *KubeProxyConfiguration, out *componentconfig.KubeProxyConfiguration, s conversion.Scope) error { - return autoConvert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in, out, s) -} - -func autoConvert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in *componentconfig.KubeProxyConfiguration, out *KubeProxyConfiguration, s conversion.Scope) error { - if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { - return err - } - out.BindAddress = in.BindAddress - out.ClusterCIDR = in.ClusterCIDR - out.HealthzBindAddress = in.HealthzBindAddress - out.HealthzPort = in.HealthzPort - out.HostnameOverride = in.HostnameOverride - out.IPTablesMasqueradeBit = in.IPTablesMasqueradeBit - out.IPTablesSyncPeriod = in.IPTablesSyncPeriod - out.KubeconfigPath = in.KubeconfigPath - out.MasqueradeAll = in.MasqueradeAll - out.Master = in.Master - out.OOMScoreAdj = in.OOMScoreAdj - out.Mode = ProxyMode(in.Mode) - out.PortRange = in.PortRange - out.ResourceContainer = in.ResourceContainer - out.UDPIdleTimeout = in.UDPIdleTimeout - out.ConntrackMax = in.ConntrackMax - out.ConntrackMaxPerCore = in.ConntrackMaxPerCore - out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout - return nil -} - -func Convert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in *componentconfig.KubeProxyConfiguration, out *KubeProxyConfiguration, s conversion.Scope) error { - return autoConvert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in, out, s) -} - -func autoConvert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in *KubeSchedulerConfiguration, out *componentconfig.KubeSchedulerConfiguration, s conversion.Scope) error { - SetDefaults_KubeSchedulerConfiguration(in) - if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { - return err - } - out.Port = int32(in.Port) - out.Address = in.Address - out.AlgorithmProvider = in.AlgorithmProvider - out.PolicyConfigFile = in.PolicyConfigFile - if err := api.Convert_Pointer_bool_To_bool(&in.EnableProfiling, &out.EnableProfiling, s); err != nil { - return err - } - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = int32(in.KubeAPIBurst) - out.SchedulerName = in.SchedulerName - out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight - out.FailureDomains = in.FailureDomains - if err := Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(&in.LeaderElection, &out.LeaderElection, s); err != nil { - return err - } - return nil -} - -func Convert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in *KubeSchedulerConfiguration, out *componentconfig.KubeSchedulerConfiguration, s conversion.Scope) error { - return autoConvert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in, out, s) -} - -func autoConvert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in *componentconfig.KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, s conversion.Scope) error { - if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { - return err - } - out.Port = int(in.Port) - out.Address = in.Address - out.AlgorithmProvider = in.AlgorithmProvider - out.PolicyConfigFile = in.PolicyConfigFile - if err := api.Convert_bool_To_Pointer_bool(&in.EnableProfiling, &out.EnableProfiling, s); err != nil { - return err - } - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = int(in.KubeAPIBurst) - out.SchedulerName = in.SchedulerName - out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight - out.FailureDomains = in.FailureDomains - if err := Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(&in.LeaderElection, &out.LeaderElection, s); err != nil { - return err - } - return nil -} - -func Convert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in *componentconfig.KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, s conversion.Scope) error { - return autoConvert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in, out, s) -} - -func autoConvert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *componentconfig.LeaderElectionConfiguration, s conversion.Scope) error { - SetDefaults_LeaderElectionConfiguration(in) - if err := api.Convert_Pointer_bool_To_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil { - return err - } - out.LeaseDuration = in.LeaseDuration - out.RenewDeadline = in.RenewDeadline - out.RetryPeriod = in.RetryPeriod - return nil -} - -func Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *componentconfig.LeaderElectionConfiguration, s conversion.Scope) error { - return autoConvert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in, out, s) -} - -func autoConvert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *componentconfig.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error { - if err := api.Convert_bool_To_Pointer_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil { - return err - } - out.LeaseDuration = in.LeaseDuration - out.RenewDeadline = in.RenewDeadline - out.RetryPeriod = in.RetryPeriod - return nil -} - -func Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *componentconfig.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error { - return autoConvert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in, out, s) -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/deep_copy_generated.go deleted file mode 100644 index d1543037d24c..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/deep_copy_generated.go +++ /dev/null @@ -1,128 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1alpha1_KubeProxyConfiguration, - DeepCopy_v1alpha1_KubeSchedulerConfiguration, - DeepCopy_v1alpha1_LeaderElectionConfiguration, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1alpha1_KubeProxyConfiguration(in KubeProxyConfiguration, out *KubeProxyConfiguration, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.BindAddress = in.BindAddress - out.ClusterCIDR = in.ClusterCIDR - out.HealthzBindAddress = in.HealthzBindAddress - out.HealthzPort = in.HealthzPort - out.HostnameOverride = in.HostnameOverride - if in.IPTablesMasqueradeBit != nil { - in, out := in.IPTablesMasqueradeBit, &out.IPTablesMasqueradeBit - *out = new(int32) - **out = *in - } else { - out.IPTablesMasqueradeBit = nil - } - if err := unversioned.DeepCopy_unversioned_Duration(in.IPTablesSyncPeriod, &out.IPTablesSyncPeriod, c); err != nil { - return err - } - out.KubeconfigPath = in.KubeconfigPath - out.MasqueradeAll = in.MasqueradeAll - out.Master = in.Master - if in.OOMScoreAdj != nil { - in, out := in.OOMScoreAdj, &out.OOMScoreAdj - *out = new(int32) - **out = *in - } else { - out.OOMScoreAdj = nil - } - out.Mode = in.Mode - out.PortRange = in.PortRange - out.ResourceContainer = in.ResourceContainer - if err := unversioned.DeepCopy_unversioned_Duration(in.UDPIdleTimeout, &out.UDPIdleTimeout, c); err != nil { - return err - } - out.ConntrackMax = in.ConntrackMax - out.ConntrackMaxPerCore = in.ConntrackMaxPerCore - if err := unversioned.DeepCopy_unversioned_Duration(in.ConntrackTCPEstablishedTimeout, &out.ConntrackTCPEstablishedTimeout, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_KubeSchedulerConfiguration(in KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Port = in.Port - out.Address = in.Address - out.AlgorithmProvider = in.AlgorithmProvider - out.PolicyConfigFile = in.PolicyConfigFile - if in.EnableProfiling != nil { - in, out := in.EnableProfiling, &out.EnableProfiling - *out = new(bool) - **out = *in - } else { - out.EnableProfiling = nil - } - out.ContentType = in.ContentType - out.KubeAPIQPS = in.KubeAPIQPS - out.KubeAPIBurst = in.KubeAPIBurst - out.SchedulerName = in.SchedulerName - out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight - out.FailureDomains = in.FailureDomains - if err := DeepCopy_v1alpha1_LeaderElectionConfiguration(in.LeaderElection, &out.LeaderElection, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_LeaderElectionConfiguration(in LeaderElectionConfiguration, out *LeaderElectionConfiguration, c *conversion.Cloner) error { - if in.LeaderElect != nil { - in, out := in.LeaderElect, &out.LeaderElect - *out = new(bool) - **out = *in - } else { - out.LeaderElect = nil - } - if err := unversioned.DeepCopy_unversioned_Duration(in.LeaseDuration, &out.LeaseDuration, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.RenewDeadline, &out.RenewDeadline, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Duration(in.RetryPeriod, &out.RetryPeriod, c); err != nil { - return err - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/defaults.go index d90e2205b80b..16feb2ea1a48 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,20 +17,42 @@ limitations under the License. package v1alpha1 import ( + "path/filepath" + "runtime" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/kubelet/qos" + kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/master/ports" - "k8s.io/kubernetes/pkg/runtime" + kruntime "k8s.io/kubernetes/pkg/runtime" ) -func addDefaultingFuncs(scheme *runtime.Scheme) { +const ( + defaultRootDir = "/var/lib/kubelet" + + // When these values are updated, also update test/e2e/framework/util.go + defaultPodInfraContainerImageName = "gcr.io/google_containers/pause" + defaultPodInfraContainerImageVersion = "3.0" + defaultPodInfraContainerImage = defaultPodInfraContainerImageName + + "-" + runtime.GOARCH + ":" + + defaultPodInfraContainerImageVersion + + // From pkg/kubelet/rkt/rkt.go to avoid circular import + defaultRktAPIServiceEndpoint = "localhost:15441" + + AutoDetectCloudProvider = "auto-detect" +) + +var zeroDuration = unversioned.Duration{} + +func addDefaultingFuncs(scheme *kruntime.Scheme) { scheme.AddDefaultingFuncs( SetDefaults_KubeProxyConfiguration, SetDefaults_KubeSchedulerConfiguration, SetDefaults_LeaderElectionConfiguration, + SetDefaults_KubeletConfiguration, ) } @@ -116,3 +138,211 @@ func SetDefaults_LeaderElectionConfiguration(obj *LeaderElectionConfiguration) { obj.RetryPeriod = unversioned.Duration{Duration: 2 * time.Second} } } + +func SetDefaults_KubeletConfiguration(obj *KubeletConfiguration) { + if obj.Address == "" { + obj.Address = "0.0.0.0" + } + if obj.CloudProvider == "" { + obj.CloudProvider = AutoDetectCloudProvider + } + if obj.CAdvisorPort == 0 { + obj.CAdvisorPort = 4194 + } + if obj.VolumeStatsAggPeriod == zeroDuration { + obj.VolumeStatsAggPeriod = unversioned.Duration{Duration: time.Minute} + } + if obj.CertDirectory == "" { + obj.CertDirectory = "/var/run/kubernetes" + } + if obj.ConfigureCBR0 == nil { + obj.ConfigureCBR0 = boolVar(false) + } + if obj.CgroupsPerQOS == nil { + obj.CgroupsPerQOS = boolVar(false) + } + if obj.ContainerRuntime == "" { + obj.ContainerRuntime = "docker" + } + if obj.RuntimeRequestTimeout == zeroDuration { + obj.RuntimeRequestTimeout = unversioned.Duration{Duration: 2 * time.Minute} + } + if obj.CPUCFSQuota == nil { + obj.CPUCFSQuota = boolVar(true) + } + if obj.DockerExecHandlerName == "" { + obj.DockerExecHandlerName = "native" + } + if obj.DockerEndpoint == "" { + obj.DockerEndpoint = "unix:///var/run/docker.sock" + } + if obj.EventBurst == 0 { + obj.EventBurst = 10 + } + if obj.EventRecordQPS == nil { + temp := int32(5) + obj.EventRecordQPS = &temp + } + if obj.EnableControllerAttachDetach == nil { + obj.EnableControllerAttachDetach = boolVar(true) + } + if obj.EnableDebuggingHandlers == nil { + obj.EnableDebuggingHandlers = boolVar(true) + } + if obj.EnableServer == nil { + obj.EnableServer = boolVar(true) + } + if obj.FileCheckFrequency == zeroDuration { + obj.FileCheckFrequency = unversioned.Duration{Duration: 20 * time.Second} + } + if obj.HealthzBindAddress == "" { + obj.HealthzBindAddress = "127.0.0.1" + } + if obj.HealthzPort == 0 { + obj.HealthzPort = 10248 + } + if obj.HostNetworkSources == nil { + obj.HostNetworkSources = []string{kubetypes.AllSource} + } + if obj.HostPIDSources == nil { + obj.HostPIDSources = []string{kubetypes.AllSource} + } + if obj.HostIPCSources == nil { + obj.HostIPCSources = []string{kubetypes.AllSource} + } + if obj.HTTPCheckFrequency == zeroDuration { + obj.HTTPCheckFrequency = unversioned.Duration{Duration: 20 * time.Second} + } + if obj.ImageMinimumGCAge == zeroDuration { + obj.ImageMinimumGCAge = unversioned.Duration{Duration: 2 * time.Minute} + } + if obj.ImageGCHighThresholdPercent == nil { + temp := int32(90) + obj.ImageGCHighThresholdPercent = &temp + } + if obj.ImageGCLowThresholdPercent == nil { + temp := int32(80) + obj.ImageGCLowThresholdPercent = &temp + } + if obj.LowDiskSpaceThresholdMB == 0 { + obj.LowDiskSpaceThresholdMB = 256 + } + if obj.MasterServiceNamespace == "" { + obj.MasterServiceNamespace = api.NamespaceDefault + } + if obj.MaxContainerCount == nil { + temp := int32(-1) + obj.MaxContainerCount = &temp + } + if obj.MaxPerPodContainerCount == 0 { + obj.MaxPerPodContainerCount = 1 + } + if obj.MaxOpenFiles == 0 { + obj.MaxOpenFiles = 1000000 + } + if obj.MaxPods == 0 { + obj.MaxPods = 110 + } + if obj.MinimumGCAge == zeroDuration { + obj.MinimumGCAge = unversioned.Duration{Duration: 0} + } + if obj.NetworkPluginDir == "" { + obj.NetworkPluginDir = "/usr/libexec/kubernetes/kubelet-plugins/net/exec/" + } + if obj.NonMasqueradeCIDR == "" { + obj.NonMasqueradeCIDR = "10.0.0.0/8" + } + if obj.VolumePluginDir == "" { + obj.VolumePluginDir = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/" + } + if obj.NodeStatusUpdateFrequency == zeroDuration { + obj.NodeStatusUpdateFrequency = unversioned.Duration{Duration: 10 * time.Second} + } + if obj.OOMScoreAdj == nil { + temp := int32(qos.KubeletOOMScoreAdj) + obj.OOMScoreAdj = &temp + } + if obj.PodInfraContainerImage == "" { + obj.PodInfraContainerImage = defaultPodInfraContainerImage + } + if obj.Port == 0 { + obj.Port = ports.KubeletPort + } + if obj.ReadOnlyPort == 0 { + obj.ReadOnlyPort = ports.KubeletReadOnlyPort + } + if obj.RegisterNode == nil { + obj.RegisterNode = boolVar(true) + } + if obj.RegisterSchedulable == nil { + obj.RegisterSchedulable = boolVar(true) + } + if obj.RegistryBurst == 0 { + obj.RegistryBurst = 10 + } + if obj.RegistryPullQPS == nil { + temp := int32(5) + obj.RegistryPullQPS = &temp + } + if obj.ResolverConfig == "" { + obj.ResolverConfig = kubetypes.ResolvConfDefault + } + if obj.RktAPIEndpoint == "" { + obj.RktAPIEndpoint = defaultRktAPIServiceEndpoint + } + if obj.RootDirectory == "" { + obj.RootDirectory = defaultRootDir + } + if obj.SerializeImagePulls == nil { + obj.SerializeImagePulls = boolVar(true) + } + if obj.SeccompProfileRoot == "" { + filepath.Join(defaultRootDir, "seccomp") + } + if obj.StreamingConnectionIdleTimeout == zeroDuration { + obj.StreamingConnectionIdleTimeout = unversioned.Duration{Duration: 4 * time.Hour} + } + if obj.SyncFrequency == zeroDuration { + obj.SyncFrequency = unversioned.Duration{Duration: 1 * time.Minute} + } + if obj.ReconcileCIDR == nil { + obj.ReconcileCIDR = boolVar(true) + } + if obj.ContentType == "" { + obj.ContentType = "application/vnd.kubernetes.protobuf" + } + if obj.KubeAPIQPS == nil { + temp := int32(5) + obj.KubeAPIQPS = &temp + } + if obj.KubeAPIBurst == 0 { + obj.KubeAPIBurst = 10 + } + if obj.OutOfDiskTransitionFrequency == zeroDuration { + obj.OutOfDiskTransitionFrequency = unversioned.Duration{Duration: 5 * time.Minute} + } + if string(obj.HairpinMode) == "" { + obj.HairpinMode = PromiscuousBridge + } + if obj.EvictionHard == nil { + temp := "memory.available<100Mi" + obj.EvictionHard = &temp + } + if obj.EvictionPressureTransitionPeriod == zeroDuration { + obj.EvictionPressureTransitionPeriod = unversioned.Duration{Duration: 5 * time.Minute} + } + if obj.SystemReserved == nil { + obj.SystemReserved = make(map[string]string) + } + if obj.KubeReserved == nil { + obj.KubeReserved = make(map[string]string) + } +} + +func boolVar(b bool) *bool { + return &b +} + +var ( + defaultCfg = KubeletConfiguration{} +) diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/doc.go index 65a03a2093dc..621e80613d1c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/componentconfig + package v1alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/register.go index d74effb7d178..adf968c83198 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,5 +36,10 @@ func addKnownTypes(scheme *runtime.Scheme) { scheme.AddKnownTypes(SchemeGroupVersion, &KubeProxyConfiguration{}, &KubeSchedulerConfiguration{}, + &KubeletConfiguration{}, ) } + +func (obj *KubeProxyConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *KubeSchedulerConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } +func (obj *KubeletConfiguration) GetObjectKind() unversioned.ObjectKind { return &obj.TypeMeta } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/types.go index 95c3aee5589b..681bce3d67b1 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -120,6 +120,24 @@ type KubeSchedulerConfiguration struct { LeaderElection LeaderElectionConfiguration `json:"leaderElection"` } +// HairpinMode denotes how the kubelet should configure networking to handle +// hairpin packets. +type HairpinMode string + +// Enum settings for different ways to handle hairpin packets. +const ( + // Set the hairpin flag on the veth of containers in the respective + // container runtime. + HairpinVeth = "hairpin-veth" + // Make the container bridge promiscuous. This will force it to accept + // hairpin packets, even if the flag isn't set on ports of the bridge. + PromiscuousBridge = "promiscuous-bridge" + // Neither of the above. If the kubelet is started in this hairpin mode + // and kube-proxy is running in iptables mode, hairpin packets will be + // dropped by the container bridge. + HairpinNone = "none" +) + // LeaderElectionConfiguration defines the configuration of leader election // clients for components that can run with leader election enabled. type LeaderElectionConfiguration struct { @@ -144,3 +162,293 @@ type LeaderElectionConfiguration struct { // leader election is enabled. RetryPeriod unversioned.Duration `json:"retryPeriod"` } + +type KubeletConfiguration struct { + unversioned.TypeMeta + + // config is the path to the config file or directory of files + Config string `json:"config"` + // syncFrequency is the max period between synchronizing running + // containers and config + SyncFrequency unversioned.Duration `json:"syncFrequency"` + // fileCheckFrequency is the duration between checking config files for + // new data + FileCheckFrequency unversioned.Duration `json:"fileCheckFrequency"` + // httpCheckFrequency is the duration between checking http for new data + HTTPCheckFrequency unversioned.Duration `json:"httpCheckFrequency"` + // manifestURL is the URL for accessing the container manifest + ManifestURL string `json:"manifestURL"` + // manifestURLHeader is the HTTP header to use when accessing the manifest + // URL, with the key separated from the value with a ':', as in 'key:value' + ManifestURLHeader string `json:"manifestURLHeader"` + // enableServer enables the Kubelet's server + EnableServer *bool `json:"enableServer"` + // address is the IP address for the Kubelet to serve on (set to 0.0.0.0 + // for all interfaces) + Address string `json:"address"` + // port is the port for the Kubelet to serve on. + Port int32 `json:"port"` + // readOnlyPort is the read-only port for the Kubelet to serve on with + // no authentication/authorization (set to 0 to disable) + ReadOnlyPort int32 `json:"readOnlyPort"` + // tlsCertFile is the file containing x509 Certificate for HTTPS. (CA cert, + // if any, concatenated after server cert). If tlsCertFile and + // tlsPrivateKeyFile are not provided, a self-signed certificate + // and key are generated for the public address and saved to the directory + // passed to certDir. + TLSCertFile string `json:"tlsCertFile"` + // tlsPrivateKeyFile is the ile containing x509 private key matching + // tlsCertFile. + TLSPrivateKeyFile string `json:"tlsPrivateKeyFile"` + // certDirectory is the directory where the TLS certs are located (by + // default /var/run/kubernetes). If tlsCertFile and tlsPrivateKeyFile + // are provided, this flag will be ignored. + CertDirectory string `json:"certDirectory"` + // hostnameOverride is the hostname used to identify the kubelet instead + // of the actual hostname. + HostnameOverride string `json:"hostnameOverride"` + // podInfraContainerImage is the image whose network/ipc namespaces + // containers in each pod will use. + PodInfraContainerImage string `json:"podInfraContainerImage"` + // dockerEndpoint is the path to the docker endpoint to communicate with. + DockerEndpoint string `json:"dockerEndpoint"` + // rootDirectory is the directory path to place kubelet files (volume + // mounts,etc). + RootDirectory string `json:"rootDirectory"` + // seccompProfileRoot is the directory path for seccomp profiles. + SeccompProfileRoot string `json:"seccompProfileRoot"` + // allowPrivileged enables containers to request privileged mode. + // Defaults to false. + AllowPrivileged *bool `json:"allowPrivileged"` + // hostNetworkSources is a comma-separated list of sources from which the + // Kubelet allows pods to use of host network. Defaults to "*". Valid + // options are "file", "http", "api", and "*" (all sources). + HostNetworkSources []string `json:"hostNetworkSources"` + // hostPIDSources is a comma-separated list of sources from which the + // Kubelet allows pods to use the host pid namespace. Defaults to "*". + HostPIDSources []string `json:"hostPIDSources"` + // hostIPCSources is a comma-separated list of sources from which the + // Kubelet allows pods to use the host ipc namespace. Defaults to "*". + HostIPCSources []string `json:"hostIPCSources"` + // registryPullQPS is the limit of registry pulls per second. If 0, + // unlimited. Set to 0 for no limit. Defaults to 5.0. + RegistryPullQPS *int32 `json:"registryPullQPS"` + // registryBurst is the maximum size of a bursty pulls, temporarily allows + // pulls to burst to this number, while still not exceeding registryQps. + // Only used if registryQPS > 0. + RegistryBurst int32 `json:"registryBurst"` + // eventRecordQPS is the maximum event creations per second. If 0, there + // is no limit enforced. + EventRecordQPS *int32 `json:"eventRecordQPS"` + // eventBurst is the maximum size of a bursty event records, temporarily + // allows event records to burst to this number, while still not exceeding + // event-qps. Only used if eventQps > 0 + EventBurst int32 `json:"eventBurst"` + // enableDebuggingHandlers enables server endpoints for log collection + // and local running of containers and commands + EnableDebuggingHandlers *bool `json:"enableDebuggingHandlers"` + // minimumGCAge is the minimum age for a finished container before it is + // garbage collected. + MinimumGCAge unversioned.Duration `json:"minimumGCAge"` + // maxPerPodContainerCount is the maximum number of old instances to + // retain per container. Each container takes up some disk space. + MaxPerPodContainerCount int32 `json:"maxPerPodContainerCount"` + // maxContainerCount is the maximum number of old instances of containers + // to retain globally. Each container takes up some disk space. + MaxContainerCount *int32 `json:"maxContainerCount"` + // cAdvisorPort is the port of the localhost cAdvisor endpoint + CAdvisorPort int32 `json:"cAdvisorPort"` + // healthzPort is the port of the localhost healthz endpoint + HealthzPort int32 `json:"healthzPort"` + // healthzBindAddress is the IP address for the healthz server to serve + // on. + HealthzBindAddress string `json:"healthzBindAddress"` + // oomScoreAdj is The oom-score-adj value for kubelet process. Values + // must be within the range [-1000, 1000]. + OOMScoreAdj *int32 `json:"oomScoreAdj"` + // registerNode enables automatic registration with the apiserver. + RegisterNode *bool `json:"registerNode"` + // clusterDomain is the DNS domain for this cluster. If set, kubelet will + // configure all containers to search this domain in addition to the + // host's search domains. + ClusterDomain string `json:"clusterDomain"` + // masterServiceNamespace is The namespace from which the kubernetes + // master services should be injected into pods. + MasterServiceNamespace string `json:"masterServiceNamespace"` + // clusterDNS is the IP address for a cluster DNS server. If set, kubelet + // will configure all containers to use this for DNS resolution in + // addition to the host's DNS servers + ClusterDNS string `json:"clusterDNS"` + // streamingConnectionIdleTimeout is the maximum time a streaming connection + // can be idle before the connection is automatically closed. + StreamingConnectionIdleTimeout unversioned.Duration `json:"streamingConnectionIdleTimeout"` + // nodeStatusUpdateFrequency is the frequency that kubelet posts node + // status to master. Note: be cautious when changing the constant, it + // must work with nodeMonitorGracePeriod in nodecontroller. + NodeStatusUpdateFrequency unversioned.Duration `json:"nodeStatusUpdateFrequency"` + // imageMinimumGCAge is the minimum age for a unused image before it is + // garbage collected. + ImageMinimumGCAge unversioned.Duration `json:"imageMinimumGCAge"` + // imageGCHighThresholdPercent is the percent of disk usage after which + // image garbage collection is always run. The percent is calculated as + // this field value out of 100. + ImageGCHighThresholdPercent *int32 `json:"imageGCHighThresholdPercent"` + // imageGCLowThresholdPercent is the percent of disk usage before which + // image garbage collection is never run. Lowest disk usage to garbage + // collect to. The percent is calculated as this field value out of 100. + ImageGCLowThresholdPercent *int32 `json:"imageGCLowThresholdPercent"` + // lowDiskSpaceThresholdMB is the absolute free disk space, in MB, to + // maintain. When disk space falls below this threshold, new pods would + // be rejected. + LowDiskSpaceThresholdMB int32 `json:"lowDiskSpaceThresholdMB"` + // How frequently to calculate and cache volume disk usage for all pods + VolumeStatsAggPeriod unversioned.Duration `json:"volumeStatsAggPeriod"` + // networkPluginName is the name of the network plugin to be invoked for + // various events in kubelet/pod lifecycle + NetworkPluginName string `json:"networkPluginName"` + // networkPluginDir is the full path of the directory in which to search + // for network plugins + NetworkPluginDir string `json:"networkPluginDir"` + // volumePluginDir is the full path of the directory in which to search + // for additional third party volume plugins + VolumePluginDir string `json:"volumePluginDir"` + // cloudProvider is the provider for cloud services. + CloudProvider string `json:"cloudProvider"` + // cloudConfigFile is the path to the cloud provider configuration file. + CloudConfigFile string `json:"cloudConfigFile"` + // kubeletCgroups is the absolute name of cgroups to isolate the kubelet in. + KubeletCgroups string `json:"kubeletCgroups"` + // runtimeCgroups are cgroups that container runtime is expected to be isolated in. + RuntimeCgroups string `json:"runtimeCgroups"` + // systemCgroups is absolute name of cgroups in which to place + // all non-kernel processes that are not already in a container. Empty + // for no container. Rolling back the flag requires a reboot. + SystemCgroups string `json:"systemCgroups"` + // cgroupRoot is the root cgroup to use for pods. This is handled by the + // container runtime on a best effort basis. + CgroupRoot string `json:"cgroupRoot"` + // Enable QoS based Cgroup hierarchy: top level cgroups for QoS Classes + // And all Burstable and BestEffort pods are brought up under their + // specific top level QoS cgroup. + CgroupsPerQOS *bool `json:"CgroupsPerQOS,omitempty"` + // containerRuntime is the container runtime to use. + ContainerRuntime string `json:"containerRuntime"` + // runtimeRequestTimeout is the timeout for all runtime requests except long running + // requests - pull, logs, exec and attach. + RuntimeRequestTimeout unversioned.Duration `json:"runtimeRequestTimeout"` + // rktPath is the path of rkt binary. Leave empty to use the first rkt in + // $PATH. + RktPath string `json:"rktPath"` + // rktApiEndpoint is the endpoint of the rkt API service to communicate with. + RktAPIEndpoint string `json:"rktAPIEndpoint"` + // rktStage1Image is the image to use as stage1. Local paths and + // http/https URLs are supported. + RktStage1Image string `json:"rktStage1Image"` + // lockFilePath is the path that kubelet will use to as a lock file. + // It uses this file as a lock to synchronize with other kubelet processes + // that may be running. + LockFilePath *string `json:"lockFilePath"` + // ExitOnLockContention is a flag that signifies to the kubelet that it is running + // in "bootstrap" mode. This requires that 'LockFilePath' has been set. + // This will cause the kubelet to listen to inotify events on the lock file, + // releasing it and exiting when another process tries to open that file. + ExitOnLockContention bool `json:"exitOnLockContention"` + // configureCBR0 enables the kublet to configure cbr0 based on + // Node.Spec.PodCIDR. + ConfigureCBR0 *bool `json:"configureCbr0"` + // How should the kubelet configure the container bridge for hairpin packets. + // Setting this flag allows endpoints in a Service to loadbalance back to + // themselves if they should try to access their own Service. Values: + // "promiscuous-bridge": make the container bridge promiscuous. + // "hairpin-veth": set the hairpin flag on container veth interfaces. + // "none": do nothing. + // Setting --configure-cbr0 to false implies that to achieve hairpin NAT + // one must set --hairpin-mode=veth-flag, because bridge assumes the + // existence of a container bridge named cbr0. + HairpinMode string `json:"hairpinMode"` + // The node has babysitter process monitoring docker and kubelet. + BabysitDaemons bool `json:"babysitDaemons"` + // maxPods is the number of pods that can run on this Kubelet. + MaxPods int32 `json:"maxPods"` + // nvidiaGPUs is the number of NVIDIA GPU devices on this node. + NvidiaGPUs int32 `json:"nvidiaGPUs"` + // dockerExecHandlerName is the handler to use when executing a command + // in a container. Valid values are 'native' and 'nsenter'. Defaults to + // 'native'. + DockerExecHandlerName string `json:"dockerExecHandlerName"` + // The CIDR to use for pod IP addresses, only used in standalone mode. + // In cluster mode, this is obtained from the master. + PodCIDR string `json:"podCIDR"` + // ResolverConfig is the resolver configuration file used as the basis + // for the container DNS resolution configuration."), [] + ResolverConfig string `json:"resolvConf"` + // cpuCFSQuota is Enable CPU CFS quota enforcement for containers that + // specify CPU limits + CPUCFSQuota *bool `json:"cpuCFSQuota"` + // containerized should be set to true if kubelet is running in a container. + Containerized *bool `json:"containerized"` + // maxOpenFiles is Number of files that can be opened by Kubelet process. + MaxOpenFiles int64 `json:"maxOpenFiles"` + // reconcileCIDR is Reconcile node CIDR with the CIDR specified by the + // API server. No-op if register-node or configure-cbr0 is false. + ReconcileCIDR *bool `json:"reconcileCIDR"` + // registerSchedulable tells the kubelet to register the node as + // schedulable. No-op if register-node is false. + RegisterSchedulable *bool `json:"registerSchedulable"` + // contentType is contentType of requests sent to apiserver. + ContentType string `json:"contentType"` + // kubeAPIQPS is the QPS to use while talking with kubernetes apiserver + KubeAPIQPS *int32 `json:"kubeAPIQPS"` + // kubeAPIBurst is the burst to allow while talking with kubernetes + // apiserver + KubeAPIBurst int32 `json:"kubeAPIBurst"` + // serializeImagePulls when enabled, tells the Kubelet to pull images one + // at a time. We recommend *not* changing the default value on nodes that + // run docker daemon with version < 1.9 or an Aufs storage backend. + // Issue #10959 has more details. + SerializeImagePulls *bool `json:"serializeImagePulls"` + // experimentalFlannelOverlay enables experimental support for starting the + // kubelet with the default overlay network (flannel). Assumes flanneld + // is already running in client mode. + ExperimentalFlannelOverlay bool `json:"experimentalFlannelOverlay"` + // outOfDiskTransitionFrequency is duration for which the kubelet has to + // wait before transitioning out of out-of-disk node condition status. + OutOfDiskTransitionFrequency unversioned.Duration `json:"outOfDiskTransitionFrequency"` + // nodeIP is IP address of the node. If set, kubelet will use this IP + // address for the node. + NodeIP string `json:"nodeIP"` + // nodeLabels to add when registering the node in the cluster. + NodeLabels map[string]string `json:"nodeLabels"` + // nonMasqueradeCIDR configures masquerading: traffic to IPs outside this range will use IP masquerade. + NonMasqueradeCIDR string `json:"nonMasqueradeCIDR"` + // enable gathering custom metrics. + EnableCustomMetrics bool `json:"enableCustomMetrics"` + // Comma-delimited list of hard eviction expressions. For example, 'memory.available<300Mi'. + EvictionHard *string `json:"evictionHard"` + // Comma-delimited list of soft eviction expressions. For example, 'memory.available<300Mi'. + EvictionSoft string `json:"evictionSoft"` + // Comma-delimeted list of grace periods for each soft eviction signal. For example, 'memory.available=30s'. + EvictionSoftGracePeriod string `json:"evictionSoftGracePeriod"` + // Duration for which the kubelet has to wait before transitioning out of an eviction pressure condition. + EvictionPressureTransitionPeriod unversioned.Duration `json:"evictionPressureTransitionPeriod"` + // Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met. + EvictionMaxPodGracePeriod int32 `json:"evictionMaxPodGracePeriod"` + // Comma-delimited list of minimum reclaims (e.g. imagefs.available=2Gi) that describes the minimum amount of resource the kubelet will reclaim when performing a pod eviction if that resource is under pressure. + EvictionMinimumReclaim string `json:"evictionMinimumReclaim"` + // Maximum number of pods per core. Cannot exceed MaxPods + PodsPerCore int32 `json:"podsPerCore"` + // enableControllerAttachDetach enables the Attach/Detach controller to + // manage attachment/detachment of volumes scheduled to this node, and + // disables kubelet from executing any attach/detach operations + EnableControllerAttachDetach *bool `json:"enableControllerAttachDetach"` + // A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs + // that describe resources reserved for non-kubernetes components. + // Currently only cpu and memory are supported. [default=none] + // See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. + SystemReserved map[string]string `json:"systemReserved"` + // A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=150G) pairs + // that describe resources reserved for kubernetes system components. + // Currently only cpu and memory are supported. [default=none] + // See http://releases.k8s.io/HEAD/docs/user-guide/compute-resources.md for more detail. + KubeReserved map[string]string `json:"kubeReserved"` +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.conversion.go new file mode 100644 index 000000000000..d9a2d8cbe8e5 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.conversion.go @@ -0,0 +1,516 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by conversion-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + componentconfig "k8s.io/kubernetes/pkg/apis/componentconfig" + conversion "k8s.io/kubernetes/pkg/conversion" + config "k8s.io/kubernetes/pkg/util/config" +) + +func init() { + if err := api.Scheme.AddGeneratedConversionFuncs( + Convert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration, + Convert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration, + Convert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration, + Convert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration, + Convert_v1alpha1_KubeletConfiguration_To_componentconfig_KubeletConfiguration, + Convert_componentconfig_KubeletConfiguration_To_v1alpha1_KubeletConfiguration, + Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration, + Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration, + ); err != nil { + // if one of the conversion functions is malformed, detect it immediately. + panic(err) + } +} + +func autoConvert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in *KubeProxyConfiguration, out *componentconfig.KubeProxyConfiguration, s conversion.Scope) error { + SetDefaults_KubeProxyConfiguration(in) + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.BindAddress = in.BindAddress + out.ClusterCIDR = in.ClusterCIDR + out.HealthzBindAddress = in.HealthzBindAddress + out.HealthzPort = in.HealthzPort + out.HostnameOverride = in.HostnameOverride + out.IPTablesMasqueradeBit = in.IPTablesMasqueradeBit + out.IPTablesSyncPeriod = in.IPTablesSyncPeriod + out.KubeconfigPath = in.KubeconfigPath + out.MasqueradeAll = in.MasqueradeAll + out.Master = in.Master + out.OOMScoreAdj = in.OOMScoreAdj + out.Mode = componentconfig.ProxyMode(in.Mode) + out.PortRange = in.PortRange + out.ResourceContainer = in.ResourceContainer + out.UDPIdleTimeout = in.UDPIdleTimeout + out.ConntrackMax = in.ConntrackMax + out.ConntrackMaxPerCore = in.ConntrackMaxPerCore + out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout + return nil +} + +func Convert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in *KubeProxyConfiguration, out *componentconfig.KubeProxyConfiguration, s conversion.Scope) error { + return autoConvert_v1alpha1_KubeProxyConfiguration_To_componentconfig_KubeProxyConfiguration(in, out, s) +} + +func autoConvert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in *componentconfig.KubeProxyConfiguration, out *KubeProxyConfiguration, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.BindAddress = in.BindAddress + out.ClusterCIDR = in.ClusterCIDR + out.HealthzBindAddress = in.HealthzBindAddress + out.HealthzPort = in.HealthzPort + out.HostnameOverride = in.HostnameOverride + out.IPTablesMasqueradeBit = in.IPTablesMasqueradeBit + out.IPTablesSyncPeriod = in.IPTablesSyncPeriod + out.KubeconfigPath = in.KubeconfigPath + out.MasqueradeAll = in.MasqueradeAll + out.Master = in.Master + out.OOMScoreAdj = in.OOMScoreAdj + out.Mode = ProxyMode(in.Mode) + out.PortRange = in.PortRange + out.ResourceContainer = in.ResourceContainer + out.UDPIdleTimeout = in.UDPIdleTimeout + out.ConntrackMax = in.ConntrackMax + out.ConntrackMaxPerCore = in.ConntrackMaxPerCore + out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout + return nil +} + +func Convert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in *componentconfig.KubeProxyConfiguration, out *KubeProxyConfiguration, s conversion.Scope) error { + return autoConvert_componentconfig_KubeProxyConfiguration_To_v1alpha1_KubeProxyConfiguration(in, out, s) +} + +func autoConvert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in *KubeSchedulerConfiguration, out *componentconfig.KubeSchedulerConfiguration, s conversion.Scope) error { + SetDefaults_KubeSchedulerConfiguration(in) + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Port = int32(in.Port) + out.Address = in.Address + out.AlgorithmProvider = in.AlgorithmProvider + out.PolicyConfigFile = in.PolicyConfigFile + if err := api.Convert_Pointer_bool_To_bool(&in.EnableProfiling, &out.EnableProfiling, s); err != nil { + return err + } + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = int32(in.KubeAPIBurst) + out.SchedulerName = in.SchedulerName + out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight + out.FailureDomains = in.FailureDomains + if err := Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(&in.LeaderElection, &out.LeaderElection, s); err != nil { + return err + } + return nil +} + +func Convert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in *KubeSchedulerConfiguration, out *componentconfig.KubeSchedulerConfiguration, s conversion.Scope) error { + return autoConvert_v1alpha1_KubeSchedulerConfiguration_To_componentconfig_KubeSchedulerConfiguration(in, out, s) +} + +func autoConvert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in *componentconfig.KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Port = int(in.Port) + out.Address = in.Address + out.AlgorithmProvider = in.AlgorithmProvider + out.PolicyConfigFile = in.PolicyConfigFile + if err := api.Convert_bool_To_Pointer_bool(&in.EnableProfiling, &out.EnableProfiling, s); err != nil { + return err + } + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = int(in.KubeAPIBurst) + out.SchedulerName = in.SchedulerName + out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight + out.FailureDomains = in.FailureDomains + if err := Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(&in.LeaderElection, &out.LeaderElection, s); err != nil { + return err + } + return nil +} + +func Convert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in *componentconfig.KubeSchedulerConfiguration, out *KubeSchedulerConfiguration, s conversion.Scope) error { + return autoConvert_componentconfig_KubeSchedulerConfiguration_To_v1alpha1_KubeSchedulerConfiguration(in, out, s) +} + +func autoConvert_v1alpha1_KubeletConfiguration_To_componentconfig_KubeletConfiguration(in *KubeletConfiguration, out *componentconfig.KubeletConfiguration, s conversion.Scope) error { + SetDefaults_KubeletConfiguration(in) + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Config = in.Config + out.SyncFrequency = in.SyncFrequency + out.FileCheckFrequency = in.FileCheckFrequency + out.HTTPCheckFrequency = in.HTTPCheckFrequency + out.ManifestURL = in.ManifestURL + out.ManifestURLHeader = in.ManifestURLHeader + if err := api.Convert_Pointer_bool_To_bool(&in.EnableServer, &out.EnableServer, s); err != nil { + return err + } + out.Address = in.Address + out.Port = in.Port + out.ReadOnlyPort = in.ReadOnlyPort + out.TLSCertFile = in.TLSCertFile + out.TLSPrivateKeyFile = in.TLSPrivateKeyFile + out.CertDirectory = in.CertDirectory + out.HostnameOverride = in.HostnameOverride + out.PodInfraContainerImage = in.PodInfraContainerImage + out.DockerEndpoint = in.DockerEndpoint + out.RootDirectory = in.RootDirectory + out.SeccompProfileRoot = in.SeccompProfileRoot + if err := api.Convert_Pointer_bool_To_bool(&in.AllowPrivileged, &out.AllowPrivileged, s); err != nil { + return err + } + out.HostNetworkSources = in.HostNetworkSources + out.HostPIDSources = in.HostPIDSources + out.HostIPCSources = in.HostIPCSources + if err := api.Convert_Pointer_int32_To_int32(&in.RegistryPullQPS, &out.RegistryPullQPS, s); err != nil { + return err + } + out.RegistryBurst = in.RegistryBurst + if err := api.Convert_Pointer_int32_To_int32(&in.EventRecordQPS, &out.EventRecordQPS, s); err != nil { + return err + } + out.EventBurst = in.EventBurst + if err := api.Convert_Pointer_bool_To_bool(&in.EnableDebuggingHandlers, &out.EnableDebuggingHandlers, s); err != nil { + return err + } + out.MinimumGCAge = in.MinimumGCAge + out.MaxPerPodContainerCount = in.MaxPerPodContainerCount + if err := api.Convert_Pointer_int32_To_int32(&in.MaxContainerCount, &out.MaxContainerCount, s); err != nil { + return err + } + out.CAdvisorPort = in.CAdvisorPort + out.HealthzPort = in.HealthzPort + out.HealthzBindAddress = in.HealthzBindAddress + if err := api.Convert_Pointer_int32_To_int32(&in.OOMScoreAdj, &out.OOMScoreAdj, s); err != nil { + return err + } + if err := api.Convert_Pointer_bool_To_bool(&in.RegisterNode, &out.RegisterNode, s); err != nil { + return err + } + out.ClusterDomain = in.ClusterDomain + out.MasterServiceNamespace = in.MasterServiceNamespace + out.ClusterDNS = in.ClusterDNS + out.StreamingConnectionIdleTimeout = in.StreamingConnectionIdleTimeout + out.NodeStatusUpdateFrequency = in.NodeStatusUpdateFrequency + out.ImageMinimumGCAge = in.ImageMinimumGCAge + if err := api.Convert_Pointer_int32_To_int32(&in.ImageGCHighThresholdPercent, &out.ImageGCHighThresholdPercent, s); err != nil { + return err + } + if err := api.Convert_Pointer_int32_To_int32(&in.ImageGCLowThresholdPercent, &out.ImageGCLowThresholdPercent, s); err != nil { + return err + } + out.LowDiskSpaceThresholdMB = in.LowDiskSpaceThresholdMB + out.VolumeStatsAggPeriod = in.VolumeStatsAggPeriod + out.NetworkPluginName = in.NetworkPluginName + out.NetworkPluginDir = in.NetworkPluginDir + out.VolumePluginDir = in.VolumePluginDir + out.CloudProvider = in.CloudProvider + out.CloudConfigFile = in.CloudConfigFile + out.KubeletCgroups = in.KubeletCgroups + out.RuntimeCgroups = in.RuntimeCgroups + out.SystemCgroups = in.SystemCgroups + out.CgroupRoot = in.CgroupRoot + if err := api.Convert_Pointer_bool_To_bool(&in.CgroupsPerQOS, &out.CgroupsPerQOS, s); err != nil { + return err + } + out.ContainerRuntime = in.ContainerRuntime + out.RuntimeRequestTimeout = in.RuntimeRequestTimeout + out.RktPath = in.RktPath + out.RktAPIEndpoint = in.RktAPIEndpoint + out.RktStage1Image = in.RktStage1Image + if err := api.Convert_Pointer_string_To_string(&in.LockFilePath, &out.LockFilePath, s); err != nil { + return err + } + out.ExitOnLockContention = in.ExitOnLockContention + if err := api.Convert_Pointer_bool_To_bool(&in.ConfigureCBR0, &out.ConfigureCBR0, s); err != nil { + return err + } + out.HairpinMode = in.HairpinMode + out.BabysitDaemons = in.BabysitDaemons + out.MaxPods = in.MaxPods + out.NvidiaGPUs = in.NvidiaGPUs + out.DockerExecHandlerName = in.DockerExecHandlerName + out.PodCIDR = in.PodCIDR + out.ResolverConfig = in.ResolverConfig + if err := api.Convert_Pointer_bool_To_bool(&in.CPUCFSQuota, &out.CPUCFSQuota, s); err != nil { + return err + } + if err := api.Convert_Pointer_bool_To_bool(&in.Containerized, &out.Containerized, s); err != nil { + return err + } + out.MaxOpenFiles = in.MaxOpenFiles + if err := api.Convert_Pointer_bool_To_bool(&in.ReconcileCIDR, &out.ReconcileCIDR, s); err != nil { + return err + } + if err := api.Convert_Pointer_bool_To_bool(&in.RegisterSchedulable, &out.RegisterSchedulable, s); err != nil { + return err + } + out.ContentType = in.ContentType + if err := api.Convert_Pointer_int32_To_int32(&in.KubeAPIQPS, &out.KubeAPIQPS, s); err != nil { + return err + } + out.KubeAPIBurst = in.KubeAPIBurst + if err := api.Convert_Pointer_bool_To_bool(&in.SerializeImagePulls, &out.SerializeImagePulls, s); err != nil { + return err + } + out.ExperimentalFlannelOverlay = in.ExperimentalFlannelOverlay + out.OutOfDiskTransitionFrequency = in.OutOfDiskTransitionFrequency + out.NodeIP = in.NodeIP + out.NodeLabels = in.NodeLabels + out.NonMasqueradeCIDR = in.NonMasqueradeCIDR + out.EnableCustomMetrics = in.EnableCustomMetrics + if err := api.Convert_Pointer_string_To_string(&in.EvictionHard, &out.EvictionHard, s); err != nil { + return err + } + out.EvictionSoft = in.EvictionSoft + out.EvictionSoftGracePeriod = in.EvictionSoftGracePeriod + out.EvictionPressureTransitionPeriod = in.EvictionPressureTransitionPeriod + out.EvictionMaxPodGracePeriod = in.EvictionMaxPodGracePeriod + out.EvictionMinimumReclaim = in.EvictionMinimumReclaim + out.PodsPerCore = in.PodsPerCore + if err := api.Convert_Pointer_bool_To_bool(&in.EnableControllerAttachDetach, &out.EnableControllerAttachDetach, s); err != nil { + return err + } + if in.SystemReserved != nil { + in, out := &in.SystemReserved, &out.SystemReserved + *out = make(config.ConfigurationMap, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.SystemReserved = nil + } + if in.KubeReserved != nil { + in, out := &in.KubeReserved, &out.KubeReserved + *out = make(config.ConfigurationMap, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.KubeReserved = nil + } + return nil +} + +func Convert_v1alpha1_KubeletConfiguration_To_componentconfig_KubeletConfiguration(in *KubeletConfiguration, out *componentconfig.KubeletConfiguration, s conversion.Scope) error { + return autoConvert_v1alpha1_KubeletConfiguration_To_componentconfig_KubeletConfiguration(in, out, s) +} + +func autoConvert_componentconfig_KubeletConfiguration_To_v1alpha1_KubeletConfiguration(in *componentconfig.KubeletConfiguration, out *KubeletConfiguration, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Config = in.Config + out.SyncFrequency = in.SyncFrequency + out.FileCheckFrequency = in.FileCheckFrequency + out.HTTPCheckFrequency = in.HTTPCheckFrequency + out.ManifestURL = in.ManifestURL + out.ManifestURLHeader = in.ManifestURLHeader + if err := api.Convert_bool_To_Pointer_bool(&in.EnableServer, &out.EnableServer, s); err != nil { + return err + } + out.Address = in.Address + out.Port = in.Port + out.ReadOnlyPort = in.ReadOnlyPort + out.TLSCertFile = in.TLSCertFile + out.TLSPrivateKeyFile = in.TLSPrivateKeyFile + out.CertDirectory = in.CertDirectory + out.HostnameOverride = in.HostnameOverride + out.PodInfraContainerImage = in.PodInfraContainerImage + out.DockerEndpoint = in.DockerEndpoint + out.RootDirectory = in.RootDirectory + out.SeccompProfileRoot = in.SeccompProfileRoot + if err := api.Convert_bool_To_Pointer_bool(&in.AllowPrivileged, &out.AllowPrivileged, s); err != nil { + return err + } + out.HostNetworkSources = in.HostNetworkSources + out.HostPIDSources = in.HostPIDSources + out.HostIPCSources = in.HostIPCSources + if err := api.Convert_int32_To_Pointer_int32(&in.RegistryPullQPS, &out.RegistryPullQPS, s); err != nil { + return err + } + out.RegistryBurst = in.RegistryBurst + if err := api.Convert_int32_To_Pointer_int32(&in.EventRecordQPS, &out.EventRecordQPS, s); err != nil { + return err + } + out.EventBurst = in.EventBurst + if err := api.Convert_bool_To_Pointer_bool(&in.EnableDebuggingHandlers, &out.EnableDebuggingHandlers, s); err != nil { + return err + } + out.MinimumGCAge = in.MinimumGCAge + out.MaxPerPodContainerCount = in.MaxPerPodContainerCount + if err := api.Convert_int32_To_Pointer_int32(&in.MaxContainerCount, &out.MaxContainerCount, s); err != nil { + return err + } + out.CAdvisorPort = in.CAdvisorPort + out.HealthzPort = in.HealthzPort + out.HealthzBindAddress = in.HealthzBindAddress + if err := api.Convert_int32_To_Pointer_int32(&in.OOMScoreAdj, &out.OOMScoreAdj, s); err != nil { + return err + } + if err := api.Convert_bool_To_Pointer_bool(&in.RegisterNode, &out.RegisterNode, s); err != nil { + return err + } + out.ClusterDomain = in.ClusterDomain + out.MasterServiceNamespace = in.MasterServiceNamespace + out.ClusterDNS = in.ClusterDNS + out.StreamingConnectionIdleTimeout = in.StreamingConnectionIdleTimeout + out.NodeStatusUpdateFrequency = in.NodeStatusUpdateFrequency + out.ImageMinimumGCAge = in.ImageMinimumGCAge + if err := api.Convert_int32_To_Pointer_int32(&in.ImageGCHighThresholdPercent, &out.ImageGCHighThresholdPercent, s); err != nil { + return err + } + if err := api.Convert_int32_To_Pointer_int32(&in.ImageGCLowThresholdPercent, &out.ImageGCLowThresholdPercent, s); err != nil { + return err + } + out.LowDiskSpaceThresholdMB = in.LowDiskSpaceThresholdMB + out.VolumeStatsAggPeriod = in.VolumeStatsAggPeriod + out.NetworkPluginName = in.NetworkPluginName + out.NetworkPluginDir = in.NetworkPluginDir + out.VolumePluginDir = in.VolumePluginDir + out.CloudProvider = in.CloudProvider + out.CloudConfigFile = in.CloudConfigFile + out.KubeletCgroups = in.KubeletCgroups + if err := api.Convert_bool_To_Pointer_bool(&in.CgroupsPerQOS, &out.CgroupsPerQOS, s); err != nil { + return err + } + out.RuntimeCgroups = in.RuntimeCgroups + out.SystemCgroups = in.SystemCgroups + out.CgroupRoot = in.CgroupRoot + out.ContainerRuntime = in.ContainerRuntime + out.RuntimeRequestTimeout = in.RuntimeRequestTimeout + out.RktPath = in.RktPath + out.RktAPIEndpoint = in.RktAPIEndpoint + out.RktStage1Image = in.RktStage1Image + if err := api.Convert_string_To_Pointer_string(&in.LockFilePath, &out.LockFilePath, s); err != nil { + return err + } + out.ExitOnLockContention = in.ExitOnLockContention + if err := api.Convert_bool_To_Pointer_bool(&in.ConfigureCBR0, &out.ConfigureCBR0, s); err != nil { + return err + } + out.HairpinMode = in.HairpinMode + out.BabysitDaemons = in.BabysitDaemons + out.MaxPods = in.MaxPods + out.NvidiaGPUs = in.NvidiaGPUs + out.DockerExecHandlerName = in.DockerExecHandlerName + out.PodCIDR = in.PodCIDR + out.ResolverConfig = in.ResolverConfig + if err := api.Convert_bool_To_Pointer_bool(&in.CPUCFSQuota, &out.CPUCFSQuota, s); err != nil { + return err + } + if err := api.Convert_bool_To_Pointer_bool(&in.Containerized, &out.Containerized, s); err != nil { + return err + } + out.MaxOpenFiles = in.MaxOpenFiles + if err := api.Convert_bool_To_Pointer_bool(&in.ReconcileCIDR, &out.ReconcileCIDR, s); err != nil { + return err + } + if err := api.Convert_bool_To_Pointer_bool(&in.RegisterSchedulable, &out.RegisterSchedulable, s); err != nil { + return err + } + out.ContentType = in.ContentType + if err := api.Convert_int32_To_Pointer_int32(&in.KubeAPIQPS, &out.KubeAPIQPS, s); err != nil { + return err + } + out.KubeAPIBurst = in.KubeAPIBurst + if err := api.Convert_bool_To_Pointer_bool(&in.SerializeImagePulls, &out.SerializeImagePulls, s); err != nil { + return err + } + out.ExperimentalFlannelOverlay = in.ExperimentalFlannelOverlay + out.OutOfDiskTransitionFrequency = in.OutOfDiskTransitionFrequency + out.NodeIP = in.NodeIP + out.NodeLabels = in.NodeLabels + out.NonMasqueradeCIDR = in.NonMasqueradeCIDR + out.EnableCustomMetrics = in.EnableCustomMetrics + if err := api.Convert_string_To_Pointer_string(&in.EvictionHard, &out.EvictionHard, s); err != nil { + return err + } + out.EvictionSoft = in.EvictionSoft + out.EvictionSoftGracePeriod = in.EvictionSoftGracePeriod + out.EvictionPressureTransitionPeriod = in.EvictionPressureTransitionPeriod + out.EvictionMaxPodGracePeriod = in.EvictionMaxPodGracePeriod + out.EvictionMinimumReclaim = in.EvictionMinimumReclaim + out.PodsPerCore = in.PodsPerCore + if err := api.Convert_bool_To_Pointer_bool(&in.EnableControllerAttachDetach, &out.EnableControllerAttachDetach, s); err != nil { + return err + } + if in.SystemReserved != nil { + in, out := &in.SystemReserved, &out.SystemReserved + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.SystemReserved = nil + } + if in.KubeReserved != nil { + in, out := &in.KubeReserved, &out.KubeReserved + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.KubeReserved = nil + } + return nil +} + +func Convert_componentconfig_KubeletConfiguration_To_v1alpha1_KubeletConfiguration(in *componentconfig.KubeletConfiguration, out *KubeletConfiguration, s conversion.Scope) error { + return autoConvert_componentconfig_KubeletConfiguration_To_v1alpha1_KubeletConfiguration(in, out, s) +} + +func autoConvert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *componentconfig.LeaderElectionConfiguration, s conversion.Scope) error { + SetDefaults_LeaderElectionConfiguration(in) + if err := api.Convert_Pointer_bool_To_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil { + return err + } + out.LeaseDuration = in.LeaseDuration + out.RenewDeadline = in.RenewDeadline + out.RetryPeriod = in.RetryPeriod + return nil +} + +func Convert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *componentconfig.LeaderElectionConfiguration, s conversion.Scope) error { + return autoConvert_v1alpha1_LeaderElectionConfiguration_To_componentconfig_LeaderElectionConfiguration(in, out, s) +} + +func autoConvert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *componentconfig.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error { + if err := api.Convert_bool_To_Pointer_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil { + return err + } + out.LeaseDuration = in.LeaseDuration + out.RenewDeadline = in.RenewDeadline + out.RetryPeriod = in.RetryPeriod + return nil +} + +func Convert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *componentconfig.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error { + return autoConvert_componentconfig_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in, out, s) +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..9235a379f56f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,397 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_KubeProxyConfiguration, InType: reflect.TypeOf(func() *KubeProxyConfiguration { var x *KubeProxyConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_KubeSchedulerConfiguration, InType: reflect.TypeOf(func() *KubeSchedulerConfiguration { var x *KubeSchedulerConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_KubeletConfiguration, InType: reflect.TypeOf(func() *KubeletConfiguration { var x *KubeletConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_LeaderElectionConfiguration, InType: reflect.TypeOf(func() *LeaderElectionConfiguration { var x *LeaderElectionConfiguration; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1alpha1_KubeProxyConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeProxyConfiguration) + out := out.(*KubeProxyConfiguration) + out.TypeMeta = in.TypeMeta + out.BindAddress = in.BindAddress + out.ClusterCIDR = in.ClusterCIDR + out.HealthzBindAddress = in.HealthzBindAddress + out.HealthzPort = in.HealthzPort + out.HostnameOverride = in.HostnameOverride + if in.IPTablesMasqueradeBit != nil { + in, out := &in.IPTablesMasqueradeBit, &out.IPTablesMasqueradeBit + *out = new(int32) + **out = **in + } else { + out.IPTablesMasqueradeBit = nil + } + out.IPTablesSyncPeriod = in.IPTablesSyncPeriod + out.KubeconfigPath = in.KubeconfigPath + out.MasqueradeAll = in.MasqueradeAll + out.Master = in.Master + if in.OOMScoreAdj != nil { + in, out := &in.OOMScoreAdj, &out.OOMScoreAdj + *out = new(int32) + **out = **in + } else { + out.OOMScoreAdj = nil + } + out.Mode = in.Mode + out.PortRange = in.PortRange + out.ResourceContainer = in.ResourceContainer + out.UDPIdleTimeout = in.UDPIdleTimeout + out.ConntrackMax = in.ConntrackMax + out.ConntrackMaxPerCore = in.ConntrackMaxPerCore + out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout + return nil + } +} + +func DeepCopy_v1alpha1_KubeSchedulerConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeSchedulerConfiguration) + out := out.(*KubeSchedulerConfiguration) + out.TypeMeta = in.TypeMeta + out.Port = in.Port + out.Address = in.Address + out.AlgorithmProvider = in.AlgorithmProvider + out.PolicyConfigFile = in.PolicyConfigFile + if in.EnableProfiling != nil { + in, out := &in.EnableProfiling, &out.EnableProfiling + *out = new(bool) + **out = **in + } else { + out.EnableProfiling = nil + } + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = in.KubeAPIBurst + out.SchedulerName = in.SchedulerName + out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight + out.FailureDomains = in.FailureDomains + if err := DeepCopy_v1alpha1_LeaderElectionConfiguration(&in.LeaderElection, &out.LeaderElection, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1alpha1_KubeletConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeletConfiguration) + out := out.(*KubeletConfiguration) + out.TypeMeta = in.TypeMeta + out.Config = in.Config + out.SyncFrequency = in.SyncFrequency + out.FileCheckFrequency = in.FileCheckFrequency + out.HTTPCheckFrequency = in.HTTPCheckFrequency + out.ManifestURL = in.ManifestURL + out.ManifestURLHeader = in.ManifestURLHeader + if in.EnableServer != nil { + in, out := &in.EnableServer, &out.EnableServer + *out = new(bool) + **out = **in + } else { + out.EnableServer = nil + } + out.Address = in.Address + out.Port = in.Port + out.ReadOnlyPort = in.ReadOnlyPort + out.TLSCertFile = in.TLSCertFile + out.TLSPrivateKeyFile = in.TLSPrivateKeyFile + out.CertDirectory = in.CertDirectory + out.HostnameOverride = in.HostnameOverride + out.PodInfraContainerImage = in.PodInfraContainerImage + out.DockerEndpoint = in.DockerEndpoint + out.RootDirectory = in.RootDirectory + out.SeccompProfileRoot = in.SeccompProfileRoot + if in.AllowPrivileged != nil { + in, out := &in.AllowPrivileged, &out.AllowPrivileged + *out = new(bool) + **out = **in + } else { + out.AllowPrivileged = nil + } + if in.HostNetworkSources != nil { + in, out := &in.HostNetworkSources, &out.HostNetworkSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostNetworkSources = nil + } + if in.HostPIDSources != nil { + in, out := &in.HostPIDSources, &out.HostPIDSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostPIDSources = nil + } + if in.HostIPCSources != nil { + in, out := &in.HostIPCSources, &out.HostIPCSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostIPCSources = nil + } + if in.RegistryPullQPS != nil { + in, out := &in.RegistryPullQPS, &out.RegistryPullQPS + *out = new(int32) + **out = **in + } else { + out.RegistryPullQPS = nil + } + out.RegistryBurst = in.RegistryBurst + if in.EventRecordQPS != nil { + in, out := &in.EventRecordQPS, &out.EventRecordQPS + *out = new(int32) + **out = **in + } else { + out.EventRecordQPS = nil + } + out.EventBurst = in.EventBurst + if in.EnableDebuggingHandlers != nil { + in, out := &in.EnableDebuggingHandlers, &out.EnableDebuggingHandlers + *out = new(bool) + **out = **in + } else { + out.EnableDebuggingHandlers = nil + } + out.MinimumGCAge = in.MinimumGCAge + out.MaxPerPodContainerCount = in.MaxPerPodContainerCount + if in.MaxContainerCount != nil { + in, out := &in.MaxContainerCount, &out.MaxContainerCount + *out = new(int32) + **out = **in + } else { + out.MaxContainerCount = nil + } + out.CAdvisorPort = in.CAdvisorPort + out.HealthzPort = in.HealthzPort + out.HealthzBindAddress = in.HealthzBindAddress + if in.OOMScoreAdj != nil { + in, out := &in.OOMScoreAdj, &out.OOMScoreAdj + *out = new(int32) + **out = **in + } else { + out.OOMScoreAdj = nil + } + if in.RegisterNode != nil { + in, out := &in.RegisterNode, &out.RegisterNode + *out = new(bool) + **out = **in + } else { + out.RegisterNode = nil + } + out.ClusterDomain = in.ClusterDomain + out.MasterServiceNamespace = in.MasterServiceNamespace + out.ClusterDNS = in.ClusterDNS + out.StreamingConnectionIdleTimeout = in.StreamingConnectionIdleTimeout + out.NodeStatusUpdateFrequency = in.NodeStatusUpdateFrequency + out.ImageMinimumGCAge = in.ImageMinimumGCAge + if in.ImageGCHighThresholdPercent != nil { + in, out := &in.ImageGCHighThresholdPercent, &out.ImageGCHighThresholdPercent + *out = new(int32) + **out = **in + } else { + out.ImageGCHighThresholdPercent = nil + } + if in.ImageGCLowThresholdPercent != nil { + in, out := &in.ImageGCLowThresholdPercent, &out.ImageGCLowThresholdPercent + *out = new(int32) + **out = **in + } else { + out.ImageGCLowThresholdPercent = nil + } + out.LowDiskSpaceThresholdMB = in.LowDiskSpaceThresholdMB + out.VolumeStatsAggPeriod = in.VolumeStatsAggPeriod + out.NetworkPluginName = in.NetworkPluginName + out.NetworkPluginDir = in.NetworkPluginDir + out.VolumePluginDir = in.VolumePluginDir + out.CloudProvider = in.CloudProvider + out.CloudConfigFile = in.CloudConfigFile + out.KubeletCgroups = in.KubeletCgroups + out.RuntimeCgroups = in.RuntimeCgroups + out.SystemCgroups = in.SystemCgroups + out.CgroupRoot = in.CgroupRoot + if in.CgroupsPerQOS != nil { + in, out := &in.CgroupsPerQOS, &out.CgroupsPerQOS + *out = new(bool) + **out = **in + } else { + out.CgroupsPerQOS = nil + } + out.ContainerRuntime = in.ContainerRuntime + out.RuntimeRequestTimeout = in.RuntimeRequestTimeout + out.RktPath = in.RktPath + out.RktAPIEndpoint = in.RktAPIEndpoint + out.RktStage1Image = in.RktStage1Image + if in.LockFilePath != nil { + in, out := &in.LockFilePath, &out.LockFilePath + *out = new(string) + **out = **in + } else { + out.LockFilePath = nil + } + out.ExitOnLockContention = in.ExitOnLockContention + if in.ConfigureCBR0 != nil { + in, out := &in.ConfigureCBR0, &out.ConfigureCBR0 + *out = new(bool) + **out = **in + } else { + out.ConfigureCBR0 = nil + } + out.HairpinMode = in.HairpinMode + out.BabysitDaemons = in.BabysitDaemons + out.MaxPods = in.MaxPods + out.NvidiaGPUs = in.NvidiaGPUs + out.DockerExecHandlerName = in.DockerExecHandlerName + out.PodCIDR = in.PodCIDR + out.ResolverConfig = in.ResolverConfig + if in.CPUCFSQuota != nil { + in, out := &in.CPUCFSQuota, &out.CPUCFSQuota + *out = new(bool) + **out = **in + } else { + out.CPUCFSQuota = nil + } + if in.Containerized != nil { + in, out := &in.Containerized, &out.Containerized + *out = new(bool) + **out = **in + } else { + out.Containerized = nil + } + out.MaxOpenFiles = in.MaxOpenFiles + if in.ReconcileCIDR != nil { + in, out := &in.ReconcileCIDR, &out.ReconcileCIDR + *out = new(bool) + **out = **in + } else { + out.ReconcileCIDR = nil + } + if in.RegisterSchedulable != nil { + in, out := &in.RegisterSchedulable, &out.RegisterSchedulable + *out = new(bool) + **out = **in + } else { + out.RegisterSchedulable = nil + } + out.ContentType = in.ContentType + if in.KubeAPIQPS != nil { + in, out := &in.KubeAPIQPS, &out.KubeAPIQPS + *out = new(int32) + **out = **in + } else { + out.KubeAPIQPS = nil + } + out.KubeAPIBurst = in.KubeAPIBurst + if in.SerializeImagePulls != nil { + in, out := &in.SerializeImagePulls, &out.SerializeImagePulls + *out = new(bool) + **out = **in + } else { + out.SerializeImagePulls = nil + } + out.ExperimentalFlannelOverlay = in.ExperimentalFlannelOverlay + out.OutOfDiskTransitionFrequency = in.OutOfDiskTransitionFrequency + out.NodeIP = in.NodeIP + if in.NodeLabels != nil { + in, out := &in.NodeLabels, &out.NodeLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.NodeLabels = nil + } + out.NonMasqueradeCIDR = in.NonMasqueradeCIDR + out.EnableCustomMetrics = in.EnableCustomMetrics + if in.EvictionHard != nil { + in, out := &in.EvictionHard, &out.EvictionHard + *out = new(string) + **out = **in + } else { + out.EvictionHard = nil + } + out.EvictionSoft = in.EvictionSoft + out.EvictionSoftGracePeriod = in.EvictionSoftGracePeriod + out.EvictionPressureTransitionPeriod = in.EvictionPressureTransitionPeriod + out.EvictionMaxPodGracePeriod = in.EvictionMaxPodGracePeriod + out.EvictionMinimumReclaim = in.EvictionMinimumReclaim + out.PodsPerCore = in.PodsPerCore + if in.EnableControllerAttachDetach != nil { + in, out := &in.EnableControllerAttachDetach, &out.EnableControllerAttachDetach + *out = new(bool) + **out = **in + } else { + out.EnableControllerAttachDetach = nil + } + if in.SystemReserved != nil { + in, out := &in.SystemReserved, &out.SystemReserved + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.SystemReserved = nil + } + if in.KubeReserved != nil { + in, out := &in.KubeReserved, &out.KubeReserved + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.KubeReserved = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_LeaderElectionConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LeaderElectionConfiguration) + out := out.(*LeaderElectionConfiguration) + if in.LeaderElect != nil { + in, out := &in.LeaderElect, &out.LeaderElect + *out = new(bool) + **out = **in + } else { + out.LeaderElect = nil + } + out.LeaseDuration = in.LeaseDuration + out.RenewDeadline = in.RenewDeadline + out.RetryPeriod = in.RetryPeriod + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/zz_generated.deepcopy.go new file mode 100644 index 000000000000..2aca3f7fb2be --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/componentconfig/zz_generated.deepcopy.go @@ -0,0 +1,380 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package componentconfig + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + config "k8s.io/kubernetes/pkg/util/config" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_IPVar, InType: reflect.TypeOf(func() *IPVar { var x *IPVar; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_KubeControllerManagerConfiguration, InType: reflect.TypeOf(func() *KubeControllerManagerConfiguration { var x *KubeControllerManagerConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_KubeProxyConfiguration, InType: reflect.TypeOf(func() *KubeProxyConfiguration { var x *KubeProxyConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_KubeSchedulerConfiguration, InType: reflect.TypeOf(func() *KubeSchedulerConfiguration { var x *KubeSchedulerConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_KubeletConfiguration, InType: reflect.TypeOf(func() *KubeletConfiguration { var x *KubeletConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_LeaderElectionConfiguration, InType: reflect.TypeOf(func() *LeaderElectionConfiguration { var x *LeaderElectionConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_PersistentVolumeRecyclerConfiguration, InType: reflect.TypeOf(func() *PersistentVolumeRecyclerConfiguration { var x *PersistentVolumeRecyclerConfiguration; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_PortRangeVar, InType: reflect.TypeOf(func() *PortRangeVar { var x *PortRangeVar; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_componentconfig_VolumeConfiguration, InType: reflect.TypeOf(func() *VolumeConfiguration { var x *VolumeConfiguration; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_componentconfig_IPVar(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IPVar) + out := out.(*IPVar) + if in.Val != nil { + in, out := &in.Val, &out.Val + *out = new(string) + **out = **in + } else { + out.Val = nil + } + return nil + } +} + +func DeepCopy_componentconfig_KubeControllerManagerConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeControllerManagerConfiguration) + out := out.(*KubeControllerManagerConfiguration) + out.TypeMeta = in.TypeMeta + out.Port = in.Port + out.Address = in.Address + out.CloudProvider = in.CloudProvider + out.CloudConfigFile = in.CloudConfigFile + out.ConcurrentEndpointSyncs = in.ConcurrentEndpointSyncs + out.ConcurrentRSSyncs = in.ConcurrentRSSyncs + out.ConcurrentRCSyncs = in.ConcurrentRCSyncs + out.ConcurrentResourceQuotaSyncs = in.ConcurrentResourceQuotaSyncs + out.ConcurrentDeploymentSyncs = in.ConcurrentDeploymentSyncs + out.ConcurrentDaemonSetSyncs = in.ConcurrentDaemonSetSyncs + out.ConcurrentJobSyncs = in.ConcurrentJobSyncs + out.ConcurrentNamespaceSyncs = in.ConcurrentNamespaceSyncs + out.ConcurrentSATokenSyncs = in.ConcurrentSATokenSyncs + out.LookupCacheSizeForRC = in.LookupCacheSizeForRC + out.LookupCacheSizeForRS = in.LookupCacheSizeForRS + out.LookupCacheSizeForDaemonSet = in.LookupCacheSizeForDaemonSet + out.ServiceSyncPeriod = in.ServiceSyncPeriod + out.NodeSyncPeriod = in.NodeSyncPeriod + out.ResourceQuotaSyncPeriod = in.ResourceQuotaSyncPeriod + out.NamespaceSyncPeriod = in.NamespaceSyncPeriod + out.PVClaimBinderSyncPeriod = in.PVClaimBinderSyncPeriod + out.MinResyncPeriod = in.MinResyncPeriod + out.TerminatedPodGCThreshold = in.TerminatedPodGCThreshold + out.HorizontalPodAutoscalerSyncPeriod = in.HorizontalPodAutoscalerSyncPeriod + out.DeploymentControllerSyncPeriod = in.DeploymentControllerSyncPeriod + out.PodEvictionTimeout = in.PodEvictionTimeout + out.DeletingPodsQps = in.DeletingPodsQps + out.DeletingPodsBurst = in.DeletingPodsBurst + out.NodeMonitorGracePeriod = in.NodeMonitorGracePeriod + out.RegisterRetryCount = in.RegisterRetryCount + out.NodeStartupGracePeriod = in.NodeStartupGracePeriod + out.NodeMonitorPeriod = in.NodeMonitorPeriod + out.ServiceAccountKeyFile = in.ServiceAccountKeyFile + out.ClusterSigningCertFile = in.ClusterSigningCertFile + out.ClusterSigningKeyFile = in.ClusterSigningKeyFile + out.EnableProfiling = in.EnableProfiling + out.ClusterName = in.ClusterName + out.ClusterCIDR = in.ClusterCIDR + out.ServiceCIDR = in.ServiceCIDR + out.NodeCIDRMaskSize = in.NodeCIDRMaskSize + out.AllocateNodeCIDRs = in.AllocateNodeCIDRs + out.ConfigureCloudRoutes = in.ConfigureCloudRoutes + out.RootCAFile = in.RootCAFile + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = in.KubeAPIBurst + out.LeaderElection = in.LeaderElection + out.VolumeConfiguration = in.VolumeConfiguration + out.ControllerStartInterval = in.ControllerStartInterval + out.EnableGarbageCollector = in.EnableGarbageCollector + out.ConcurrentGCSyncs = in.ConcurrentGCSyncs + return nil + } +} + +func DeepCopy_componentconfig_KubeProxyConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeProxyConfiguration) + out := out.(*KubeProxyConfiguration) + out.TypeMeta = in.TypeMeta + out.BindAddress = in.BindAddress + out.ClusterCIDR = in.ClusterCIDR + out.HealthzBindAddress = in.HealthzBindAddress + out.HealthzPort = in.HealthzPort + out.HostnameOverride = in.HostnameOverride + if in.IPTablesMasqueradeBit != nil { + in, out := &in.IPTablesMasqueradeBit, &out.IPTablesMasqueradeBit + *out = new(int32) + **out = **in + } else { + out.IPTablesMasqueradeBit = nil + } + out.IPTablesSyncPeriod = in.IPTablesSyncPeriod + out.KubeconfigPath = in.KubeconfigPath + out.MasqueradeAll = in.MasqueradeAll + out.Master = in.Master + if in.OOMScoreAdj != nil { + in, out := &in.OOMScoreAdj, &out.OOMScoreAdj + *out = new(int32) + **out = **in + } else { + out.OOMScoreAdj = nil + } + out.Mode = in.Mode + out.PortRange = in.PortRange + out.ResourceContainer = in.ResourceContainer + out.UDPIdleTimeout = in.UDPIdleTimeout + out.ConntrackMax = in.ConntrackMax + out.ConntrackMaxPerCore = in.ConntrackMaxPerCore + out.ConntrackTCPEstablishedTimeout = in.ConntrackTCPEstablishedTimeout + return nil + } +} + +func DeepCopy_componentconfig_KubeSchedulerConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeSchedulerConfiguration) + out := out.(*KubeSchedulerConfiguration) + out.TypeMeta = in.TypeMeta + out.Port = in.Port + out.Address = in.Address + out.AlgorithmProvider = in.AlgorithmProvider + out.PolicyConfigFile = in.PolicyConfigFile + out.EnableProfiling = in.EnableProfiling + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = in.KubeAPIBurst + out.SchedulerName = in.SchedulerName + out.HardPodAffinitySymmetricWeight = in.HardPodAffinitySymmetricWeight + out.FailureDomains = in.FailureDomains + out.LeaderElection = in.LeaderElection + return nil + } +} + +func DeepCopy_componentconfig_KubeletConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*KubeletConfiguration) + out := out.(*KubeletConfiguration) + out.TypeMeta = in.TypeMeta + out.Config = in.Config + out.SyncFrequency = in.SyncFrequency + out.FileCheckFrequency = in.FileCheckFrequency + out.HTTPCheckFrequency = in.HTTPCheckFrequency + out.ManifestURL = in.ManifestURL + out.ManifestURLHeader = in.ManifestURLHeader + out.EnableServer = in.EnableServer + out.Address = in.Address + out.Port = in.Port + out.ReadOnlyPort = in.ReadOnlyPort + out.TLSCertFile = in.TLSCertFile + out.TLSPrivateKeyFile = in.TLSPrivateKeyFile + out.CertDirectory = in.CertDirectory + out.HostnameOverride = in.HostnameOverride + out.PodInfraContainerImage = in.PodInfraContainerImage + out.DockerEndpoint = in.DockerEndpoint + out.RootDirectory = in.RootDirectory + out.SeccompProfileRoot = in.SeccompProfileRoot + out.AllowPrivileged = in.AllowPrivileged + if in.HostNetworkSources != nil { + in, out := &in.HostNetworkSources, &out.HostNetworkSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostNetworkSources = nil + } + if in.HostPIDSources != nil { + in, out := &in.HostPIDSources, &out.HostPIDSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostPIDSources = nil + } + if in.HostIPCSources != nil { + in, out := &in.HostIPCSources, &out.HostIPCSources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.HostIPCSources = nil + } + out.RegistryPullQPS = in.RegistryPullQPS + out.RegistryBurst = in.RegistryBurst + out.EventRecordQPS = in.EventRecordQPS + out.EventBurst = in.EventBurst + out.EnableDebuggingHandlers = in.EnableDebuggingHandlers + out.MinimumGCAge = in.MinimumGCAge + out.MaxPerPodContainerCount = in.MaxPerPodContainerCount + out.MaxContainerCount = in.MaxContainerCount + out.CAdvisorPort = in.CAdvisorPort + out.HealthzPort = in.HealthzPort + out.HealthzBindAddress = in.HealthzBindAddress + out.OOMScoreAdj = in.OOMScoreAdj + out.RegisterNode = in.RegisterNode + out.ClusterDomain = in.ClusterDomain + out.MasterServiceNamespace = in.MasterServiceNamespace + out.ClusterDNS = in.ClusterDNS + out.StreamingConnectionIdleTimeout = in.StreamingConnectionIdleTimeout + out.NodeStatusUpdateFrequency = in.NodeStatusUpdateFrequency + out.ImageMinimumGCAge = in.ImageMinimumGCAge + out.ImageGCHighThresholdPercent = in.ImageGCHighThresholdPercent + out.ImageGCLowThresholdPercent = in.ImageGCLowThresholdPercent + out.LowDiskSpaceThresholdMB = in.LowDiskSpaceThresholdMB + out.VolumeStatsAggPeriod = in.VolumeStatsAggPeriod + out.NetworkPluginName = in.NetworkPluginName + out.NetworkPluginDir = in.NetworkPluginDir + out.VolumePluginDir = in.VolumePluginDir + out.CloudProvider = in.CloudProvider + out.CloudConfigFile = in.CloudConfigFile + out.KubeletCgroups = in.KubeletCgroups + out.CgroupsPerQOS = in.CgroupsPerQOS + out.RuntimeCgroups = in.RuntimeCgroups + out.SystemCgroups = in.SystemCgroups + out.CgroupRoot = in.CgroupRoot + out.ContainerRuntime = in.ContainerRuntime + out.RuntimeRequestTimeout = in.RuntimeRequestTimeout + out.RktPath = in.RktPath + out.RktAPIEndpoint = in.RktAPIEndpoint + out.RktStage1Image = in.RktStage1Image + out.LockFilePath = in.LockFilePath + out.ExitOnLockContention = in.ExitOnLockContention + out.ConfigureCBR0 = in.ConfigureCBR0 + out.HairpinMode = in.HairpinMode + out.BabysitDaemons = in.BabysitDaemons + out.MaxPods = in.MaxPods + out.NvidiaGPUs = in.NvidiaGPUs + out.DockerExecHandlerName = in.DockerExecHandlerName + out.PodCIDR = in.PodCIDR + out.ResolverConfig = in.ResolverConfig + out.CPUCFSQuota = in.CPUCFSQuota + out.Containerized = in.Containerized + out.MaxOpenFiles = in.MaxOpenFiles + out.ReconcileCIDR = in.ReconcileCIDR + out.RegisterSchedulable = in.RegisterSchedulable + out.ContentType = in.ContentType + out.KubeAPIQPS = in.KubeAPIQPS + out.KubeAPIBurst = in.KubeAPIBurst + out.SerializeImagePulls = in.SerializeImagePulls + out.ExperimentalFlannelOverlay = in.ExperimentalFlannelOverlay + out.OutOfDiskTransitionFrequency = in.OutOfDiskTransitionFrequency + out.NodeIP = in.NodeIP + if in.NodeLabels != nil { + in, out := &in.NodeLabels, &out.NodeLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.NodeLabels = nil + } + out.NonMasqueradeCIDR = in.NonMasqueradeCIDR + out.EnableCustomMetrics = in.EnableCustomMetrics + out.EvictionHard = in.EvictionHard + out.EvictionSoft = in.EvictionSoft + out.EvictionSoftGracePeriod = in.EvictionSoftGracePeriod + out.EvictionPressureTransitionPeriod = in.EvictionPressureTransitionPeriod + out.EvictionMaxPodGracePeriod = in.EvictionMaxPodGracePeriod + out.EvictionMinimumReclaim = in.EvictionMinimumReclaim + out.PodsPerCore = in.PodsPerCore + out.EnableControllerAttachDetach = in.EnableControllerAttachDetach + if in.SystemReserved != nil { + in, out := &in.SystemReserved, &out.SystemReserved + *out = make(config.ConfigurationMap) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.SystemReserved = nil + } + if in.KubeReserved != nil { + in, out := &in.KubeReserved, &out.KubeReserved + *out = make(config.ConfigurationMap) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.KubeReserved = nil + } + return nil + } +} + +func DeepCopy_componentconfig_LeaderElectionConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LeaderElectionConfiguration) + out := out.(*LeaderElectionConfiguration) + out.LeaderElect = in.LeaderElect + out.LeaseDuration = in.LeaseDuration + out.RenewDeadline = in.RenewDeadline + out.RetryPeriod = in.RetryPeriod + return nil + } +} + +func DeepCopy_componentconfig_PersistentVolumeRecyclerConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PersistentVolumeRecyclerConfiguration) + out := out.(*PersistentVolumeRecyclerConfiguration) + out.MaximumRetry = in.MaximumRetry + out.MinimumTimeoutNFS = in.MinimumTimeoutNFS + out.PodTemplateFilePathNFS = in.PodTemplateFilePathNFS + out.IncrementTimeoutNFS = in.IncrementTimeoutNFS + out.PodTemplateFilePathHostPath = in.PodTemplateFilePathHostPath + out.MinimumTimeoutHostPath = in.MinimumTimeoutHostPath + out.IncrementTimeoutHostPath = in.IncrementTimeoutHostPath + return nil + } +} + +func DeepCopy_componentconfig_PortRangeVar(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PortRangeVar) + out := out.(*PortRangeVar) + if in.Val != nil { + in, out := &in.Val, &out.Val + *out = new(string) + **out = **in + } else { + out.Val = nil + } + return nil + } +} + +func DeepCopy_componentconfig_VolumeConfiguration(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*VolumeConfiguration) + out := out.(*VolumeConfiguration) + out.EnableHostPathProvisioning = in.EnableHostPathProvisioning + out.EnableDynamicProvisioning = in.EnableDynamicProvisioning + out.PersistentVolumeRecyclerConfiguration = in.PersistentVolumeRecyclerConfiguration + out.FlexVolumePluginDir = in.FlexVolumePluginDir + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/deep_copy_generated.go deleted file mode 100644 index 118d478c28b0..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/deep_copy_generated.go +++ /dev/null @@ -1,958 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package extensions - -import ( - api "k8s.io/kubernetes/pkg/api" - resource "k8s.io/kubernetes/pkg/api/resource" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_extensions_APIVersion, - DeepCopy_extensions_CustomMetricCurrentStatus, - DeepCopy_extensions_CustomMetricCurrentStatusList, - DeepCopy_extensions_CustomMetricTarget, - DeepCopy_extensions_CustomMetricTargetList, - DeepCopy_extensions_DaemonSet, - DeepCopy_extensions_DaemonSetList, - DeepCopy_extensions_DaemonSetSpec, - DeepCopy_extensions_DaemonSetStatus, - DeepCopy_extensions_Deployment, - DeepCopy_extensions_DeploymentList, - DeepCopy_extensions_DeploymentRollback, - DeepCopy_extensions_DeploymentSpec, - DeepCopy_extensions_DeploymentStatus, - DeepCopy_extensions_DeploymentStrategy, - DeepCopy_extensions_FSGroupStrategyOptions, - DeepCopy_extensions_HTTPIngressPath, - DeepCopy_extensions_HTTPIngressRuleValue, - DeepCopy_extensions_HostPortRange, - DeepCopy_extensions_IDRange, - DeepCopy_extensions_Ingress, - DeepCopy_extensions_IngressBackend, - DeepCopy_extensions_IngressList, - DeepCopy_extensions_IngressRule, - DeepCopy_extensions_IngressRuleValue, - DeepCopy_extensions_IngressSpec, - DeepCopy_extensions_IngressStatus, - DeepCopy_extensions_IngressTLS, - DeepCopy_extensions_NetworkPolicy, - DeepCopy_extensions_NetworkPolicyIngressRule, - DeepCopy_extensions_NetworkPolicyList, - DeepCopy_extensions_NetworkPolicyPeer, - DeepCopy_extensions_NetworkPolicyPort, - DeepCopy_extensions_NetworkPolicySpec, - DeepCopy_extensions_PodSecurityPolicy, - DeepCopy_extensions_PodSecurityPolicyList, - DeepCopy_extensions_PodSecurityPolicySpec, - DeepCopy_extensions_ReplicaSet, - DeepCopy_extensions_ReplicaSetList, - DeepCopy_extensions_ReplicaSetSpec, - DeepCopy_extensions_ReplicaSetStatus, - DeepCopy_extensions_ReplicationControllerDummy, - DeepCopy_extensions_RollbackConfig, - DeepCopy_extensions_RollingUpdateDeployment, - DeepCopy_extensions_RunAsUserStrategyOptions, - DeepCopy_extensions_SELinuxStrategyOptions, - DeepCopy_extensions_Scale, - DeepCopy_extensions_ScaleSpec, - DeepCopy_extensions_ScaleStatus, - DeepCopy_extensions_SupplementalGroupsStrategyOptions, - DeepCopy_extensions_ThirdPartyResource, - DeepCopy_extensions_ThirdPartyResourceData, - DeepCopy_extensions_ThirdPartyResourceDataList, - DeepCopy_extensions_ThirdPartyResourceList, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_extensions_APIVersion(in APIVersion, out *APIVersion, c *conversion.Cloner) error { - out.Name = in.Name - return nil -} - -func DeepCopy_extensions_CustomMetricCurrentStatus(in CustomMetricCurrentStatus, out *CustomMetricCurrentStatus, c *conversion.Cloner) error { - out.Name = in.Name - if err := resource.DeepCopy_resource_Quantity(in.CurrentValue, &out.CurrentValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_CustomMetricCurrentStatusList(in CustomMetricCurrentStatusList, out *CustomMetricCurrentStatusList, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]CustomMetricCurrentStatus, len(in)) - for i := range in { - if err := DeepCopy_extensions_CustomMetricCurrentStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_CustomMetricTarget(in CustomMetricTarget, out *CustomMetricTarget, c *conversion.Cloner) error { - out.Name = in.Name - if err := resource.DeepCopy_resource_Quantity(in.TargetValue, &out.TargetValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_CustomMetricTargetList(in CustomMetricTargetList, out *CustomMetricTargetList, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]CustomMetricTarget, len(in)) - for i := range in { - if err := DeepCopy_extensions_CustomMetricTarget(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_DaemonSet(in DaemonSet, out *DaemonSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_DaemonSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_extensions_DaemonSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_DaemonSetList(in DaemonSetList, out *DaemonSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]DaemonSet, len(in)) - for i := range in { - if err := DeepCopy_extensions_DaemonSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_DaemonSetSpec(in DaemonSetSpec, out *DaemonSetSpec, c *conversion.Cloner) error { - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := api.DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_DaemonSetStatus(in DaemonSetStatus, out *DaemonSetStatus, c *conversion.Cloner) error { - out.CurrentNumberScheduled = in.CurrentNumberScheduled - out.NumberMisscheduled = in.NumberMisscheduled - out.DesiredNumberScheduled = in.DesiredNumberScheduled - return nil -} - -func DeepCopy_extensions_Deployment(in Deployment, out *Deployment, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_DeploymentSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_extensions_DeploymentStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_DeploymentList(in DeploymentList, out *DeploymentList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Deployment, len(in)) - for i := range in { - if err := DeepCopy_extensions_Deployment(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_DeploymentRollback(in DeploymentRollback, out *DeploymentRollback, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Name = in.Name - if in.UpdatedAnnotations != nil { - in, out := in.UpdatedAnnotations, &out.UpdatedAnnotations - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.UpdatedAnnotations = nil - } - if err := DeepCopy_extensions_RollbackConfig(in.RollbackTo, &out.RollbackTo, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_DeploymentSpec(in DeploymentSpec, out *DeploymentSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := api.DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - if err := DeepCopy_extensions_DeploymentStrategy(in.Strategy, &out.Strategy, c); err != nil { - return err - } - out.MinReadySeconds = in.MinReadySeconds - if in.RevisionHistoryLimit != nil { - in, out := in.RevisionHistoryLimit, &out.RevisionHistoryLimit - *out = new(int32) - **out = *in - } else { - out.RevisionHistoryLimit = nil - } - out.Paused = in.Paused - if in.RollbackTo != nil { - in, out := in.RollbackTo, &out.RollbackTo - *out = new(RollbackConfig) - if err := DeepCopy_extensions_RollbackConfig(*in, *out, c); err != nil { - return err - } - } else { - out.RollbackTo = nil - } - return nil -} - -func DeepCopy_extensions_DeploymentStatus(in DeploymentStatus, out *DeploymentStatus, c *conversion.Cloner) error { - out.ObservedGeneration = in.ObservedGeneration - out.Replicas = in.Replicas - out.UpdatedReplicas = in.UpdatedReplicas - out.AvailableReplicas = in.AvailableReplicas - out.UnavailableReplicas = in.UnavailableReplicas - return nil -} - -func DeepCopy_extensions_DeploymentStrategy(in DeploymentStrategy, out *DeploymentStrategy, c *conversion.Cloner) error { - out.Type = in.Type - if in.RollingUpdate != nil { - in, out := in.RollingUpdate, &out.RollingUpdate - *out = new(RollingUpdateDeployment) - if err := DeepCopy_extensions_RollingUpdateDeployment(*in, *out, c); err != nil { - return err - } - } else { - out.RollingUpdate = nil - } - return nil -} - -func DeepCopy_extensions_FSGroupStrategyOptions(in FSGroupStrategyOptions, out *FSGroupStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_extensions_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_extensions_HTTPIngressPath(in HTTPIngressPath, out *HTTPIngressPath, c *conversion.Cloner) error { - out.Path = in.Path - if err := DeepCopy_extensions_IngressBackend(in.Backend, &out.Backend, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_HTTPIngressRuleValue(in HTTPIngressRuleValue, out *HTTPIngressRuleValue, c *conversion.Cloner) error { - if in.Paths != nil { - in, out := in.Paths, &out.Paths - *out = make([]HTTPIngressPath, len(in)) - for i := range in { - if err := DeepCopy_extensions_HTTPIngressPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Paths = nil - } - return nil -} - -func DeepCopy_extensions_HostPortRange(in HostPortRange, out *HostPortRange, c *conversion.Cloner) error { - out.Min = in.Min - out.Max = in.Max - return nil -} - -func DeepCopy_extensions_IDRange(in IDRange, out *IDRange, c *conversion.Cloner) error { - out.Min = in.Min - out.Max = in.Max - return nil -} - -func DeepCopy_extensions_Ingress(in Ingress, out *Ingress, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_IngressSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_extensions_IngressStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_IngressBackend(in IngressBackend, out *IngressBackend, c *conversion.Cloner) error { - out.ServiceName = in.ServiceName - if err := intstr.DeepCopy_intstr_IntOrString(in.ServicePort, &out.ServicePort, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_IngressList(in IngressList, out *IngressList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Ingress, len(in)) - for i := range in { - if err := DeepCopy_extensions_Ingress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_IngressRule(in IngressRule, out *IngressRule, c *conversion.Cloner) error { - out.Host = in.Host - if err := DeepCopy_extensions_IngressRuleValue(in.IngressRuleValue, &out.IngressRuleValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_IngressRuleValue(in IngressRuleValue, out *IngressRuleValue, c *conversion.Cloner) error { - if in.HTTP != nil { - in, out := in.HTTP, &out.HTTP - *out = new(HTTPIngressRuleValue) - if err := DeepCopy_extensions_HTTPIngressRuleValue(*in, *out, c); err != nil { - return err - } - } else { - out.HTTP = nil - } - return nil -} - -func DeepCopy_extensions_IngressSpec(in IngressSpec, out *IngressSpec, c *conversion.Cloner) error { - if in.Backend != nil { - in, out := in.Backend, &out.Backend - *out = new(IngressBackend) - if err := DeepCopy_extensions_IngressBackend(*in, *out, c); err != nil { - return err - } - } else { - out.Backend = nil - } - if in.TLS != nil { - in, out := in.TLS, &out.TLS - *out = make([]IngressTLS, len(in)) - for i := range in { - if err := DeepCopy_extensions_IngressTLS(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.TLS = nil - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]IngressRule, len(in)) - for i := range in { - if err := DeepCopy_extensions_IngressRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_extensions_IngressStatus(in IngressStatus, out *IngressStatus, c *conversion.Cloner) error { - if err := api.DeepCopy_api_LoadBalancerStatus(in.LoadBalancer, &out.LoadBalancer, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_IngressTLS(in IngressTLS, out *IngressTLS, c *conversion.Cloner) error { - if in.Hosts != nil { - in, out := in.Hosts, &out.Hosts - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Hosts = nil - } - out.SecretName = in.SecretName - return nil -} - -func DeepCopy_extensions_NetworkPolicy(in NetworkPolicy, out *NetworkPolicy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_NetworkPolicySpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_NetworkPolicyIngressRule(in NetworkPolicyIngressRule, out *NetworkPolicyIngressRule, c *conversion.Cloner) error { - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]NetworkPolicyPort, len(in)) - for i := range in { - if err := DeepCopy_extensions_NetworkPolicyPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.From != nil { - in, out := in.From, &out.From - *out = make([]NetworkPolicyPeer, len(in)) - for i := range in { - if err := DeepCopy_extensions_NetworkPolicyPeer(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.From = nil - } - return nil -} - -func DeepCopy_extensions_NetworkPolicyList(in NetworkPolicyList, out *NetworkPolicyList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]NetworkPolicy, len(in)) - for i := range in { - if err := DeepCopy_extensions_NetworkPolicy(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_NetworkPolicyPeer(in NetworkPolicyPeer, out *NetworkPolicyPeer, c *conversion.Cloner) error { - if in.PodSelector != nil { - in, out := in.PodSelector, &out.PodSelector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.PodSelector = nil - } - if in.NamespaceSelector != nil { - in, out := in.NamespaceSelector, &out.NamespaceSelector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.NamespaceSelector = nil - } - return nil -} - -func DeepCopy_extensions_NetworkPolicyPort(in NetworkPolicyPort, out *NetworkPolicyPort, c *conversion.Cloner) error { - if in.Protocol != nil { - in, out := in.Protocol, &out.Protocol - *out = new(api.Protocol) - **out = *in - } else { - out.Protocol = nil - } - if in.Port != nil { - in, out := in.Port, &out.Port - *out = new(intstr.IntOrString) - if err := intstr.DeepCopy_intstr_IntOrString(*in, *out, c); err != nil { - return err - } - } else { - out.Port = nil - } - return nil -} - -func DeepCopy_extensions_NetworkPolicySpec(in NetworkPolicySpec, out *NetworkPolicySpec, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_LabelSelector(in.PodSelector, &out.PodSelector, c); err != nil { - return err - } - if in.Ingress != nil { - in, out := in.Ingress, &out.Ingress - *out = make([]NetworkPolicyIngressRule, len(in)) - for i := range in { - if err := DeepCopy_extensions_NetworkPolicyIngressRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ingress = nil - } - return nil -} - -func DeepCopy_extensions_PodSecurityPolicy(in PodSecurityPolicy, out *PodSecurityPolicy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_PodSecurityPolicySpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_PodSecurityPolicyList(in PodSecurityPolicyList, out *PodSecurityPolicyList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodSecurityPolicy, len(in)) - for i := range in { - if err := DeepCopy_extensions_PodSecurityPolicy(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_PodSecurityPolicySpec(in PodSecurityPolicySpec, out *PodSecurityPolicySpec, c *conversion.Cloner) error { - out.Privileged = in.Privileged - if in.DefaultAddCapabilities != nil { - in, out := in.DefaultAddCapabilities, &out.DefaultAddCapabilities - *out = make([]api.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.DefaultAddCapabilities = nil - } - if in.RequiredDropCapabilities != nil { - in, out := in.RequiredDropCapabilities, &out.RequiredDropCapabilities - *out = make([]api.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.RequiredDropCapabilities = nil - } - if in.AllowedCapabilities != nil { - in, out := in.AllowedCapabilities, &out.AllowedCapabilities - *out = make([]api.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AllowedCapabilities = nil - } - if in.Volumes != nil { - in, out := in.Volumes, &out.Volumes - *out = make([]FSType, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Volumes = nil - } - out.HostNetwork = in.HostNetwork - if in.HostPorts != nil { - in, out := in.HostPorts, &out.HostPorts - *out = make([]HostPortRange, len(in)) - for i := range in { - if err := DeepCopy_extensions_HostPortRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.HostPorts = nil - } - out.HostPID = in.HostPID - out.HostIPC = in.HostIPC - if err := DeepCopy_extensions_SELinuxStrategyOptions(in.SELinux, &out.SELinux, c); err != nil { - return err - } - if err := DeepCopy_extensions_RunAsUserStrategyOptions(in.RunAsUser, &out.RunAsUser, c); err != nil { - return err - } - if err := DeepCopy_extensions_SupplementalGroupsStrategyOptions(in.SupplementalGroups, &out.SupplementalGroups, c); err != nil { - return err - } - if err := DeepCopy_extensions_FSGroupStrategyOptions(in.FSGroup, &out.FSGroup, c); err != nil { - return err - } - out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem - return nil -} - -func DeepCopy_extensions_ReplicaSet(in ReplicaSet, out *ReplicaSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_ReplicaSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_extensions_ReplicaSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_ReplicaSetList(in ReplicaSetList, out *ReplicaSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ReplicaSet, len(in)) - for i := range in { - if err := DeepCopy_extensions_ReplicaSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_ReplicaSetSpec(in ReplicaSetSpec, out *ReplicaSetSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := api.DeepCopy_api_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_ReplicaSetStatus(in ReplicaSetStatus, out *ReplicaSetStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.FullyLabeledReplicas = in.FullyLabeledReplicas - out.ObservedGeneration = in.ObservedGeneration - return nil -} - -func DeepCopy_extensions_ReplicationControllerDummy(in ReplicationControllerDummy, out *ReplicationControllerDummy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_RollbackConfig(in RollbackConfig, out *RollbackConfig, c *conversion.Cloner) error { - out.Revision = in.Revision - return nil -} - -func DeepCopy_extensions_RollingUpdateDeployment(in RollingUpdateDeployment, out *RollingUpdateDeployment, c *conversion.Cloner) error { - if err := intstr.DeepCopy_intstr_IntOrString(in.MaxUnavailable, &out.MaxUnavailable, c); err != nil { - return err - } - if err := intstr.DeepCopy_intstr_IntOrString(in.MaxSurge, &out.MaxSurge, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_RunAsUserStrategyOptions(in RunAsUserStrategyOptions, out *RunAsUserStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_extensions_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_extensions_SELinuxStrategyOptions(in SELinuxStrategyOptions, out *SELinuxStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(api.SELinuxOptions) - if err := api.DeepCopy_api_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - return nil -} - -func DeepCopy_extensions_Scale(in Scale, out *Scale, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_extensions_ScaleSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_extensions_ScaleStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_extensions_ScaleSpec(in ScaleSpec, out *ScaleSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - return nil -} - -func DeepCopy_extensions_ScaleStatus(in ScaleStatus, out *ScaleStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - return nil -} - -func DeepCopy_extensions_SupplementalGroupsStrategyOptions(in SupplementalGroupsStrategyOptions, out *SupplementalGroupsStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_extensions_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_extensions_ThirdPartyResource(in ThirdPartyResource, out *ThirdPartyResource, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - out.Description = in.Description - if in.Versions != nil { - in, out := in.Versions, &out.Versions - *out = make([]APIVersion, len(in)) - for i := range in { - if err := DeepCopy_extensions_APIVersion(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Versions = nil - } - return nil -} - -func DeepCopy_extensions_ThirdPartyResourceData(in ThirdPartyResourceData, out *ThirdPartyResourceData, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_extensions_ThirdPartyResourceDataList(in ThirdPartyResourceDataList, out *ThirdPartyResourceDataList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ThirdPartyResourceData, len(in)) - for i := range in { - if err := DeepCopy_extensions_ThirdPartyResourceData(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_extensions_ThirdPartyResourceList(in ThirdPartyResourceList, out *ThirdPartyResourceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ThirdPartyResource, len(in)) - for i := range in { - if err := DeepCopy_extensions_ThirdPartyResource(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/doc.go new file mode 100644 index 000000000000..2bbb71d0571d --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package extensions diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/install/install.go index 449127084b32..5fe3abbd72ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -93,6 +93,7 @@ func newRESTMapper(externalVersions []unversioned.GroupVersion) meta.RESTMapper rootScoped := sets.NewString( "PodSecurityPolicy", "ThirdPartyResource", + "StorageClass", ) ignoredKinds := sets.NewString() diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/register.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/register.go index 1c5f6ba105ab..480a38d97923 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -75,5 +75,7 @@ func addKnownTypes(scheme *runtime.Scheme) { &PodSecurityPolicyList{}, &NetworkPolicy{}, &NetworkPolicyList{}, + &StorageClass{}, + &StorageClassList{}, ) } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go index eec90fb0a2cd..265f2ffdf4e4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15508,6 +15508,718 @@ func (x *NetworkPolicyList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x *StorageClass) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [5]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[2] = len(x.Parameters) != 0 + yyq2[3] = x.Kind != "" + yyq2[4] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(5) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ObjectMeta + yy4.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ObjectMeta + yy6.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Provisioner)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("provisioner")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Provisioner)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + if x.Parameters == nil { + r.EncodeNil() + } else { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + z.F.EncMapStringStringV(x.Parameters, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("parameters")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Parameters == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + z.F.EncMapStringStringV(x.Parameters, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym18 := z.EncBinary() + _ = yym18 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *StorageClass) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *StorageClass) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_api.ObjectMeta{} + } else { + yyv4 := &x.ObjectMeta + yyv4.CodecDecodeSelf(d) + } + case "provisioner": + if r.TryDecodeAsNil() { + x.Provisioner = "" + } else { + x.Provisioner = string(r.DecodeString()) + } + case "parameters": + if r.TryDecodeAsNil() { + x.Parameters = nil + } else { + yyv6 := &x.Parameters + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + z.F.DecMapStringStringX(yyv6, false, d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *StorageClass) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_api.ObjectMeta{} + } else { + yyv11 := &x.ObjectMeta + yyv11.CodecDecodeSelf(d) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Provisioner = "" + } else { + x.Provisioner = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Parameters = nil + } else { + yyv13 := &x.Parameters + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + z.F.DecMapStringStringX(yyv13, false, d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *StorageClassList) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[2] = x.Kind != "" + yyq2[3] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ListMeta + yym5 := z.EncBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.EncExt(yy4) { + } else { + z.EncFallback(yy4) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ListMeta + yym7 := z.EncBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.EncExt(yy6) { + } else { + z.EncFallback(yy6) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceStorageClass(([]StorageClass)(x.Items), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("items")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceStorageClass(([]StorageClass)(x.Items), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *StorageClassList) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *StorageClassList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv4 := &x.ListMeta + yym5 := z.DecBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.DecExt(yyv4) { + } else { + z.DecFallback(yyv4, false) + } + } + case "items": + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv6 := &x.Items + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSliceStorageClass((*[]StorageClass)(yyv6), d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *StorageClassList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv11 := &x.ListMeta + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else { + z.DecFallback(yyv11, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv13 := &x.Items + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSliceStorageClass((*[]StorageClass)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + func (x codecSelfer1234) encSliceCustomMetricTarget(v []CustomMetricTarget, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -17989,3 +18701,122 @@ func (x codecSelfer1234) decSliceNetworkPolicy(v *[]NetworkPolicy, d *codec1978. *v = yyv1 } } + +func (x codecSelfer1234) encSliceStorageClass(v []StorageClass, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceStorageClass(v *[]StorageClass, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []StorageClass{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 264) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]StorageClass, yyrl1) + } + } else { + yyv1 = make([]StorageClass, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, StorageClass{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, StorageClass{}) // var yyz1 StorageClass + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []StorageClass{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.go index 9db03ab7ce8c..95b1b935fb94 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -47,22 +47,23 @@ type ScaleStatus struct { Replicas int32 `json:"replicas"` // label query over pods that should match the replicas count. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *unversioned.LabelSelector `json:"selector,omitempty"` } -// +genclient=true,noMethods=true +// +genclient=true +// +noMethods=true // represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. api.ObjectMeta `json:"metadata,omitempty"` - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty"` - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty"` } @@ -94,7 +95,8 @@ type CustomMetricCurrentStatusList struct { Items []CustomMetricCurrentStatus `json:"items"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // A ThirdPartyResource is a generic representation of a resource, it is used by add-ons and plugins to add new resource // types to the API. It consists of one or more Versions of the api. @@ -330,14 +332,14 @@ type DaemonSetSpec struct { // Selector is a label query over pods that are managed by the daemon set. // Must match in order to be controlled. // If empty, defaulted to labels on Pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *unversioned.LabelSelector `json:"selector,omitempty"` // Template is the object that describes the pod that will be created. // The DaemonSet will create exactly one copy of this pod on every node // that matches the template's node selector (or on every node if no node // selector is specified). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template Template api.PodTemplateSpec `json:"template"` // TODO(madhusudancs): Uncomment while implementing DaemonSet updates. @@ -384,18 +386,18 @@ type DaemonSetStatus struct { type DaemonSet struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec DaemonSetSpec `json:"spec,omitempty"` // Status is the current status of this daemon set. This data may be // out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status DaemonSetStatus `json:"status,omitempty"` } @@ -403,7 +405,7 @@ type DaemonSet struct { type DaemonSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of daemon sets. @@ -413,7 +415,7 @@ type DaemonSetList struct { type ThirdPartyResourceDataList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is a list of third party objects Items []ThirdPartyResourceData `json:"items"` @@ -428,15 +430,15 @@ type ThirdPartyResourceDataList struct { type Ingress struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata api.ObjectMeta `json:"metadata,omitempty"` // Spec is the desired state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec IngressSpec `json:"spec,omitempty"` // Status is the current state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status IngressStatus `json:"status,omitempty"` } @@ -444,7 +446,7 @@ type Ingress struct { type IngressList struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty"` // Items is the list of Ingress. @@ -604,7 +606,7 @@ type ReplicaSetSpec struct { // Selector is a label query over pods that should match the replica count. // Must match in order to be controlled. // If empty, defaulted to labels on pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *unversioned.LabelSelector `json:"selector,omitempty"` // Template is the object that describes the pod that will be created if @@ -624,7 +626,8 @@ type ReplicaSetStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // PodSecurityPolicy governs the ability to make requests that affect the SecurityContext // that will be applied to a pod and container. @@ -641,7 +644,7 @@ type PodSecurityPolicySpec struct { // Privileged determines if a pod can request to be run as privileged. Privileged bool `json:"privileged,omitempty"` // DefaultAddCapabilities is the default set of capabilities that will be added to the container - // unless the pod spec specifically drops the capability. You may not list a capabiility in both + // unless the pod spec specifically drops the capability. You may not list a capability in both // DefaultAddCapabilities and RequiredDropCapabilities. DefaultAddCapabilities []api.Capability `json:"defaultAddCapabilities,omitempty"` // RequiredDropCapabilities are the capabilities that will be dropped from the container. These @@ -719,7 +722,7 @@ type SELinuxStrategyOptions struct { // Rule is the strategy that will dictate the allowable labels that may be set. Rule SELinuxStrategy `json:"rule"` // seLinuxOptions required to run as; required for MustRunAs - // More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md#security-context + // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md#security-context SELinuxOptions *api.SELinuxOptions `json:"seLinuxOptions,omitempty"` } @@ -896,3 +899,41 @@ type NetworkPolicyList struct { Items []NetworkPolicy `json:"items"` } + +// +genclient=true +// +nonNamespaced=true + +// StorageClass describes a named "class" of storage offered in a cluster. +// Different classes might map to quality-of-service levels, or to backup policies, +// or to arbitrary policies determined by the cluster administrators. Kubernetes +// itself is unopinionated about what classes represent. This concept is sometimes +// called "profiles" in other storage systems. +// The name of a StorageClass object is significant, and is how users can request a particular class. +type StorageClass struct { + unversioned.TypeMeta `json:",inline"` + api.ObjectMeta `json:"metadata,omitempty"` + + // provisioner is the driver expected to handle this StorageClass. + // This is an optionally-prefixed name, like a label key. + // For example: "kubernetes.io/gce-pd" or "kubernetes.io/aws-ebs". + // This value may not be empty. + Provisioner string `json:"provisioner"` + + // parameters holds parameters for the provisioner. + // These values are opaque to the system and are passed directly + // to the provisioner. The only validation done on keys is that they are + // not empty. The maximum number of parameters is + // 512, with a cumulative max size of 256K + Parameters map[string]string `json:"parameters,omitempty"` +} + +// StorageClassList is a collection of storage classes. +type StorageClassList struct { + unversioned.TypeMeta `json:",inline"` + // Standard list metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + unversioned.ListMeta `json:"metadata,omitempty"` + + // Items is the list of StorageClasses + Items []StorageClass `json:"items"` +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go index ad5c91c90e50..d685ebfee55b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go deleted file mode 100644 index 32debd197f0a..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/deep_copy_generated.go +++ /dev/null @@ -1,1297 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1beta1 - -import ( - api "k8s.io/kubernetes/pkg/api" - resource "k8s.io/kubernetes/pkg/api/resource" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1beta1_APIVersion, - DeepCopy_v1beta1_CPUTargetUtilization, - DeepCopy_v1beta1_CustomMetricCurrentStatus, - DeepCopy_v1beta1_CustomMetricCurrentStatusList, - DeepCopy_v1beta1_CustomMetricTarget, - DeepCopy_v1beta1_CustomMetricTargetList, - DeepCopy_v1beta1_DaemonSet, - DeepCopy_v1beta1_DaemonSetList, - DeepCopy_v1beta1_DaemonSetSpec, - DeepCopy_v1beta1_DaemonSetStatus, - DeepCopy_v1beta1_Deployment, - DeepCopy_v1beta1_DeploymentList, - DeepCopy_v1beta1_DeploymentRollback, - DeepCopy_v1beta1_DeploymentSpec, - DeepCopy_v1beta1_DeploymentStatus, - DeepCopy_v1beta1_DeploymentStrategy, - DeepCopy_v1beta1_ExportOptions, - DeepCopy_v1beta1_FSGroupStrategyOptions, - DeepCopy_v1beta1_HTTPIngressPath, - DeepCopy_v1beta1_HTTPIngressRuleValue, - DeepCopy_v1beta1_HorizontalPodAutoscaler, - DeepCopy_v1beta1_HorizontalPodAutoscalerList, - DeepCopy_v1beta1_HorizontalPodAutoscalerSpec, - DeepCopy_v1beta1_HorizontalPodAutoscalerStatus, - DeepCopy_v1beta1_HostPortRange, - DeepCopy_v1beta1_IDRange, - DeepCopy_v1beta1_Ingress, - DeepCopy_v1beta1_IngressBackend, - DeepCopy_v1beta1_IngressList, - DeepCopy_v1beta1_IngressRule, - DeepCopy_v1beta1_IngressRuleValue, - DeepCopy_v1beta1_IngressSpec, - DeepCopy_v1beta1_IngressStatus, - DeepCopy_v1beta1_IngressTLS, - DeepCopy_v1beta1_Job, - DeepCopy_v1beta1_JobCondition, - DeepCopy_v1beta1_JobList, - DeepCopy_v1beta1_JobSpec, - DeepCopy_v1beta1_JobStatus, - DeepCopy_v1beta1_LabelSelector, - DeepCopy_v1beta1_LabelSelectorRequirement, - DeepCopy_v1beta1_ListOptions, - DeepCopy_v1beta1_NetworkPolicy, - DeepCopy_v1beta1_NetworkPolicyIngressRule, - DeepCopy_v1beta1_NetworkPolicyList, - DeepCopy_v1beta1_NetworkPolicyPeer, - DeepCopy_v1beta1_NetworkPolicyPort, - DeepCopy_v1beta1_NetworkPolicySpec, - DeepCopy_v1beta1_PodSecurityPolicy, - DeepCopy_v1beta1_PodSecurityPolicyList, - DeepCopy_v1beta1_PodSecurityPolicySpec, - DeepCopy_v1beta1_ReplicaSet, - DeepCopy_v1beta1_ReplicaSetList, - DeepCopy_v1beta1_ReplicaSetSpec, - DeepCopy_v1beta1_ReplicaSetStatus, - DeepCopy_v1beta1_ReplicationControllerDummy, - DeepCopy_v1beta1_RollbackConfig, - DeepCopy_v1beta1_RollingUpdateDeployment, - DeepCopy_v1beta1_RunAsUserStrategyOptions, - DeepCopy_v1beta1_SELinuxStrategyOptions, - DeepCopy_v1beta1_Scale, - DeepCopy_v1beta1_ScaleSpec, - DeepCopy_v1beta1_ScaleStatus, - DeepCopy_v1beta1_SubresourceReference, - DeepCopy_v1beta1_SupplementalGroupsStrategyOptions, - DeepCopy_v1beta1_ThirdPartyResource, - DeepCopy_v1beta1_ThirdPartyResourceData, - DeepCopy_v1beta1_ThirdPartyResourceDataList, - DeepCopy_v1beta1_ThirdPartyResourceList, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1beta1_APIVersion(in APIVersion, out *APIVersion, c *conversion.Cloner) error { - out.Name = in.Name - return nil -} - -func DeepCopy_v1beta1_CPUTargetUtilization(in CPUTargetUtilization, out *CPUTargetUtilization, c *conversion.Cloner) error { - out.TargetPercentage = in.TargetPercentage - return nil -} - -func DeepCopy_v1beta1_CustomMetricCurrentStatus(in CustomMetricCurrentStatus, out *CustomMetricCurrentStatus, c *conversion.Cloner) error { - out.Name = in.Name - if err := resource.DeepCopy_resource_Quantity(in.CurrentValue, &out.CurrentValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_CustomMetricCurrentStatusList(in CustomMetricCurrentStatusList, out *CustomMetricCurrentStatusList, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]CustomMetricCurrentStatus, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_CustomMetricCurrentStatus(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_CustomMetricTarget(in CustomMetricTarget, out *CustomMetricTarget, c *conversion.Cloner) error { - out.Name = in.Name - if err := resource.DeepCopy_resource_Quantity(in.TargetValue, &out.TargetValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_CustomMetricTargetList(in CustomMetricTargetList, out *CustomMetricTargetList, c *conversion.Cloner) error { - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]CustomMetricTarget, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_CustomMetricTarget(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_DaemonSet(in DaemonSet, out *DaemonSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_DaemonSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_DaemonSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_DaemonSetList(in DaemonSetList, out *DaemonSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]DaemonSet, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_DaemonSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_DaemonSetSpec(in DaemonSetSpec, out *DaemonSetSpec, c *conversion.Cloner) error { - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_DaemonSetStatus(in DaemonSetStatus, out *DaemonSetStatus, c *conversion.Cloner) error { - out.CurrentNumberScheduled = in.CurrentNumberScheduled - out.NumberMisscheduled = in.NumberMisscheduled - out.DesiredNumberScheduled = in.DesiredNumberScheduled - return nil -} - -func DeepCopy_v1beta1_Deployment(in Deployment, out *Deployment, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_DeploymentSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_DeploymentStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_DeploymentList(in DeploymentList, out *DeploymentList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Deployment, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_Deployment(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_DeploymentRollback(in DeploymentRollback, out *DeploymentRollback, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Name = in.Name - if in.UpdatedAnnotations != nil { - in, out := in.UpdatedAnnotations, &out.UpdatedAnnotations - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.UpdatedAnnotations = nil - } - if err := DeepCopy_v1beta1_RollbackConfig(in.RollbackTo, &out.RollbackTo, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_DeploymentSpec(in DeploymentSpec, out *DeploymentSpec, c *conversion.Cloner) error { - if in.Replicas != nil { - in, out := in.Replicas, &out.Replicas - *out = new(int32) - **out = *in - } else { - out.Replicas = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_DeploymentStrategy(in.Strategy, &out.Strategy, c); err != nil { - return err - } - out.MinReadySeconds = in.MinReadySeconds - if in.RevisionHistoryLimit != nil { - in, out := in.RevisionHistoryLimit, &out.RevisionHistoryLimit - *out = new(int32) - **out = *in - } else { - out.RevisionHistoryLimit = nil - } - out.Paused = in.Paused - if in.RollbackTo != nil { - in, out := in.RollbackTo, &out.RollbackTo - *out = new(RollbackConfig) - if err := DeepCopy_v1beta1_RollbackConfig(*in, *out, c); err != nil { - return err - } - } else { - out.RollbackTo = nil - } - return nil -} - -func DeepCopy_v1beta1_DeploymentStatus(in DeploymentStatus, out *DeploymentStatus, c *conversion.Cloner) error { - out.ObservedGeneration = in.ObservedGeneration - out.Replicas = in.Replicas - out.UpdatedReplicas = in.UpdatedReplicas - out.AvailableReplicas = in.AvailableReplicas - out.UnavailableReplicas = in.UnavailableReplicas - return nil -} - -func DeepCopy_v1beta1_DeploymentStrategy(in DeploymentStrategy, out *DeploymentStrategy, c *conversion.Cloner) error { - out.Type = in.Type - if in.RollingUpdate != nil { - in, out := in.RollingUpdate, &out.RollingUpdate - *out = new(RollingUpdateDeployment) - if err := DeepCopy_v1beta1_RollingUpdateDeployment(*in, *out, c); err != nil { - return err - } - } else { - out.RollingUpdate = nil - } - return nil -} - -func DeepCopy_v1beta1_ExportOptions(in ExportOptions, out *ExportOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.Export = in.Export - out.Exact = in.Exact - return nil -} - -func DeepCopy_v1beta1_FSGroupStrategyOptions(in FSGroupStrategyOptions, out *FSGroupStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_v1beta1_HTTPIngressPath(in HTTPIngressPath, out *HTTPIngressPath, c *conversion.Cloner) error { - out.Path = in.Path - if err := DeepCopy_v1beta1_IngressBackend(in.Backend, &out.Backend, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_HTTPIngressRuleValue(in HTTPIngressRuleValue, out *HTTPIngressRuleValue, c *conversion.Cloner) error { - if in.Paths != nil { - in, out := in.Paths, &out.Paths - *out = make([]HTTPIngressPath, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_HTTPIngressPath(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Paths = nil - } - return nil -} - -func DeepCopy_v1beta1_HorizontalPodAutoscaler(in HorizontalPodAutoscaler, out *HorizontalPodAutoscaler, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_HorizontalPodAutoscalerList(in HorizontalPodAutoscalerList, out *HorizontalPodAutoscalerList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]HorizontalPodAutoscaler, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_HorizontalPodAutoscaler(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(in HorizontalPodAutoscalerSpec, out *HorizontalPodAutoscalerSpec, c *conversion.Cloner) error { - if err := DeepCopy_v1beta1_SubresourceReference(in.ScaleRef, &out.ScaleRef, c); err != nil { - return err - } - if in.MinReplicas != nil { - in, out := in.MinReplicas, &out.MinReplicas - *out = new(int32) - **out = *in - } else { - out.MinReplicas = nil - } - out.MaxReplicas = in.MaxReplicas - if in.CPUUtilization != nil { - in, out := in.CPUUtilization, &out.CPUUtilization - *out = new(CPUTargetUtilization) - if err := DeepCopy_v1beta1_CPUTargetUtilization(*in, *out, c); err != nil { - return err - } - } else { - out.CPUUtilization = nil - } - return nil -} - -func DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(in HorizontalPodAutoscalerStatus, out *HorizontalPodAutoscalerStatus, c *conversion.Cloner) error { - if in.ObservedGeneration != nil { - in, out := in.ObservedGeneration, &out.ObservedGeneration - *out = new(int64) - **out = *in - } else { - out.ObservedGeneration = nil - } - if in.LastScaleTime != nil { - in, out := in.LastScaleTime, &out.LastScaleTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.LastScaleTime = nil - } - out.CurrentReplicas = in.CurrentReplicas - out.DesiredReplicas = in.DesiredReplicas - if in.CurrentCPUUtilizationPercentage != nil { - in, out := in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage - *out = new(int32) - **out = *in - } else { - out.CurrentCPUUtilizationPercentage = nil - } - return nil -} - -func DeepCopy_v1beta1_HostPortRange(in HostPortRange, out *HostPortRange, c *conversion.Cloner) error { - out.Min = in.Min - out.Max = in.Max - return nil -} - -func DeepCopy_v1beta1_IDRange(in IDRange, out *IDRange, c *conversion.Cloner) error { - out.Min = in.Min - out.Max = in.Max - return nil -} - -func DeepCopy_v1beta1_Ingress(in Ingress, out *Ingress, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_IngressSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_IngressStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_IngressBackend(in IngressBackend, out *IngressBackend, c *conversion.Cloner) error { - out.ServiceName = in.ServiceName - if err := intstr.DeepCopy_intstr_IntOrString(in.ServicePort, &out.ServicePort, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_IngressList(in IngressList, out *IngressList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Ingress, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_Ingress(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_IngressRule(in IngressRule, out *IngressRule, c *conversion.Cloner) error { - out.Host = in.Host - if err := DeepCopy_v1beta1_IngressRuleValue(in.IngressRuleValue, &out.IngressRuleValue, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_IngressRuleValue(in IngressRuleValue, out *IngressRuleValue, c *conversion.Cloner) error { - if in.HTTP != nil { - in, out := in.HTTP, &out.HTTP - *out = new(HTTPIngressRuleValue) - if err := DeepCopy_v1beta1_HTTPIngressRuleValue(*in, *out, c); err != nil { - return err - } - } else { - out.HTTP = nil - } - return nil -} - -func DeepCopy_v1beta1_IngressSpec(in IngressSpec, out *IngressSpec, c *conversion.Cloner) error { - if in.Backend != nil { - in, out := in.Backend, &out.Backend - *out = new(IngressBackend) - if err := DeepCopy_v1beta1_IngressBackend(*in, *out, c); err != nil { - return err - } - } else { - out.Backend = nil - } - if in.TLS != nil { - in, out := in.TLS, &out.TLS - *out = make([]IngressTLS, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_IngressTLS(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.TLS = nil - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]IngressRule, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_IngressRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_v1beta1_IngressStatus(in IngressStatus, out *IngressStatus, c *conversion.Cloner) error { - if err := v1.DeepCopy_v1_LoadBalancerStatus(in.LoadBalancer, &out.LoadBalancer, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_IngressTLS(in IngressTLS, out *IngressTLS, c *conversion.Cloner) error { - if in.Hosts != nil { - in, out := in.Hosts, &out.Hosts - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Hosts = nil - } - out.SecretName = in.SecretName - return nil -} - -func DeepCopy_v1beta1_Job(in Job, out *Job, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_JobSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_JobStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_JobCondition(in JobCondition, out *JobCondition, c *conversion.Cloner) error { - out.Type = in.Type - out.Status = in.Status - if err := unversioned.DeepCopy_unversioned_Time(in.LastProbeTime, &out.LastProbeTime, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_Time(in.LastTransitionTime, &out.LastTransitionTime, c); err != nil { - return err - } - out.Reason = in.Reason - out.Message = in.Message - return nil -} - -func DeepCopy_v1beta1_JobList(in JobList, out *JobList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Job, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_Job(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_JobSpec(in JobSpec, out *JobSpec, c *conversion.Cloner) error { - if in.Parallelism != nil { - in, out := in.Parallelism, &out.Parallelism - *out = new(int32) - **out = *in - } else { - out.Parallelism = nil - } - if in.Completions != nil { - in, out := in.Completions, &out.Completions - *out = new(int32) - **out = *in - } else { - out.Completions = nil - } - if in.ActiveDeadlineSeconds != nil { - in, out := in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = *in - } else { - out.ActiveDeadlineSeconds = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if in.AutoSelector != nil { - in, out := in.AutoSelector, &out.AutoSelector - *out = new(bool) - **out = *in - } else { - out.AutoSelector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_JobStatus(in JobStatus, out *JobStatus, c *conversion.Cloner) error { - if in.Conditions != nil { - in, out := in.Conditions, &out.Conditions - *out = make([]JobCondition, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_JobCondition(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Conditions = nil - } - if in.StartTime != nil { - in, out := in.StartTime, &out.StartTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.StartTime = nil - } - if in.CompletionTime != nil { - in, out := in.CompletionTime, &out.CompletionTime - *out = new(unversioned.Time) - if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil { - return err - } - } else { - out.CompletionTime = nil - } - out.Active = in.Active - out.Succeeded = in.Succeeded - out.Failed = in.Failed - return nil -} - -func DeepCopy_v1beta1_LabelSelector(in LabelSelector, out *LabelSelector, c *conversion.Cloner) error { - if in.MatchLabels != nil { - in, out := in.MatchLabels, &out.MatchLabels - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.MatchLabels = nil - } - if in.MatchExpressions != nil { - in, out := in.MatchExpressions, &out.MatchExpressions - *out = make([]LabelSelectorRequirement, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_LabelSelectorRequirement(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.MatchExpressions = nil - } - return nil -} - -func DeepCopy_v1beta1_LabelSelectorRequirement(in LabelSelectorRequirement, out *LabelSelectorRequirement, c *conversion.Cloner) error { - out.Key = in.Key - out.Operator = in.Operator - if in.Values != nil { - in, out := in.Values, &out.Values - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Values = nil - } - return nil -} - -func DeepCopy_v1beta1_ListOptions(in ListOptions, out *ListOptions, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - out.LabelSelector = in.LabelSelector - out.FieldSelector = in.FieldSelector - out.Watch = in.Watch - out.ResourceVersion = in.ResourceVersion - if in.TimeoutSeconds != nil { - in, out := in.TimeoutSeconds, &out.TimeoutSeconds - *out = new(int64) - **out = *in - } else { - out.TimeoutSeconds = nil - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicy(in NetworkPolicy, out *NetworkPolicy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_NetworkPolicySpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicyIngressRule(in NetworkPolicyIngressRule, out *NetworkPolicyIngressRule, c *conversion.Cloner) error { - if in.Ports != nil { - in, out := in.Ports, &out.Ports - *out = make([]NetworkPolicyPort, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_NetworkPolicyPort(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ports = nil - } - if in.From != nil { - in, out := in.From, &out.From - *out = make([]NetworkPolicyPeer, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_NetworkPolicyPeer(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.From = nil - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicyList(in NetworkPolicyList, out *NetworkPolicyList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]NetworkPolicy, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_NetworkPolicy(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicyPeer(in NetworkPolicyPeer, out *NetworkPolicyPeer, c *conversion.Cloner) error { - if in.PodSelector != nil { - in, out := in.PodSelector, &out.PodSelector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.PodSelector = nil - } - if in.NamespaceSelector != nil { - in, out := in.NamespaceSelector, &out.NamespaceSelector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.NamespaceSelector = nil - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicyPort(in NetworkPolicyPort, out *NetworkPolicyPort, c *conversion.Cloner) error { - if in.Protocol != nil { - in, out := in.Protocol, &out.Protocol - *out = new(v1.Protocol) - **out = *in - } else { - out.Protocol = nil - } - if in.Port != nil { - in, out := in.Port, &out.Port - *out = new(intstr.IntOrString) - if err := intstr.DeepCopy_intstr_IntOrString(*in, *out, c); err != nil { - return err - } - } else { - out.Port = nil - } - return nil -} - -func DeepCopy_v1beta1_NetworkPolicySpec(in NetworkPolicySpec, out *NetworkPolicySpec, c *conversion.Cloner) error { - if err := DeepCopy_v1beta1_LabelSelector(in.PodSelector, &out.PodSelector, c); err != nil { - return err - } - if in.Ingress != nil { - in, out := in.Ingress, &out.Ingress - *out = make([]NetworkPolicyIngressRule, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_NetworkPolicyIngressRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ingress = nil - } - return nil -} - -func DeepCopy_v1beta1_PodSecurityPolicy(in PodSecurityPolicy, out *PodSecurityPolicy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_PodSecurityPolicySpec(in.Spec, &out.Spec, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_PodSecurityPolicyList(in PodSecurityPolicyList, out *PodSecurityPolicyList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodSecurityPolicy, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_PodSecurityPolicy(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_PodSecurityPolicySpec(in PodSecurityPolicySpec, out *PodSecurityPolicySpec, c *conversion.Cloner) error { - out.Privileged = in.Privileged - if in.DefaultAddCapabilities != nil { - in, out := in.DefaultAddCapabilities, &out.DefaultAddCapabilities - *out = make([]v1.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.DefaultAddCapabilities = nil - } - if in.RequiredDropCapabilities != nil { - in, out := in.RequiredDropCapabilities, &out.RequiredDropCapabilities - *out = make([]v1.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.RequiredDropCapabilities = nil - } - if in.AllowedCapabilities != nil { - in, out := in.AllowedCapabilities, &out.AllowedCapabilities - *out = make([]v1.Capability, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.AllowedCapabilities = nil - } - if in.Volumes != nil { - in, out := in.Volumes, &out.Volumes - *out = make([]FSType, len(in)) - for i := range in { - (*out)[i] = in[i] - } - } else { - out.Volumes = nil - } - out.HostNetwork = in.HostNetwork - if in.HostPorts != nil { - in, out := in.HostPorts, &out.HostPorts - *out = make([]HostPortRange, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_HostPortRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.HostPorts = nil - } - out.HostPID = in.HostPID - out.HostIPC = in.HostIPC - if err := DeepCopy_v1beta1_SELinuxStrategyOptions(in.SELinux, &out.SELinux, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_RunAsUserStrategyOptions(in.RunAsUser, &out.RunAsUser, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(in.SupplementalGroups, &out.SupplementalGroups, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_FSGroupStrategyOptions(in.FSGroup, &out.FSGroup, c); err != nil { - return err - } - out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem - return nil -} - -func DeepCopy_v1beta1_ReplicaSet(in ReplicaSet, out *ReplicaSet, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_ReplicaSetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_ReplicaSetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_ReplicaSetList(in ReplicaSetList, out *ReplicaSetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ReplicaSet, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_ReplicaSet(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_ReplicaSetSpec(in ReplicaSetSpec, out *ReplicaSetSpec, c *conversion.Cloner) error { - if in.Replicas != nil { - in, out := in.Replicas, &out.Replicas - *out = new(int32) - **out = *in - } else { - out.Replicas = nil - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(LabelSelector) - if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - if err := v1.DeepCopy_v1_PodTemplateSpec(in.Template, &out.Template, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_ReplicaSetStatus(in ReplicaSetStatus, out *ReplicaSetStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - out.FullyLabeledReplicas = in.FullyLabeledReplicas - out.ObservedGeneration = in.ObservedGeneration - return nil -} - -func DeepCopy_v1beta1_ReplicationControllerDummy(in ReplicationControllerDummy, out *ReplicationControllerDummy, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_RollbackConfig(in RollbackConfig, out *RollbackConfig, c *conversion.Cloner) error { - out.Revision = in.Revision - return nil -} - -func DeepCopy_v1beta1_RollingUpdateDeployment(in RollingUpdateDeployment, out *RollingUpdateDeployment, c *conversion.Cloner) error { - if in.MaxUnavailable != nil { - in, out := in.MaxUnavailable, &out.MaxUnavailable - *out = new(intstr.IntOrString) - if err := intstr.DeepCopy_intstr_IntOrString(*in, *out, c); err != nil { - return err - } - } else { - out.MaxUnavailable = nil - } - if in.MaxSurge != nil { - in, out := in.MaxSurge, &out.MaxSurge - *out = new(intstr.IntOrString) - if err := intstr.DeepCopy_intstr_IntOrString(*in, *out, c); err != nil { - return err - } - } else { - out.MaxSurge = nil - } - return nil -} - -func DeepCopy_v1beta1_RunAsUserStrategyOptions(in RunAsUserStrategyOptions, out *RunAsUserStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_v1beta1_SELinuxStrategyOptions(in SELinuxStrategyOptions, out *SELinuxStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.SELinuxOptions != nil { - in, out := in.SELinuxOptions, &out.SELinuxOptions - *out = new(v1.SELinuxOptions) - if err := v1.DeepCopy_v1_SELinuxOptions(*in, *out, c); err != nil { - return err - } - } else { - out.SELinuxOptions = nil - } - return nil -} - -func DeepCopy_v1beta1_Scale(in Scale, out *Scale, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_ScaleSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1beta1_ScaleStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1beta1_ScaleSpec(in ScaleSpec, out *ScaleSpec, c *conversion.Cloner) error { - out.Replicas = in.Replicas - return nil -} - -func DeepCopy_v1beta1_ScaleStatus(in ScaleStatus, out *ScaleStatus, c *conversion.Cloner) error { - out.Replicas = in.Replicas - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = make(map[string]string) - for key, val := range in { - (*out)[key] = val - } - } else { - out.Selector = nil - } - out.TargetSelector = in.TargetSelector - return nil -} - -func DeepCopy_v1beta1_SubresourceReference(in SubresourceReference, out *SubresourceReference, c *conversion.Cloner) error { - out.Kind = in.Kind - out.Name = in.Name - out.APIVersion = in.APIVersion - out.Subresource = in.Subresource - return nil -} - -func DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(in SupplementalGroupsStrategyOptions, out *SupplementalGroupsStrategyOptions, c *conversion.Cloner) error { - out.Rule = in.Rule - if in.Ranges != nil { - in, out := in.Ranges, &out.Ranges - *out = make([]IDRange, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_IDRange(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Ranges = nil - } - return nil -} - -func DeepCopy_v1beta1_ThirdPartyResource(in ThirdPartyResource, out *ThirdPartyResource, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - out.Description = in.Description - if in.Versions != nil { - in, out := in.Versions, &out.Versions - *out = make([]APIVersion, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_APIVersion(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Versions = nil - } - return nil -} - -func DeepCopy_v1beta1_ThirdPartyResourceData(in ThirdPartyResourceData, out *ThirdPartyResourceData, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Data != nil { - in, out := in.Data, &out.Data - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Data = nil - } - return nil -} - -func DeepCopy_v1beta1_ThirdPartyResourceDataList(in ThirdPartyResourceDataList, out *ThirdPartyResourceDataList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ThirdPartyResourceData, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_ThirdPartyResourceData(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1beta1_ThirdPartyResourceList(in ThirdPartyResourceList, out *ThirdPartyResourceList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ThirdPartyResource, len(in)) - for i := range in { - if err := DeepCopy_v1beta1_ThirdPartyResource(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go index 71e55a467a96..ab6a202c370b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/doc.go index cfdb87c53d84..dc8790024d9c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/extensions +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/autoscaling +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/batch + package v1beta1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.pb.go index 3120ce17ff31..fd5dbc645cde 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -88,6 +88,8 @@ limitations under the License. Scale ScaleSpec ScaleStatus + StorageClass + StorageClassList SubresourceReference SupplementalGroupsStrategyOptions ThirdPartyResource @@ -106,6 +108,10 @@ import k8s_io_kubernetes_pkg_api_v1 "k8s.io/kubernetes/pkg/api/v1" import k8s_io_kubernetes_pkg_util_intstr "k8s.io/kubernetes/pkg/util/intstr" +import strings "strings" +import reflect "reflect" +import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -113,281 +119,218 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *APIVersion) Reset() { *m = APIVersion{} } -func (m *APIVersion) String() string { return proto.CompactTextString(m) } -func (*APIVersion) ProtoMessage() {} +func (m *APIVersion) Reset() { *m = APIVersion{} } +func (*APIVersion) ProtoMessage() {} + +func (m *CPUTargetUtilization) Reset() { *m = CPUTargetUtilization{} } +func (*CPUTargetUtilization) ProtoMessage() {} -func (m *CPUTargetUtilization) Reset() { *m = CPUTargetUtilization{} } -func (m *CPUTargetUtilization) String() string { return proto.CompactTextString(m) } -func (*CPUTargetUtilization) ProtoMessage() {} +func (m *CustomMetricCurrentStatus) Reset() { *m = CustomMetricCurrentStatus{} } +func (*CustomMetricCurrentStatus) ProtoMessage() {} -func (m *CustomMetricCurrentStatus) Reset() { *m = CustomMetricCurrentStatus{} } -func (m *CustomMetricCurrentStatus) String() string { return proto.CompactTextString(m) } -func (*CustomMetricCurrentStatus) ProtoMessage() {} +func (m *CustomMetricCurrentStatusList) Reset() { *m = CustomMetricCurrentStatusList{} } +func (*CustomMetricCurrentStatusList) ProtoMessage() {} -func (m *CustomMetricCurrentStatusList) Reset() { *m = CustomMetricCurrentStatusList{} } -func (m *CustomMetricCurrentStatusList) String() string { return proto.CompactTextString(m) } -func (*CustomMetricCurrentStatusList) ProtoMessage() {} +func (m *CustomMetricTarget) Reset() { *m = CustomMetricTarget{} } +func (*CustomMetricTarget) ProtoMessage() {} -func (m *CustomMetricTarget) Reset() { *m = CustomMetricTarget{} } -func (m *CustomMetricTarget) String() string { return proto.CompactTextString(m) } -func (*CustomMetricTarget) ProtoMessage() {} +func (m *CustomMetricTargetList) Reset() { *m = CustomMetricTargetList{} } +func (*CustomMetricTargetList) ProtoMessage() {} -func (m *CustomMetricTargetList) Reset() { *m = CustomMetricTargetList{} } -func (m *CustomMetricTargetList) String() string { return proto.CompactTextString(m) } -func (*CustomMetricTargetList) ProtoMessage() {} +func (m *DaemonSet) Reset() { *m = DaemonSet{} } +func (*DaemonSet) ProtoMessage() {} -func (m *DaemonSet) Reset() { *m = DaemonSet{} } -func (m *DaemonSet) String() string { return proto.CompactTextString(m) } -func (*DaemonSet) ProtoMessage() {} +func (m *DaemonSetList) Reset() { *m = DaemonSetList{} } +func (*DaemonSetList) ProtoMessage() {} -func (m *DaemonSetList) Reset() { *m = DaemonSetList{} } -func (m *DaemonSetList) String() string { return proto.CompactTextString(m) } -func (*DaemonSetList) ProtoMessage() {} +func (m *DaemonSetSpec) Reset() { *m = DaemonSetSpec{} } +func (*DaemonSetSpec) ProtoMessage() {} -func (m *DaemonSetSpec) Reset() { *m = DaemonSetSpec{} } -func (m *DaemonSetSpec) String() string { return proto.CompactTextString(m) } -func (*DaemonSetSpec) ProtoMessage() {} +func (m *DaemonSetStatus) Reset() { *m = DaemonSetStatus{} } +func (*DaemonSetStatus) ProtoMessage() {} -func (m *DaemonSetStatus) Reset() { *m = DaemonSetStatus{} } -func (m *DaemonSetStatus) String() string { return proto.CompactTextString(m) } -func (*DaemonSetStatus) ProtoMessage() {} +func (m *Deployment) Reset() { *m = Deployment{} } +func (*Deployment) ProtoMessage() {} -func (m *Deployment) Reset() { *m = Deployment{} } -func (m *Deployment) String() string { return proto.CompactTextString(m) } -func (*Deployment) ProtoMessage() {} +func (m *DeploymentList) Reset() { *m = DeploymentList{} } +func (*DeploymentList) ProtoMessage() {} -func (m *DeploymentList) Reset() { *m = DeploymentList{} } -func (m *DeploymentList) String() string { return proto.CompactTextString(m) } -func (*DeploymentList) ProtoMessage() {} +func (m *DeploymentRollback) Reset() { *m = DeploymentRollback{} } +func (*DeploymentRollback) ProtoMessage() {} -func (m *DeploymentRollback) Reset() { *m = DeploymentRollback{} } -func (m *DeploymentRollback) String() string { return proto.CompactTextString(m) } -func (*DeploymentRollback) ProtoMessage() {} +func (m *DeploymentSpec) Reset() { *m = DeploymentSpec{} } +func (*DeploymentSpec) ProtoMessage() {} -func (m *DeploymentSpec) Reset() { *m = DeploymentSpec{} } -func (m *DeploymentSpec) String() string { return proto.CompactTextString(m) } -func (*DeploymentSpec) ProtoMessage() {} +func (m *DeploymentStatus) Reset() { *m = DeploymentStatus{} } +func (*DeploymentStatus) ProtoMessage() {} -func (m *DeploymentStatus) Reset() { *m = DeploymentStatus{} } -func (m *DeploymentStatus) String() string { return proto.CompactTextString(m) } -func (*DeploymentStatus) ProtoMessage() {} +func (m *DeploymentStrategy) Reset() { *m = DeploymentStrategy{} } +func (*DeploymentStrategy) ProtoMessage() {} -func (m *DeploymentStrategy) Reset() { *m = DeploymentStrategy{} } -func (m *DeploymentStrategy) String() string { return proto.CompactTextString(m) } -func (*DeploymentStrategy) ProtoMessage() {} +func (m *ExportOptions) Reset() { *m = ExportOptions{} } +func (*ExportOptions) ProtoMessage() {} -func (m *ExportOptions) Reset() { *m = ExportOptions{} } -func (m *ExportOptions) String() string { return proto.CompactTextString(m) } -func (*ExportOptions) ProtoMessage() {} +func (m *FSGroupStrategyOptions) Reset() { *m = FSGroupStrategyOptions{} } +func (*FSGroupStrategyOptions) ProtoMessage() {} -func (m *FSGroupStrategyOptions) Reset() { *m = FSGroupStrategyOptions{} } -func (m *FSGroupStrategyOptions) String() string { return proto.CompactTextString(m) } -func (*FSGroupStrategyOptions) ProtoMessage() {} +func (m *HTTPIngressPath) Reset() { *m = HTTPIngressPath{} } +func (*HTTPIngressPath) ProtoMessage() {} -func (m *HTTPIngressPath) Reset() { *m = HTTPIngressPath{} } -func (m *HTTPIngressPath) String() string { return proto.CompactTextString(m) } -func (*HTTPIngressPath) ProtoMessage() {} +func (m *HTTPIngressRuleValue) Reset() { *m = HTTPIngressRuleValue{} } +func (*HTTPIngressRuleValue) ProtoMessage() {} -func (m *HTTPIngressRuleValue) Reset() { *m = HTTPIngressRuleValue{} } -func (m *HTTPIngressRuleValue) String() string { return proto.CompactTextString(m) } -func (*HTTPIngressRuleValue) ProtoMessage() {} +func (m *HorizontalPodAutoscaler) Reset() { *m = HorizontalPodAutoscaler{} } +func (*HorizontalPodAutoscaler) ProtoMessage() {} -func (m *HorizontalPodAutoscaler) Reset() { *m = HorizontalPodAutoscaler{} } -func (m *HorizontalPodAutoscaler) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscaler) ProtoMessage() {} +func (m *HorizontalPodAutoscalerList) Reset() { *m = HorizontalPodAutoscalerList{} } +func (*HorizontalPodAutoscalerList) ProtoMessage() {} -func (m *HorizontalPodAutoscalerList) Reset() { *m = HorizontalPodAutoscalerList{} } -func (m *HorizontalPodAutoscalerList) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerList) ProtoMessage() {} +func (m *HorizontalPodAutoscalerSpec) Reset() { *m = HorizontalPodAutoscalerSpec{} } +func (*HorizontalPodAutoscalerSpec) ProtoMessage() {} -func (m *HorizontalPodAutoscalerSpec) Reset() { *m = HorizontalPodAutoscalerSpec{} } -func (m *HorizontalPodAutoscalerSpec) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerSpec) ProtoMessage() {} +func (m *HorizontalPodAutoscalerStatus) Reset() { *m = HorizontalPodAutoscalerStatus{} } +func (*HorizontalPodAutoscalerStatus) ProtoMessage() {} -func (m *HorizontalPodAutoscalerStatus) Reset() { *m = HorizontalPodAutoscalerStatus{} } -func (m *HorizontalPodAutoscalerStatus) String() string { return proto.CompactTextString(m) } -func (*HorizontalPodAutoscalerStatus) ProtoMessage() {} +func (m *HostPortRange) Reset() { *m = HostPortRange{} } +func (*HostPortRange) ProtoMessage() {} -func (m *HostPortRange) Reset() { *m = HostPortRange{} } -func (m *HostPortRange) String() string { return proto.CompactTextString(m) } -func (*HostPortRange) ProtoMessage() {} +func (m *IDRange) Reset() { *m = IDRange{} } +func (*IDRange) ProtoMessage() {} -func (m *IDRange) Reset() { *m = IDRange{} } -func (m *IDRange) String() string { return proto.CompactTextString(m) } -func (*IDRange) ProtoMessage() {} +func (m *Ingress) Reset() { *m = Ingress{} } +func (*Ingress) ProtoMessage() {} -func (m *Ingress) Reset() { *m = Ingress{} } -func (m *Ingress) String() string { return proto.CompactTextString(m) } -func (*Ingress) ProtoMessage() {} +func (m *IngressBackend) Reset() { *m = IngressBackend{} } +func (*IngressBackend) ProtoMessage() {} -func (m *IngressBackend) Reset() { *m = IngressBackend{} } -func (m *IngressBackend) String() string { return proto.CompactTextString(m) } -func (*IngressBackend) ProtoMessage() {} +func (m *IngressList) Reset() { *m = IngressList{} } +func (*IngressList) ProtoMessage() {} -func (m *IngressList) Reset() { *m = IngressList{} } -func (m *IngressList) String() string { return proto.CompactTextString(m) } -func (*IngressList) ProtoMessage() {} +func (m *IngressRule) Reset() { *m = IngressRule{} } +func (*IngressRule) ProtoMessage() {} -func (m *IngressRule) Reset() { *m = IngressRule{} } -func (m *IngressRule) String() string { return proto.CompactTextString(m) } -func (*IngressRule) ProtoMessage() {} +func (m *IngressRuleValue) Reset() { *m = IngressRuleValue{} } +func (*IngressRuleValue) ProtoMessage() {} -func (m *IngressRuleValue) Reset() { *m = IngressRuleValue{} } -func (m *IngressRuleValue) String() string { return proto.CompactTextString(m) } -func (*IngressRuleValue) ProtoMessage() {} +func (m *IngressSpec) Reset() { *m = IngressSpec{} } +func (*IngressSpec) ProtoMessage() {} -func (m *IngressSpec) Reset() { *m = IngressSpec{} } -func (m *IngressSpec) String() string { return proto.CompactTextString(m) } -func (*IngressSpec) ProtoMessage() {} +func (m *IngressStatus) Reset() { *m = IngressStatus{} } +func (*IngressStatus) ProtoMessage() {} -func (m *IngressStatus) Reset() { *m = IngressStatus{} } -func (m *IngressStatus) String() string { return proto.CompactTextString(m) } -func (*IngressStatus) ProtoMessage() {} +func (m *IngressTLS) Reset() { *m = IngressTLS{} } +func (*IngressTLS) ProtoMessage() {} -func (m *IngressTLS) Reset() { *m = IngressTLS{} } -func (m *IngressTLS) String() string { return proto.CompactTextString(m) } -func (*IngressTLS) ProtoMessage() {} +func (m *Job) Reset() { *m = Job{} } +func (*Job) ProtoMessage() {} -func (m *Job) Reset() { *m = Job{} } -func (m *Job) String() string { return proto.CompactTextString(m) } -func (*Job) ProtoMessage() {} +func (m *JobCondition) Reset() { *m = JobCondition{} } +func (*JobCondition) ProtoMessage() {} -func (m *JobCondition) Reset() { *m = JobCondition{} } -func (m *JobCondition) String() string { return proto.CompactTextString(m) } -func (*JobCondition) ProtoMessage() {} +func (m *JobList) Reset() { *m = JobList{} } +func (*JobList) ProtoMessage() {} -func (m *JobList) Reset() { *m = JobList{} } -func (m *JobList) String() string { return proto.CompactTextString(m) } -func (*JobList) ProtoMessage() {} +func (m *JobSpec) Reset() { *m = JobSpec{} } +func (*JobSpec) ProtoMessage() {} -func (m *JobSpec) Reset() { *m = JobSpec{} } -func (m *JobSpec) String() string { return proto.CompactTextString(m) } -func (*JobSpec) ProtoMessage() {} +func (m *JobStatus) Reset() { *m = JobStatus{} } +func (*JobStatus) ProtoMessage() {} -func (m *JobStatus) Reset() { *m = JobStatus{} } -func (m *JobStatus) String() string { return proto.CompactTextString(m) } -func (*JobStatus) ProtoMessage() {} +func (m *LabelSelector) Reset() { *m = LabelSelector{} } +func (*LabelSelector) ProtoMessage() {} -func (m *LabelSelector) Reset() { *m = LabelSelector{} } -func (m *LabelSelector) String() string { return proto.CompactTextString(m) } -func (*LabelSelector) ProtoMessage() {} +func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } +func (*LabelSelectorRequirement) ProtoMessage() {} -func (m *LabelSelectorRequirement) Reset() { *m = LabelSelectorRequirement{} } -func (m *LabelSelectorRequirement) String() string { return proto.CompactTextString(m) } -func (*LabelSelectorRequirement) ProtoMessage() {} +func (m *ListOptions) Reset() { *m = ListOptions{} } +func (*ListOptions) ProtoMessage() {} -func (m *ListOptions) Reset() { *m = ListOptions{} } -func (m *ListOptions) String() string { return proto.CompactTextString(m) } -func (*ListOptions) ProtoMessage() {} +func (m *NetworkPolicy) Reset() { *m = NetworkPolicy{} } +func (*NetworkPolicy) ProtoMessage() {} -func (m *NetworkPolicy) Reset() { *m = NetworkPolicy{} } -func (m *NetworkPolicy) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicy) ProtoMessage() {} +func (m *NetworkPolicyIngressRule) Reset() { *m = NetworkPolicyIngressRule{} } +func (*NetworkPolicyIngressRule) ProtoMessage() {} -func (m *NetworkPolicyIngressRule) Reset() { *m = NetworkPolicyIngressRule{} } -func (m *NetworkPolicyIngressRule) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicyIngressRule) ProtoMessage() {} +func (m *NetworkPolicyList) Reset() { *m = NetworkPolicyList{} } +func (*NetworkPolicyList) ProtoMessage() {} -func (m *NetworkPolicyList) Reset() { *m = NetworkPolicyList{} } -func (m *NetworkPolicyList) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicyList) ProtoMessage() {} +func (m *NetworkPolicyPeer) Reset() { *m = NetworkPolicyPeer{} } +func (*NetworkPolicyPeer) ProtoMessage() {} -func (m *NetworkPolicyPeer) Reset() { *m = NetworkPolicyPeer{} } -func (m *NetworkPolicyPeer) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicyPeer) ProtoMessage() {} +func (m *NetworkPolicyPort) Reset() { *m = NetworkPolicyPort{} } +func (*NetworkPolicyPort) ProtoMessage() {} -func (m *NetworkPolicyPort) Reset() { *m = NetworkPolicyPort{} } -func (m *NetworkPolicyPort) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicyPort) ProtoMessage() {} +func (m *NetworkPolicySpec) Reset() { *m = NetworkPolicySpec{} } +func (*NetworkPolicySpec) ProtoMessage() {} -func (m *NetworkPolicySpec) Reset() { *m = NetworkPolicySpec{} } -func (m *NetworkPolicySpec) String() string { return proto.CompactTextString(m) } -func (*NetworkPolicySpec) ProtoMessage() {} +func (m *PodSecurityPolicy) Reset() { *m = PodSecurityPolicy{} } +func (*PodSecurityPolicy) ProtoMessage() {} -func (m *PodSecurityPolicy) Reset() { *m = PodSecurityPolicy{} } -func (m *PodSecurityPolicy) String() string { return proto.CompactTextString(m) } -func (*PodSecurityPolicy) ProtoMessage() {} +func (m *PodSecurityPolicyList) Reset() { *m = PodSecurityPolicyList{} } +func (*PodSecurityPolicyList) ProtoMessage() {} -func (m *PodSecurityPolicyList) Reset() { *m = PodSecurityPolicyList{} } -func (m *PodSecurityPolicyList) String() string { return proto.CompactTextString(m) } -func (*PodSecurityPolicyList) ProtoMessage() {} +func (m *PodSecurityPolicySpec) Reset() { *m = PodSecurityPolicySpec{} } +func (*PodSecurityPolicySpec) ProtoMessage() {} -func (m *PodSecurityPolicySpec) Reset() { *m = PodSecurityPolicySpec{} } -func (m *PodSecurityPolicySpec) String() string { return proto.CompactTextString(m) } -func (*PodSecurityPolicySpec) ProtoMessage() {} +func (m *ReplicaSet) Reset() { *m = ReplicaSet{} } +func (*ReplicaSet) ProtoMessage() {} -func (m *ReplicaSet) Reset() { *m = ReplicaSet{} } -func (m *ReplicaSet) String() string { return proto.CompactTextString(m) } -func (*ReplicaSet) ProtoMessage() {} +func (m *ReplicaSetList) Reset() { *m = ReplicaSetList{} } +func (*ReplicaSetList) ProtoMessage() {} -func (m *ReplicaSetList) Reset() { *m = ReplicaSetList{} } -func (m *ReplicaSetList) String() string { return proto.CompactTextString(m) } -func (*ReplicaSetList) ProtoMessage() {} +func (m *ReplicaSetSpec) Reset() { *m = ReplicaSetSpec{} } +func (*ReplicaSetSpec) ProtoMessage() {} -func (m *ReplicaSetSpec) Reset() { *m = ReplicaSetSpec{} } -func (m *ReplicaSetSpec) String() string { return proto.CompactTextString(m) } -func (*ReplicaSetSpec) ProtoMessage() {} +func (m *ReplicaSetStatus) Reset() { *m = ReplicaSetStatus{} } +func (*ReplicaSetStatus) ProtoMessage() {} -func (m *ReplicaSetStatus) Reset() { *m = ReplicaSetStatus{} } -func (m *ReplicaSetStatus) String() string { return proto.CompactTextString(m) } -func (*ReplicaSetStatus) ProtoMessage() {} +func (m *ReplicationControllerDummy) Reset() { *m = ReplicationControllerDummy{} } +func (*ReplicationControllerDummy) ProtoMessage() {} -func (m *ReplicationControllerDummy) Reset() { *m = ReplicationControllerDummy{} } -func (m *ReplicationControllerDummy) String() string { return proto.CompactTextString(m) } -func (*ReplicationControllerDummy) ProtoMessage() {} +func (m *RollbackConfig) Reset() { *m = RollbackConfig{} } +func (*RollbackConfig) ProtoMessage() {} -func (m *RollbackConfig) Reset() { *m = RollbackConfig{} } -func (m *RollbackConfig) String() string { return proto.CompactTextString(m) } -func (*RollbackConfig) ProtoMessage() {} +func (m *RollingUpdateDeployment) Reset() { *m = RollingUpdateDeployment{} } +func (*RollingUpdateDeployment) ProtoMessage() {} -func (m *RollingUpdateDeployment) Reset() { *m = RollingUpdateDeployment{} } -func (m *RollingUpdateDeployment) String() string { return proto.CompactTextString(m) } -func (*RollingUpdateDeployment) ProtoMessage() {} +func (m *RunAsUserStrategyOptions) Reset() { *m = RunAsUserStrategyOptions{} } +func (*RunAsUserStrategyOptions) ProtoMessage() {} -func (m *RunAsUserStrategyOptions) Reset() { *m = RunAsUserStrategyOptions{} } -func (m *RunAsUserStrategyOptions) String() string { return proto.CompactTextString(m) } -func (*RunAsUserStrategyOptions) ProtoMessage() {} +func (m *SELinuxStrategyOptions) Reset() { *m = SELinuxStrategyOptions{} } +func (*SELinuxStrategyOptions) ProtoMessage() {} -func (m *SELinuxStrategyOptions) Reset() { *m = SELinuxStrategyOptions{} } -func (m *SELinuxStrategyOptions) String() string { return proto.CompactTextString(m) } -func (*SELinuxStrategyOptions) ProtoMessage() {} +func (m *Scale) Reset() { *m = Scale{} } +func (*Scale) ProtoMessage() {} -func (m *Scale) Reset() { *m = Scale{} } -func (m *Scale) String() string { return proto.CompactTextString(m) } -func (*Scale) ProtoMessage() {} +func (m *ScaleSpec) Reset() { *m = ScaleSpec{} } +func (*ScaleSpec) ProtoMessage() {} -func (m *ScaleSpec) Reset() { *m = ScaleSpec{} } -func (m *ScaleSpec) String() string { return proto.CompactTextString(m) } -func (*ScaleSpec) ProtoMessage() {} +func (m *ScaleStatus) Reset() { *m = ScaleStatus{} } +func (*ScaleStatus) ProtoMessage() {} -func (m *ScaleStatus) Reset() { *m = ScaleStatus{} } -func (m *ScaleStatus) String() string { return proto.CompactTextString(m) } -func (*ScaleStatus) ProtoMessage() {} +func (m *StorageClass) Reset() { *m = StorageClass{} } +func (*StorageClass) ProtoMessage() {} -func (m *SubresourceReference) Reset() { *m = SubresourceReference{} } -func (m *SubresourceReference) String() string { return proto.CompactTextString(m) } -func (*SubresourceReference) ProtoMessage() {} +func (m *StorageClassList) Reset() { *m = StorageClassList{} } +func (*StorageClassList) ProtoMessage() {} -func (m *SupplementalGroupsStrategyOptions) Reset() { *m = SupplementalGroupsStrategyOptions{} } -func (m *SupplementalGroupsStrategyOptions) String() string { return proto.CompactTextString(m) } -func (*SupplementalGroupsStrategyOptions) ProtoMessage() {} +func (m *SubresourceReference) Reset() { *m = SubresourceReference{} } +func (*SubresourceReference) ProtoMessage() {} -func (m *ThirdPartyResource) Reset() { *m = ThirdPartyResource{} } -func (m *ThirdPartyResource) String() string { return proto.CompactTextString(m) } -func (*ThirdPartyResource) ProtoMessage() {} +func (m *SupplementalGroupsStrategyOptions) Reset() { *m = SupplementalGroupsStrategyOptions{} } +func (*SupplementalGroupsStrategyOptions) ProtoMessage() {} -func (m *ThirdPartyResourceData) Reset() { *m = ThirdPartyResourceData{} } -func (m *ThirdPartyResourceData) String() string { return proto.CompactTextString(m) } -func (*ThirdPartyResourceData) ProtoMessage() {} +func (m *ThirdPartyResource) Reset() { *m = ThirdPartyResource{} } +func (*ThirdPartyResource) ProtoMessage() {} -func (m *ThirdPartyResourceDataList) Reset() { *m = ThirdPartyResourceDataList{} } -func (m *ThirdPartyResourceDataList) String() string { return proto.CompactTextString(m) } -func (*ThirdPartyResourceDataList) ProtoMessage() {} +func (m *ThirdPartyResourceData) Reset() { *m = ThirdPartyResourceData{} } +func (*ThirdPartyResourceData) ProtoMessage() {} -func (m *ThirdPartyResourceList) Reset() { *m = ThirdPartyResourceList{} } -func (m *ThirdPartyResourceList) String() string { return proto.CompactTextString(m) } -func (*ThirdPartyResourceList) ProtoMessage() {} +func (m *ThirdPartyResourceDataList) Reset() { *m = ThirdPartyResourceDataList{} } +func (*ThirdPartyResourceDataList) ProtoMessage() {} + +func (m *ThirdPartyResourceList) Reset() { *m = ThirdPartyResourceList{} } +func (*ThirdPartyResourceList) ProtoMessage() {} func init() { proto.RegisterType((*APIVersion)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.APIVersion") @@ -453,6 +396,8 @@ func init() { proto.RegisterType((*Scale)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.Scale") proto.RegisterType((*ScaleSpec)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.ScaleSpec") proto.RegisterType((*ScaleStatus)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.ScaleStatus") + proto.RegisterType((*StorageClass)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.StorageClass") + proto.RegisterType((*StorageClassList)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.StorageClassList") proto.RegisterType((*SubresourceReference)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.SubresourceReference") proto.RegisterType((*SupplementalGroupsStrategyOptions)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.SupplementalGroupsStrategyOptions") proto.RegisterType((*ThirdPartyResource)(nil), "k8s.io.kubernetes.pkg.apis.extensions.v1beta1.ThirdPartyResource") @@ -2895,6 +2840,91 @@ func (m *ScaleStatus) MarshalTo(data []byte) (int, error) { return i, nil } +func (m *StorageClass) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *StorageClass) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) + n72, err := m.ObjectMeta.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n72 + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(m.Provisioner))) + i += copy(data[i:], m.Provisioner) + if len(m.Parameters) > 0 { + for k := range m.Parameters { + data[i] = 0x1a + i++ + v := m.Parameters[k] + mapSize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + i = encodeVarintGenerated(data, i, uint64(mapSize)) + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(len(k))) + i += copy(data[i:], k) + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(len(v))) + i += copy(data[i:], v) + } + } + return i, nil +} + +func (m *StorageClassList) Marshal() (data []byte, err error) { + size := m.Size() + data = make([]byte, size) + n, err := m.MarshalTo(data) + if err != nil { + return nil, err + } + return data[:n], nil +} + +func (m *StorageClassList) MarshalTo(data []byte) (int, error) { + var i int + _ = i + var l int + _ = l + data[i] = 0xa + i++ + i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) + n73, err := m.ListMeta.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n73 + if len(m.Items) > 0 { + for _, msg := range m.Items { + data[i] = 0x12 + i++ + i = encodeVarintGenerated(data, i, uint64(msg.Size())) + n, err := msg.MarshalTo(data[i:]) + if err != nil { + return 0, err + } + i += n + } + } + return i, nil +} + func (m *SubresourceReference) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) @@ -2981,11 +3011,11 @@ func (m *ThirdPartyResource) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n72, err := m.ObjectMeta.MarshalTo(data[i:]) + n74, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n72 + i += n74 data[i] = 0x12 i++ i = encodeVarintGenerated(data, i, uint64(len(m.Description))) @@ -3023,11 +3053,11 @@ func (m *ThirdPartyResourceData) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ObjectMeta.Size())) - n73, err := m.ObjectMeta.MarshalTo(data[i:]) + n75, err := m.ObjectMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n73 + i += n75 if m.Data != nil { data[i] = 0x12 i++ @@ -3055,11 +3085,11 @@ func (m *ThirdPartyResourceDataList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n74, err := m.ListMeta.MarshalTo(data[i:]) + n76, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n74 + i += n76 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -3093,11 +3123,11 @@ func (m *ThirdPartyResourceList) MarshalTo(data []byte) (int, error) { data[i] = 0xa i++ i = encodeVarintGenerated(data, i, uint64(m.ListMeta.Size())) - n75, err := m.ListMeta.MarshalTo(data[i:]) + n77, err := m.ListMeta.MarshalTo(data[i:]) if err != nil { return 0, err } - i += n75 + i += n77 if len(m.Items) > 0 { for _, msg := range m.Items { data[i] = 0x12 @@ -3998,6 +4028,38 @@ func (m *ScaleStatus) Size() (n int) { return n } +func (m *StorageClass) Size() (n int) { + var l int + _ = l + l = m.ObjectMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + l = len(m.Provisioner) + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Parameters) > 0 { + for k, v := range m.Parameters { + _ = k + _ = v + mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) + n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) + } + } + return n +} + +func (m *StorageClassList) Size() (n int) { + var l int + _ = l + l = m.ListMeta.Size() + n += 1 + l + sovGenerated(uint64(l)) + if len(m.Items) > 0 { + for _, e := range m.Items { + l = e.Size() + n += 1 + l + sovGenerated(uint64(l)) + } + } + return n +} + func (m *SubresourceReference) Size() (n int) { var l int _ = l @@ -4095,6 +4157,883 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *APIVersion) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&APIVersion{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `}`, + }, "") + return s +} +func (this *CPUTargetUtilization) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CPUTargetUtilization{`, + `TargetPercentage:` + fmt.Sprintf("%v", this.TargetPercentage) + `,`, + `}`, + }, "") + return s +} +func (this *CustomMetricCurrentStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CustomMetricCurrentStatus{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `CurrentValue:` + strings.Replace(strings.Replace(this.CurrentValue.String(), "Quantity", "k8s_io_kubernetes_pkg_api_resource.Quantity", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CustomMetricCurrentStatusList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CustomMetricCurrentStatusList{`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "CustomMetricCurrentStatus", "CustomMetricCurrentStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CustomMetricTarget) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CustomMetricTarget{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `TargetValue:` + strings.Replace(strings.Replace(this.TargetValue.String(), "Quantity", "k8s_io_kubernetes_pkg_api_resource.Quantity", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *CustomMetricTargetList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&CustomMetricTargetList{`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "CustomMetricTarget", "CustomMetricTarget", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DaemonSet) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DaemonSet{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "DaemonSetSpec", "DaemonSetSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "DaemonSetStatus", "DaemonSetStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DaemonSetList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DaemonSetList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "DaemonSet", "DaemonSet", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DaemonSetSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DaemonSetSpec{`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DaemonSetStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DaemonSetStatus{`, + `CurrentNumberScheduled:` + fmt.Sprintf("%v", this.CurrentNumberScheduled) + `,`, + `NumberMisscheduled:` + fmt.Sprintf("%v", this.NumberMisscheduled) + `,`, + `DesiredNumberScheduled:` + fmt.Sprintf("%v", this.DesiredNumberScheduled) + `,`, + `}`, + }, "") + return s +} +func (this *Deployment) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Deployment{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "DeploymentSpec", "DeploymentSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "DeploymentStatus", "DeploymentStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeploymentList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeploymentList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Deployment", "Deployment", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeploymentRollback) String() string { + if this == nil { + return "nil" + } + keysForUpdatedAnnotations := make([]string, 0, len(this.UpdatedAnnotations)) + for k := range this.UpdatedAnnotations { + keysForUpdatedAnnotations = append(keysForUpdatedAnnotations, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForUpdatedAnnotations) + mapStringForUpdatedAnnotations := "map[string]string{" + for _, k := range keysForUpdatedAnnotations { + mapStringForUpdatedAnnotations += fmt.Sprintf("%v: %v,", k, this.UpdatedAnnotations[k]) + } + mapStringForUpdatedAnnotations += "}" + s := strings.Join([]string{`&DeploymentRollback{`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `UpdatedAnnotations:` + mapStringForUpdatedAnnotations + `,`, + `RollbackTo:` + strings.Replace(strings.Replace(this.RollbackTo.String(), "RollbackConfig", "RollbackConfig", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeploymentSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeploymentSpec{`, + `Replicas:` + valueToStringGenerated(this.Replicas) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `Strategy:` + strings.Replace(strings.Replace(this.Strategy.String(), "DeploymentStrategy", "DeploymentStrategy", 1), `&`, ``, 1) + `,`, + `MinReadySeconds:` + fmt.Sprintf("%v", this.MinReadySeconds) + `,`, + `RevisionHistoryLimit:` + valueToStringGenerated(this.RevisionHistoryLimit) + `,`, + `Paused:` + fmt.Sprintf("%v", this.Paused) + `,`, + `RollbackTo:` + strings.Replace(fmt.Sprintf("%v", this.RollbackTo), "RollbackConfig", "RollbackConfig", 1) + `,`, + `}`, + }, "") + return s +} +func (this *DeploymentStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeploymentStatus{`, + `ObservedGeneration:` + fmt.Sprintf("%v", this.ObservedGeneration) + `,`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `UpdatedReplicas:` + fmt.Sprintf("%v", this.UpdatedReplicas) + `,`, + `AvailableReplicas:` + fmt.Sprintf("%v", this.AvailableReplicas) + `,`, + `UnavailableReplicas:` + fmt.Sprintf("%v", this.UnavailableReplicas) + `,`, + `}`, + }, "") + return s +} +func (this *DeploymentStrategy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&DeploymentStrategy{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `RollingUpdate:` + strings.Replace(fmt.Sprintf("%v", this.RollingUpdate), "RollingUpdateDeployment", "RollingUpdateDeployment", 1) + `,`, + `}`, + }, "") + return s +} +func (this *ExportOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ExportOptions{`, + `Export:` + fmt.Sprintf("%v", this.Export) + `,`, + `Exact:` + fmt.Sprintf("%v", this.Exact) + `,`, + `}`, + }, "") + return s +} +func (this *FSGroupStrategyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&FSGroupStrategyOptions{`, + `Rule:` + fmt.Sprintf("%v", this.Rule) + `,`, + `Ranges:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ranges), "IDRange", "IDRange", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HTTPIngressPath) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HTTPIngressPath{`, + `Path:` + fmt.Sprintf("%v", this.Path) + `,`, + `Backend:` + strings.Replace(strings.Replace(this.Backend.String(), "IngressBackend", "IngressBackend", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HTTPIngressRuleValue) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HTTPIngressRuleValue{`, + `Paths:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Paths), "HTTPIngressPath", "HTTPIngressPath", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscaler) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscaler{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "HorizontalPodAutoscalerSpec", "HorizontalPodAutoscalerSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "HorizontalPodAutoscalerStatus", "HorizontalPodAutoscalerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "HorizontalPodAutoscaler", "HorizontalPodAutoscaler", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerSpec{`, + `ScaleRef:` + strings.Replace(strings.Replace(this.ScaleRef.String(), "SubresourceReference", "SubresourceReference", 1), `&`, ``, 1) + `,`, + `MinReplicas:` + valueToStringGenerated(this.MinReplicas) + `,`, + `MaxReplicas:` + fmt.Sprintf("%v", this.MaxReplicas) + `,`, + `CPUUtilization:` + strings.Replace(fmt.Sprintf("%v", this.CPUUtilization), "CPUTargetUtilization", "CPUTargetUtilization", 1) + `,`, + `}`, + }, "") + return s +} +func (this *HorizontalPodAutoscalerStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HorizontalPodAutoscalerStatus{`, + `ObservedGeneration:` + valueToStringGenerated(this.ObservedGeneration) + `,`, + `LastScaleTime:` + strings.Replace(fmt.Sprintf("%v", this.LastScaleTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `CurrentReplicas:` + fmt.Sprintf("%v", this.CurrentReplicas) + `,`, + `DesiredReplicas:` + fmt.Sprintf("%v", this.DesiredReplicas) + `,`, + `CurrentCPUUtilizationPercentage:` + valueToStringGenerated(this.CurrentCPUUtilizationPercentage) + `,`, + `}`, + }, "") + return s +} +func (this *HostPortRange) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&HostPortRange{`, + `Min:` + fmt.Sprintf("%v", this.Min) + `,`, + `Max:` + fmt.Sprintf("%v", this.Max) + `,`, + `}`, + }, "") + return s +} +func (this *IDRange) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IDRange{`, + `Min:` + fmt.Sprintf("%v", this.Min) + `,`, + `Max:` + fmt.Sprintf("%v", this.Max) + `,`, + `}`, + }, "") + return s +} +func (this *Ingress) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Ingress{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "IngressSpec", "IngressSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "IngressStatus", "IngressStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressBackend) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressBackend{`, + `ServiceName:` + fmt.Sprintf("%v", this.ServiceName) + `,`, + `ServicePort:` + strings.Replace(strings.Replace(this.ServicePort.String(), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Ingress", "Ingress", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressRule) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressRule{`, + `Host:` + fmt.Sprintf("%v", this.Host) + `,`, + `IngressRuleValue:` + strings.Replace(strings.Replace(this.IngressRuleValue.String(), "IngressRuleValue", "IngressRuleValue", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressRuleValue) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressRuleValue{`, + `HTTP:` + strings.Replace(fmt.Sprintf("%v", this.HTTP), "HTTPIngressRuleValue", "HTTPIngressRuleValue", 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressSpec{`, + `Backend:` + strings.Replace(fmt.Sprintf("%v", this.Backend), "IngressBackend", "IngressBackend", 1) + `,`, + `TLS:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.TLS), "IngressTLS", "IngressTLS", 1), `&`, ``, 1) + `,`, + `Rules:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Rules), "IngressRule", "IngressRule", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressStatus{`, + `LoadBalancer:` + strings.Replace(strings.Replace(this.LoadBalancer.String(), "LoadBalancerStatus", "k8s_io_kubernetes_pkg_api_v1.LoadBalancerStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *IngressTLS) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&IngressTLS{`, + `Hosts:` + fmt.Sprintf("%v", this.Hosts) + `,`, + `SecretName:` + fmt.Sprintf("%v", this.SecretName) + `,`, + `}`, + }, "") + return s +} +func (this *Job) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Job{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "JobSpec", "JobSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "JobStatus", "JobStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobCondition) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobCondition{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Status:` + fmt.Sprintf("%v", this.Status) + `,`, + `LastProbeTime:` + strings.Replace(strings.Replace(this.LastProbeTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `LastTransitionTime:` + strings.Replace(strings.Replace(this.LastTransitionTime.String(), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1), `&`, ``, 1) + `,`, + `Reason:` + fmt.Sprintf("%v", this.Reason) + `,`, + `Message:` + fmt.Sprintf("%v", this.Message) + `,`, + `}`, + }, "") + return s +} +func (this *JobList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Job", "Job", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobSpec{`, + `Parallelism:` + valueToStringGenerated(this.Parallelism) + `,`, + `Completions:` + valueToStringGenerated(this.Completions) + `,`, + `ActiveDeadlineSeconds:` + valueToStringGenerated(this.ActiveDeadlineSeconds) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `AutoSelector:` + valueToStringGenerated(this.AutoSelector) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *JobStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&JobStatus{`, + `Conditions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Conditions), "JobCondition", "JobCondition", 1), `&`, ``, 1) + `,`, + `StartTime:` + strings.Replace(fmt.Sprintf("%v", this.StartTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `CompletionTime:` + strings.Replace(fmt.Sprintf("%v", this.CompletionTime), "Time", "k8s_io_kubernetes_pkg_api_unversioned.Time", 1) + `,`, + `Active:` + fmt.Sprintf("%v", this.Active) + `,`, + `Succeeded:` + fmt.Sprintf("%v", this.Succeeded) + `,`, + `Failed:` + fmt.Sprintf("%v", this.Failed) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelector) String() string { + if this == nil { + return "nil" + } + keysForMatchLabels := make([]string, 0, len(this.MatchLabels)) + for k := range this.MatchLabels { + keysForMatchLabels = append(keysForMatchLabels, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForMatchLabels) + mapStringForMatchLabels := "map[string]string{" + for _, k := range keysForMatchLabels { + mapStringForMatchLabels += fmt.Sprintf("%v: %v,", k, this.MatchLabels[k]) + } + mapStringForMatchLabels += "}" + s := strings.Join([]string{`&LabelSelector{`, + `MatchLabels:` + mapStringForMatchLabels + `,`, + `MatchExpressions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.MatchExpressions), "LabelSelectorRequirement", "LabelSelectorRequirement", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *LabelSelectorRequirement) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&LabelSelectorRequirement{`, + `Key:` + fmt.Sprintf("%v", this.Key) + `,`, + `Operator:` + fmt.Sprintf("%v", this.Operator) + `,`, + `Values:` + fmt.Sprintf("%v", this.Values) + `,`, + `}`, + }, "") + return s +} +func (this *ListOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ListOptions{`, + `LabelSelector:` + fmt.Sprintf("%v", this.LabelSelector) + `,`, + `FieldSelector:` + fmt.Sprintf("%v", this.FieldSelector) + `,`, + `Watch:` + fmt.Sprintf("%v", this.Watch) + `,`, + `ResourceVersion:` + fmt.Sprintf("%v", this.ResourceVersion) + `,`, + `TimeoutSeconds:` + valueToStringGenerated(this.TimeoutSeconds) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicy{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "NetworkPolicySpec", "NetworkPolicySpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicyIngressRule) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicyIngressRule{`, + `Ports:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ports), "NetworkPolicyPort", "NetworkPolicyPort", 1), `&`, ``, 1) + `,`, + `From:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.From), "NetworkPolicyPeer", "NetworkPolicyPeer", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicyList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicyList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "NetworkPolicy", "NetworkPolicy", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicyPeer) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicyPeer{`, + `PodSelector:` + strings.Replace(fmt.Sprintf("%v", this.PodSelector), "LabelSelector", "LabelSelector", 1) + `,`, + `NamespaceSelector:` + strings.Replace(fmt.Sprintf("%v", this.NamespaceSelector), "LabelSelector", "LabelSelector", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicyPort) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicyPort{`, + `Protocol:` + valueToStringGenerated(this.Protocol) + `,`, + `Port:` + strings.Replace(fmt.Sprintf("%v", this.Port), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1) + `,`, + `}`, + }, "") + return s +} +func (this *NetworkPolicySpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&NetworkPolicySpec{`, + `PodSelector:` + strings.Replace(strings.Replace(this.PodSelector.String(), "LabelSelector", "LabelSelector", 1), `&`, ``, 1) + `,`, + `Ingress:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ingress), "NetworkPolicyIngressRule", "NetworkPolicyIngressRule", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodSecurityPolicy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodSecurityPolicy{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodSecurityPolicySpec", "PodSecurityPolicySpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodSecurityPolicyList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodSecurityPolicyList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PodSecurityPolicy", "PodSecurityPolicy", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodSecurityPolicySpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodSecurityPolicySpec{`, + `Privileged:` + fmt.Sprintf("%v", this.Privileged) + `,`, + `DefaultAddCapabilities:` + fmt.Sprintf("%v", this.DefaultAddCapabilities) + `,`, + `RequiredDropCapabilities:` + fmt.Sprintf("%v", this.RequiredDropCapabilities) + `,`, + `AllowedCapabilities:` + fmt.Sprintf("%v", this.AllowedCapabilities) + `,`, + `Volumes:` + fmt.Sprintf("%v", this.Volumes) + `,`, + `HostNetwork:` + fmt.Sprintf("%v", this.HostNetwork) + `,`, + `HostPorts:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.HostPorts), "HostPortRange", "HostPortRange", 1), `&`, ``, 1) + `,`, + `HostPID:` + fmt.Sprintf("%v", this.HostPID) + `,`, + `HostIPC:` + fmt.Sprintf("%v", this.HostIPC) + `,`, + `SELinux:` + strings.Replace(strings.Replace(this.SELinux.String(), "SELinuxStrategyOptions", "SELinuxStrategyOptions", 1), `&`, ``, 1) + `,`, + `RunAsUser:` + strings.Replace(strings.Replace(this.RunAsUser.String(), "RunAsUserStrategyOptions", "RunAsUserStrategyOptions", 1), `&`, ``, 1) + `,`, + `SupplementalGroups:` + strings.Replace(strings.Replace(this.SupplementalGroups.String(), "SupplementalGroupsStrategyOptions", "SupplementalGroupsStrategyOptions", 1), `&`, ``, 1) + `,`, + `FSGroup:` + strings.Replace(strings.Replace(this.FSGroup.String(), "FSGroupStrategyOptions", "FSGroupStrategyOptions", 1), `&`, ``, 1) + `,`, + `ReadOnlyRootFilesystem:` + fmt.Sprintf("%v", this.ReadOnlyRootFilesystem) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicaSet) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicaSet{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ReplicaSetSpec", "ReplicaSetSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ReplicaSetStatus", "ReplicaSetStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicaSetList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicaSetList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ReplicaSet", "ReplicaSet", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicaSetSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicaSetSpec{`, + `Replicas:` + valueToStringGenerated(this.Replicas) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "LabelSelector", 1) + `,`, + `Template:` + strings.Replace(strings.Replace(this.Template.String(), "PodTemplateSpec", "k8s_io_kubernetes_pkg_api_v1.PodTemplateSpec", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicaSetStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicaSetStatus{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `FullyLabeledReplicas:` + fmt.Sprintf("%v", this.FullyLabeledReplicas) + `,`, + `ObservedGeneration:` + fmt.Sprintf("%v", this.ObservedGeneration) + `,`, + `}`, + }, "") + return s +} +func (this *ReplicationControllerDummy) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ReplicationControllerDummy{`, + `}`, + }, "") + return s +} +func (this *RollbackConfig) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RollbackConfig{`, + `Revision:` + fmt.Sprintf("%v", this.Revision) + `,`, + `}`, + }, "") + return s +} +func (this *RollingUpdateDeployment) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RollingUpdateDeployment{`, + `MaxUnavailable:` + strings.Replace(fmt.Sprintf("%v", this.MaxUnavailable), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1) + `,`, + `MaxSurge:` + strings.Replace(fmt.Sprintf("%v", this.MaxSurge), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1) + `,`, + `}`, + }, "") + return s +} +func (this *RunAsUserStrategyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RunAsUserStrategyOptions{`, + `Rule:` + fmt.Sprintf("%v", this.Rule) + `,`, + `Ranges:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ranges), "IDRange", "IDRange", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *SELinuxStrategyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SELinuxStrategyOptions{`, + `Rule:` + fmt.Sprintf("%v", this.Rule) + `,`, + `SELinuxOptions:` + strings.Replace(fmt.Sprintf("%v", this.SELinuxOptions), "SELinuxOptions", "k8s_io_kubernetes_pkg_api_v1.SELinuxOptions", 1) + `,`, + `}`, + }, "") + return s +} +func (this *Scale) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Scale{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ScaleSpec", "ScaleSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "ScaleStatus", "ScaleStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ScaleSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ScaleSpec{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `}`, + }, "") + return s +} +func (this *ScaleStatus) String() string { + if this == nil { + return "nil" + } + keysForSelector := make([]string, 0, len(this.Selector)) + for k := range this.Selector { + keysForSelector = append(keysForSelector, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForSelector) + mapStringForSelector := "map[string]string{" + for _, k := range keysForSelector { + mapStringForSelector += fmt.Sprintf("%v: %v,", k, this.Selector[k]) + } + mapStringForSelector += "}" + s := strings.Join([]string{`&ScaleStatus{`, + `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`, + `Selector:` + mapStringForSelector + `,`, + `TargetSelector:` + fmt.Sprintf("%v", this.TargetSelector) + `,`, + `}`, + }, "") + return s +} +func (this *StorageClass) String() string { + if this == nil { + return "nil" + } + keysForParameters := make([]string, 0, len(this.Parameters)) + for k := range this.Parameters { + keysForParameters = append(keysForParameters, k) + } + github_com_gogo_protobuf_sortkeys.Strings(keysForParameters) + mapStringForParameters := "map[string]string{" + for _, k := range keysForParameters { + mapStringForParameters += fmt.Sprintf("%v: %v,", k, this.Parameters[k]) + } + mapStringForParameters += "}" + s := strings.Join([]string{`&StorageClass{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Provisioner:` + fmt.Sprintf("%v", this.Provisioner) + `,`, + `Parameters:` + mapStringForParameters + `,`, + `}`, + }, "") + return s +} +func (this *StorageClassList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&StorageClassList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "StorageClass", "StorageClass", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *SubresourceReference) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SubresourceReference{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `Subresource:` + fmt.Sprintf("%v", this.Subresource) + `,`, + `}`, + }, "") + return s +} +func (this *SupplementalGroupsStrategyOptions) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&SupplementalGroupsStrategyOptions{`, + `Rule:` + fmt.Sprintf("%v", this.Rule) + `,`, + `Ranges:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Ranges), "IDRange", "IDRange", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ThirdPartyResource) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ThirdPartyResource{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Description:` + fmt.Sprintf("%v", this.Description) + `,`, + `Versions:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Versions), "APIVersion", "APIVersion", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ThirdPartyResourceData) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ThirdPartyResourceData{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Data:` + valueToStringGenerated(this.Data) + `,`, + `}`, + }, "") + return s +} +func (this *ThirdPartyResourceDataList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ThirdPartyResourceDataList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ThirdPartyResourceData", "ThirdPartyResourceData", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ThirdPartyResourceList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ThirdPartyResourceList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ThirdPartyResource", "ThirdPartyResource", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *APIVersion) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 @@ -12150,6 +13089,337 @@ func (m *ScaleStatus) Unmarshal(data []byte) error { } return nil } +func (m *StorageClass) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageClass: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageClass: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ObjectMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ObjectMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Provisioner", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLen |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + intStringLen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Provisioner = string(data[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Parameters", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + var keykey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + keykey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLenmapkey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey := string(data[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + var valuekey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + valuekey |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + var stringLenmapvalue uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + stringLenmapvalue |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapvalue := int(stringLenmapvalue) + if intStringLenmapvalue < 0 { + return ErrInvalidLengthGenerated + } + postStringIndexmapvalue := iNdEx + intStringLenmapvalue + if postStringIndexmapvalue > l { + return io.ErrUnexpectedEOF + } + mapvalue := string(data[iNdEx:postStringIndexmapvalue]) + iNdEx = postStringIndexmapvalue + if m.Parameters == nil { + m.Parameters = make(map[string]string) + } + m.Parameters[mapkey] = mapvalue + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *StorageClassList) Unmarshal(data []byte) error { + l := len(data) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StorageClassList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StorageClassList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ListMeta", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ListMeta.Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Items", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenerated + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := data[iNdEx] + iNdEx++ + msglen |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenerated + } + postIndex := iNdEx + msglen + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Items = append(m.Items, StorageClass{}) + if err := m.Items[len(m.Items)-1].Unmarshal(data[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenerated(data[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenerated + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *SubresourceReference) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.proto index bd4da6974f24..8abe881b6804 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -70,25 +70,25 @@ message CustomMetricTargetList { // DaemonSet represents the configuration of a daemon set. message DaemonSet { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional DaemonSetSpec spec = 2; // Status is the current status of this daemon set. This data may be // out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional DaemonSetStatus status = 3; } // DaemonSetList is a collection of daemon sets. message DaemonSetList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of daemon sets. @@ -100,14 +100,14 @@ message DaemonSetSpec { // Selector is a label query over pods that are managed by the daemon set. // Must match in order to be controlled. // If empty, defaulted to labels on Pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional LabelSelector selector = 1; // Template is the object that describes the pod that will be created. // The DaemonSet will create exactly one copy of this pod on every node // that matches the template's node selector (or on every node if no node // selector is specified). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 2; } @@ -115,17 +115,17 @@ message DaemonSetSpec { message DaemonSetStatus { // CurrentNumberScheduled is the number of nodes that are running at least 1 // daemon pod and are supposed to run the daemon pod. - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md optional int32 currentNumberScheduled = 1; // NumberMisscheduled is the number of nodes that are running the daemon pod, but are // not supposed to run the daemon pod. - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md optional int32 numberMisscheduled = 2; // DesiredNumberScheduled is the total number of nodes that should be running the daemon // pod (including nodes correctly running the daemon pod). - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md optional int32 desiredNumberScheduled = 3; } @@ -274,10 +274,10 @@ message HTTPIngressRuleValue { // configuration of a horizontal pod autoscaler. message HorizontalPodAutoscaler { - // Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; - // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. optional HorizontalPodAutoscalerSpec spec = 2; // current information about the autoscaler. @@ -355,15 +355,15 @@ message IDRange { // based virtual hosting etc. message Ingress { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec is the desired state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional IngressSpec spec = 2; // Status is the current state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional IngressStatus status = 3; } @@ -379,7 +379,7 @@ message IngressBackend { // IngressList is a collection of Ingress. message IngressList { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of Ingress. @@ -465,15 +465,15 @@ message IngressTLS { // Job represents the configuration of a single job. message Job { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobSpec spec = 2; // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional JobStatus status = 3; } @@ -501,7 +501,7 @@ message JobCondition { // JobList is a collection of jobs. message JobList { // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of Job. @@ -514,7 +514,7 @@ message JobSpec { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 parallelism = 1; // Completions specifies the desired number of successfully finished pods the @@ -522,7 +522,7 @@ message JobSpec { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional int32 completions = 2; // Optional duration in seconds relative to the startTime that the job may be active @@ -531,26 +531,26 @@ message JobSpec { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional LabelSelector selector = 4; // AutoSelector controls generation of pod labels and pod selectors. // It was not present in the original extensions/v1beta1 Job definition, but exists // to allow conversion from batch/v1 Jobs, where it corresponds to, but has the opposite // meaning as, ManualSelector. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md optional bool autoSelector = 5; // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 6; } // JobStatus represents the current state of a Job. message JobStatus { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md repeated JobCondition conditions = 1; // StartTime represents time when the job was acknowledged by the Job Manager. @@ -627,7 +627,7 @@ message ListOptions { message NetworkPolicy { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Specification of the desired behavior for this NetworkPolicy. @@ -658,7 +658,7 @@ message NetworkPolicyIngressRule { // Network Policy List is a list of NetworkPolicy objects. message NetworkPolicyList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of schema objects. @@ -716,7 +716,7 @@ message NetworkPolicySpec { // that will be applied to a pod and container. message PodSecurityPolicy { // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // spec defines the policy enforced. @@ -726,7 +726,7 @@ message PodSecurityPolicy { // Pod Security Policy List is a list of PodSecurityPolicy objects. message PodSecurityPolicyList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is a list of schema objects. @@ -792,29 +792,29 @@ message PodSecurityPolicySpec { message ReplicaSet { // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. - // Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; // Spec defines the specification of the desired behavior of the ReplicaSet. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ReplicaSetSpec spec = 2; // Status is the most recently observed status of the ReplicaSet. // This data may be out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status optional ReplicaSetStatus status = 3; } // ReplicaSetList is a collection of ReplicaSets. message ReplicaSetList { // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // List of ReplicaSets. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md repeated ReplicaSet items = 2; } @@ -823,25 +823,25 @@ message ReplicaSetSpec { // Replicas is the number of desired replicas. // This is a pointer to distinguish between explicit zero and unspecified. // Defaults to 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller optional int32 replicas = 1; // Selector is a label query over pods that should match the replica count. // If the selector is empty, it is defaulted to the labels present on the pod template. // Label keys and values that must match in order to be controlled by this replica set. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional LabelSelector selector = 2; // Template is the object that describes the pod that will be created if // insufficient replicas are detected. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template optional k8s.io.kubernetes.pkg.api.v1.PodTemplateSpec template = 3; } // ReplicaSetStatus represents the current status of a ReplicaSet. message ReplicaSetStatus { // Replicas is the most recently oberved number of replicas. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller optional int32 replicas = 1; // The number of pods that have labels matching the labels of the pod template of the replicaset. @@ -903,19 +903,19 @@ message SELinuxStrategyOptions { optional string rule = 1; // seLinuxOptions required to run as; required for MustRunAs - // More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md#security-context + // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md#security-context optional k8s.io.kubernetes.pkg.api.v1.SELinuxOptions seLinuxOptions = 2; } // represents a scaling request for a resource. message Scale { - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. optional ScaleSpec spec = 2; - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. optional ScaleStatus status = 3; } @@ -930,7 +930,7 @@ message ScaleStatus { // actual number of observed instances of the scaled object. optional int32 replicas = 1; - // label query over pods that should match the replicas count. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // label query over pods that should match the replicas count. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors map selector = 2; // label selector for pods that should match the replicas count. This is a serializated @@ -938,16 +938,44 @@ message ScaleStatus { // avoid introspection in the clients. The string will be in the same format as the // query-param syntax. If the target type only supports map-based selectors, both this // field and map-based selector field are populated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors optional string targetSelector = 3; } +// StorageClass describes the parameters for a class of storage for +// which PersistentVolumes can be dynamically provisioned. +// +// StorageClasses are non-namespaced; the name of the storage class +// according to etcd is in ObjectMeta.Name. +message StorageClass { + // Standard object's metadata. + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + optional k8s.io.kubernetes.pkg.api.v1.ObjectMeta metadata = 1; + + // Provisioner indicates the type of the provisioner. + optional string provisioner = 2; + + // Parameters holds the parameters for the provisioner that should + // create volumes of this storage class. + map parameters = 3; +} + +// StorageClassList is a collection of storage classes. +message StorageClassList { + // Standard list metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; + + // Items is the list of StorageClasses + repeated StorageClass items = 2; +} + // SubresourceReference contains enough information to let you inspect or modify the referred subresource. message SubresourceReference { - // Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds optional string kind = 1; - // Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names optional string name = 2; // API version of the referent @@ -992,7 +1020,7 @@ message ThirdPartyResourceData { // ThirdPartyResrouceDataList is a list of ThirdPartyResourceData. message ThirdPartyResourceDataList { // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata optional k8s.io.kubernetes.pkg.api.unversioned.ListMeta metadata = 1; // Items is the list of ThirdpartyResourceData. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go index e8bbf28b100f..0dce6f07ce6f 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -63,6 +63,8 @@ func addKnownTypes(scheme *runtime.Scheme) { &PodSecurityPolicyList{}, &NetworkPolicy{}, &NetworkPolicyList{}, + &StorageClass{}, + &StorageClassList{}, ) // Add the watch version that applies versionedwatch.AddToGroupVersion(scheme, SchemeGroupVersion) diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go index cbe82eff3160..b6718664c499 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20980,6 +20980,718 @@ func (x *NetworkPolicyList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } +func (x *StorageClass) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [5]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[2] = len(x.Parameters) != 0 + yyq2[3] = x.Kind != "" + yyq2[4] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(5) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ObjectMeta + yy4.CodecEncodeSelf(e) + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ObjectMeta + yy6.CodecEncodeSelf(e) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Provisioner)) + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("provisioner")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Provisioner)) + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + if x.Parameters == nil { + r.EncodeNil() + } else { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + z.F.EncMapStringStringV(x.Parameters, false, e) + } + } + } else { + r.EncodeNil() + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("parameters")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Parameters == nil { + r.EncodeNil() + } else { + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + z.F.EncMapStringStringV(x.Parameters, false, e) + } + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[4] { + yym18 := z.EncBinary() + _ = yym18 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[4] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym19 := z.EncBinary() + _ = yym19 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *StorageClass) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *StorageClass) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_v1.ObjectMeta{} + } else { + yyv4 := &x.ObjectMeta + yyv4.CodecDecodeSelf(d) + } + case "provisioner": + if r.TryDecodeAsNil() { + x.Provisioner = "" + } else { + x.Provisioner = string(r.DecodeString()) + } + case "parameters": + if r.TryDecodeAsNil() { + x.Parameters = nil + } else { + yyv6 := &x.Parameters + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + z.F.DecMapStringStringX(yyv6, false, d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *StorageClass) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ObjectMeta = pkg2_v1.ObjectMeta{} + } else { + yyv11 := &x.ObjectMeta + yyv11.CodecDecodeSelf(d) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Provisioner = "" + } else { + x.Provisioner = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Parameters = nil + } else { + yyv13 := &x.Parameters + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + z.F.DecMapStringStringX(yyv13, false, d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x *StorageClassList) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yym1 := z.EncBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.EncExt(x) { + } else { + yysep2 := !z.EncBinary() + yy2arr2 := z.EncBasicHandle().StructToArray + var yyq2 [4]bool + _, _, _ = yysep2, yyq2, yy2arr2 + const yyr2 bool = false + yyq2[0] = true + yyq2[2] = x.Kind != "" + yyq2[3] = x.APIVersion != "" + var yynn2 int + if yyr2 || yy2arr2 { + r.EncodeArrayStart(4) + } else { + yynn2 = 1 + for _, b := range yyq2 { + if b { + yynn2++ + } + } + r.EncodeMapStart(yynn2) + yynn2 = 0 + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[0] { + yy4 := &x.ListMeta + yym5 := z.EncBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.EncExt(yy4) { + } else { + z.EncFallback(yy4) + } + } else { + r.EncodeNil() + } + } else { + if yyq2[0] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("metadata")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yy6 := &x.ListMeta + yym7 := z.EncBinary() + _ = yym7 + if false { + } else if z.HasExtensions() && z.EncExt(yy6) { + } else { + z.EncFallback(yy6) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym9 := z.EncBinary() + _ = yym9 + if false { + } else { + h.encSliceStorageClass(([]StorageClass)(x.Items), e) + } + } + } else { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("items")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + if x.Items == nil { + r.EncodeNil() + } else { + yym10 := z.EncBinary() + _ = yym10 + if false { + } else { + h.encSliceStorageClass(([]StorageClass)(x.Items), e) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[2] { + yym12 := z.EncBinary() + _ = yym12 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[2] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("kind")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym13 := z.EncBinary() + _ = yym13 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + if yyq2[3] { + yym15 := z.EncBinary() + _ = yym15 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } else { + r.EncodeString(codecSelferC_UTF81234, "") + } + } else { + if yyq2[3] { + z.EncSendContainerState(codecSelfer_containerMapKey1234) + r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) + z.EncSendContainerState(codecSelfer_containerMapValue1234) + yym16 := z.EncBinary() + _ = yym16 + if false { + } else { + r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) + } + } + } + if yyr2 || yy2arr2 { + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + z.EncSendContainerState(codecSelfer_containerMapEnd1234) + } + } + } +} + +func (x *StorageClassList) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + yym1 := z.DecBinary() + _ = yym1 + if false { + } else if z.HasExtensions() && z.DecExt(x) { + } else { + yyct2 := r.ContainerType() + if yyct2 == codecSelferValueTypeMap1234 { + yyl2 := r.ReadMapStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerMapEnd1234) + } else { + x.codecDecodeSelfFromMap(yyl2, d) + } + } else if yyct2 == codecSelferValueTypeArray1234 { + yyl2 := r.ReadArrayStart() + if yyl2 == 0 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + } else { + x.codecDecodeSelfFromArray(yyl2, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) + } + } +} + +func (x *StorageClassList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys3Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys3Slc + var yyhl3 bool = l >= 0 + for yyj3 := 0; ; yyj3++ { + if yyhl3 { + if yyj3 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + } + z.DecSendContainerState(codecSelfer_containerMapKey1234) + yys3Slc = r.DecodeBytes(yys3Slc, true, true) + yys3 := string(yys3Slc) + z.DecSendContainerState(codecSelfer_containerMapValue1234) + switch yys3 { + case "metadata": + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv4 := &x.ListMeta + yym5 := z.DecBinary() + _ = yym5 + if false { + } else if z.HasExtensions() && z.DecExt(yyv4) { + } else { + z.DecFallback(yyv4, false) + } + } + case "items": + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv6 := &x.Items + yym7 := z.DecBinary() + _ = yym7 + if false { + } else { + h.decSliceStorageClass((*[]StorageClass)(yyv6), d) + } + } + case "kind": + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + case "apiVersion": + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + default: + z.DecStructFieldNotFound(-1, yys3) + } // end switch yys3 + } // end for yyj3 + z.DecSendContainerState(codecSelfer_containerMapEnd1234) +} + +func (x *StorageClassList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.ListMeta = pkg1_unversioned.ListMeta{} + } else { + yyv11 := &x.ListMeta + yym12 := z.DecBinary() + _ = yym12 + if false { + } else if z.HasExtensions() && z.DecExt(yyv11) { + } else { + z.DecFallback(yyv11, false) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Items = nil + } else { + yyv13 := &x.Items + yym14 := z.DecBinary() + _ = yym14 + if false { + } else { + h.decSliceStorageClass((*[]StorageClass)(yyv13), d) + } + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.Kind = "" + } else { + x.Kind = string(r.DecodeString()) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) + return + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + if r.TryDecodeAsNil() { + x.APIVersion = "" + } else { + x.APIVersion = string(r.DecodeString()) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + z.DecSendContainerState(codecSelfer_containerArrayElem1234) + z.DecStructFieldNotFound(yyj10-1, "") + } + z.DecSendContainerState(codecSelfer_containerArrayEnd1234) +} + func (x codecSelfer1234) encSliceCustomMetricTarget(v []CustomMetricTarget, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) @@ -23937,3 +24649,122 @@ func (x codecSelfer1234) decSliceNetworkPolicy(v *[]NetworkPolicy, d *codec1978. *v = yyv1 } } + +func (x codecSelfer1234) encSliceStorageClass(v []StorageClass, e *codec1978.Encoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + for _, yyv1 := range v { + z.EncSendContainerState(codecSelfer_containerArrayElem1234) + yy2 := &yyv1 + yy2.CodecEncodeSelf(e) + } + z.EncSendContainerState(codecSelfer_containerArrayEnd1234) +} + +func (x codecSelfer1234) decSliceStorageClass(v *[]StorageClass, d *codec1978.Decoder) { + var h codecSelfer1234 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv1 := *v + yyh1, yyl1 := z.DecSliceHelperStart() + var yyc1 bool + _ = yyc1 + if yyl1 == 0 { + if yyv1 == nil { + yyv1 = []StorageClass{} + yyc1 = true + } else if len(yyv1) != 0 { + yyv1 = yyv1[:0] + yyc1 = true + } + } else if yyl1 > 0 { + var yyrr1, yyrl1 int + var yyrt1 bool + _, _ = yyrl1, yyrt1 + yyrr1 = yyl1 // len(yyv1) + if yyl1 > cap(yyv1) { + + yyrg1 := len(yyv1) > 0 + yyv21 := yyv1 + yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 264) + if yyrt1 { + if yyrl1 <= cap(yyv1) { + yyv1 = yyv1[:yyrl1] + } else { + yyv1 = make([]StorageClass, yyrl1) + } + } else { + yyv1 = make([]StorageClass, yyrl1) + } + yyc1 = true + yyrr1 = len(yyv1) + if yyrg1 { + copy(yyv1, yyv21) + } + } else if yyl1 != len(yyv1) { + yyv1 = yyv1[:yyl1] + yyc1 = true + } + yyj1 := 0 + for ; yyj1 < yyrr1; yyj1++ { + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv2 := &yyv1[yyj1] + yyv2.CodecDecodeSelf(d) + } + + } + if yyrt1 { + for ; yyj1 < yyl1; yyj1++ { + yyv1 = append(yyv1, StorageClass{}) + yyh1.ElemContainerState(yyj1) + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv3 := &yyv1[yyj1] + yyv3.CodecDecodeSelf(d) + } + + } + } + + } else { + yyj1 := 0 + for ; !r.CheckBreak(); yyj1++ { + + if yyj1 >= len(yyv1) { + yyv1 = append(yyv1, StorageClass{}) // var yyz1 StorageClass + yyc1 = true + } + yyh1.ElemContainerState(yyj1) + if yyj1 < len(yyv1) { + if r.TryDecodeAsNil() { + yyv1[yyj1] = StorageClass{} + } else { + yyv4 := &yyv1[yyj1] + yyv4.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + if yyj1 < len(yyv1) { + yyv1 = yyv1[:yyj1] + yyc1 = true + } else if yyj1 == 0 && yyv1 == nil { + yyv1 = []StorageClass{} + yyc1 = true + } + } + yyh1.End() + if yyc1 { + *v = yyv1 + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go index 7fead65b9512..bf46988fafd7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ type ScaleStatus struct { // actual number of observed instances of the scaled object. Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` - // label query over pods that should match the replicas count. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // label query over pods that should match the replicas count. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector map[string]string `json:"selector,omitempty" protobuf:"bytes,2,rep,name=selector"` // label selector for pods that should match the replicas count. This is a serializated @@ -42,22 +42,23 @@ type ScaleStatus struct { // avoid introspection in the clients. The string will be in the same format as the // query-param syntax. If the target type only supports map-based selectors, both this // field and map-based selector field are populated. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors TargetSelector string `json:"targetSelector,omitempty" protobuf:"bytes,3,opt,name=targetSelector"` } -// +genclient=true,noMethods=true +// +genclient=true +// +noMethods=true // represents a scaling request for a resource. type Scale struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata. + // Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata. v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec ScaleSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` - // current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only. + // current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only. Status ScaleStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -68,9 +69,9 @@ type ReplicationControllerDummy struct { // SubresourceReference contains enough information to let you inspect or modify the referred subresource. type SubresourceReference struct { - // Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"` - // Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names + // Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names Name string `json:"name,omitempty" protobuf:"bytes,2,opt,name=name"` // API version of the referent APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,3,opt,name=apiVersion"` @@ -146,10 +147,10 @@ type HorizontalPodAutoscalerStatus struct { // configuration of a horizontal pod autoscaler. type HorizontalPodAutoscaler struct { unversioned.TypeMeta `json:",inline"` - // Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - // behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. + // behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Spec HorizontalPodAutoscalerSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // current information about the autoscaler. @@ -166,7 +167,8 @@ type HorizontalPodAutoscalerList struct { Items []HorizontalPodAutoscaler `json:"items" protobuf:"bytes,2,rep,name=items"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // A ThirdPartyResource is a generic representation of a resource, it is used by add-ons and plugins to add new resource // types to the API. It consists of one or more Versions of the api. @@ -410,14 +412,14 @@ type DaemonSetSpec struct { // Selector is a label query over pods that are managed by the daemon set. // Must match in order to be controlled. // If empty, defaulted to labels on Pod template. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty" protobuf:"bytes,1,opt,name=selector"` // Template is the object that describes the pod that will be created. // The DaemonSet will create exactly one copy of this pod on every node // that matches the template's node selector (or on every node if no node // selector is specified). - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,2,opt,name=template"` // TODO(madhusudancs): Uncomment while implementing DaemonSet updates. @@ -447,17 +449,17 @@ const ( type DaemonSetStatus struct { // CurrentNumberScheduled is the number of nodes that are running at least 1 // daemon pod and are supposed to run the daemon pod. - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md CurrentNumberScheduled int32 `json:"currentNumberScheduled" protobuf:"varint,1,opt,name=currentNumberScheduled"` // NumberMisscheduled is the number of nodes that are running the daemon pod, but are // not supposed to run the daemon pod. - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md NumberMisscheduled int32 `json:"numberMisscheduled" protobuf:"varint,2,opt,name=numberMisscheduled"` // DesiredNumberScheduled is the total number of nodes that should be running the daemon // pod (including nodes correctly running the daemon pod). - // More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md + // More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md DesiredNumberScheduled int32 `json:"desiredNumberScheduled" protobuf:"varint,3,opt,name=desiredNumberScheduled"` } @@ -467,18 +469,18 @@ type DaemonSetStatus struct { type DaemonSet struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the desired behavior of this daemon set. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec DaemonSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current status of this daemon set. This data may be // out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status DaemonSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -486,7 +488,7 @@ type DaemonSet struct { type DaemonSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of daemon sets. @@ -497,7 +499,7 @@ type DaemonSetList struct { type ThirdPartyResourceDataList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of ThirdpartyResourceData. @@ -510,15 +512,15 @@ type ThirdPartyResourceDataList struct { type Job struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is a structure defining the expected behavior of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec JobSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is a structure describing current status of a job. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status JobStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -526,7 +528,7 @@ type Job struct { type JobList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Job. @@ -540,7 +542,7 @@ type JobSpec struct { // run at any given time. The actual number of pods running in steady state will // be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), // i.e. when the work left to do is less than max parallelism. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Parallelism *int32 `json:"parallelism,omitempty" protobuf:"varint,1,opt,name=parallelism"` // Completions specifies the desired number of successfully finished pods the @@ -548,7 +550,7 @@ type JobSpec struct { // pod signals the success of all pods, and allows parallelism to have any positive // value. Setting to 1 means that parallelism is limited to 1 and the success of that // pod signals the success of the job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Completions *int32 `json:"completions,omitempty" protobuf:"varint,2,opt,name=completions"` // Optional duration in seconds relative to the startTime that the job may be active @@ -557,19 +559,19 @@ type JobSpec struct { // Selector is a label query over pods that should match the pod count. // Normally, the system sets this field for you. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty" protobuf:"bytes,4,opt,name=selector"` // AutoSelector controls generation of pod labels and pod selectors. // It was not present in the original extensions/v1beta1 Job definition, but exists // to allow conversion from batch/v1 Jobs, where it corresponds to, but has the opposite // meaning as, ManualSelector. - // More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md + // More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md AutoSelector *bool `json:"autoSelector,omitempty" protobuf:"varint,5,opt,name=autoSelector"` // Template is the object that describes the pod that will be created when // executing a job. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Template v1.PodTemplateSpec `json:"template" protobuf:"bytes,6,opt,name=template"` } @@ -577,7 +579,7 @@ type JobSpec struct { type JobStatus struct { // Conditions represent the latest available observations of an object's current state. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md Conditions []JobCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` // StartTime represents time when the job was acknowledged by the Job Manager. @@ -635,15 +637,15 @@ type JobCondition struct { type Ingress struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec is the desired state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec IngressSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the current state of the Ingress. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status IngressStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -651,7 +653,7 @@ type Ingress struct { type IngressList struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is the list of Ingress. @@ -852,18 +854,18 @@ type ReplicaSet struct { // If the Labels of a ReplicaSet are empty, they are defaulted to // be the same as the Pod(s) that the ReplicaSet manages. - // Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Spec defines the specification of the desired behavior of the ReplicaSet. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Spec ReplicaSetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Status is the most recently observed status of the ReplicaSet. // This data may be out of date by some window of time. // Populated by the system. // Read-only. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status Status ReplicaSetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } @@ -871,11 +873,11 @@ type ReplicaSet struct { type ReplicaSetList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // List of ReplicaSets. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md Items []ReplicaSet `json:"items" protobuf:"bytes,2,rep,name=items"` } @@ -884,25 +886,25 @@ type ReplicaSetSpec struct { // Replicas is the number of desired replicas. // This is a pointer to distinguish between explicit zero and unspecified. // Defaults to 1. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // Selector is a label query over pods that should match the replica count. // If the selector is empty, it is defaulted to the labels present on the pod template. // Label keys and values that must match in order to be controlled by this replica set. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors + // More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors Selector *LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` // Template is the object that describes the pod that will be created if // insufficient replicas are detected. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template Template v1.PodTemplateSpec `json:"template,omitempty" protobuf:"bytes,3,opt,name=template"` } // ReplicaSetStatus represents the current status of a ReplicaSet. type ReplicaSetStatus struct { // Replicas is the most recently oberved number of replicas. - // More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller + // More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller Replicas int32 `json:"replicas" protobuf:"varint,1,opt,name=replicas"` // The number of pods that have labels matching the labels of the pod template of the replicaset. @@ -912,14 +914,15 @@ type ReplicaSetStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,3,opt,name=observedGeneration"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // Pod Security Policy governs the ability to make requests that affect the Security Context // that will be applied to a pod and container. type PodSecurityPolicy struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // spec defines the policy enforced. @@ -1008,7 +1011,7 @@ type SELinuxStrategyOptions struct { // type is the strategy that will dictate the allowable labels that may be set. Rule SELinuxStrategy `json:"rule" protobuf:"bytes,1,opt,name=rule,casttype=SELinuxStrategy"` // seLinuxOptions required to run as; required for MustRunAs - // More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md#security-context + // More info: http://releases.k8s.io/HEAD/docs/design/security_context.md#security-context SELinuxOptions *v1.SELinuxOptions `json:"seLinuxOptions,omitempty" protobuf:"bytes,2,opt,name=seLinuxOptions"` } @@ -1096,7 +1099,7 @@ const ( type PodSecurityPolicyList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of schema objects. @@ -1106,7 +1109,7 @@ type PodSecurityPolicyList struct { type NetworkPolicy struct { unversioned.TypeMeta `json:",inline"` // Standard object's metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior for this NetworkPolicy. @@ -1187,9 +1190,42 @@ type NetworkPolicyPeer struct { type NetworkPolicyList struct { unversioned.TypeMeta `json:",inline"` // Standard list metadata. - // More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Items is a list of schema objects. Items []NetworkPolicy `json:"items" protobuf:"bytes,2,rep,name=items"` } + +// +genclient=true +// +nonNamespaced=true + +// StorageClass describes the parameters for a class of storage for +// which PersistentVolumes can be dynamically provisioned. +// +// StorageClasses are non-namespaced; the name of the storage class +// according to etcd is in ObjectMeta.Name. +type StorageClass struct { + unversioned.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Provisioner indicates the type of the provisioner. + Provisioner string `json:"provisioner" protobuf:"bytes,2,opt,name=provisioner"` + + // Parameters holds the parameters for the provisioner that should + // create volumes of this storage class. + Parameters map[string]string `json:"parameters,omitempty" protobuf:"bytes,3,rep,name=parameters"` +} + +// StorageClassList is a collection of storage classes. +type StorageClassList struct { + unversioned.TypeMeta `json:",inline"` + // Standard list metadata + // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata + unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` + + // Items is the list of StorageClasses + Items []StorageClass `json:"items" protobuf:"bytes,2,rep,name=items"` +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go index 1864a965828d..ea99629c3c93 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -65,9 +65,9 @@ func (CustomMetricTarget) SwaggerDoc() map[string]string { var map_DaemonSet = map[string]string{ "": "DaemonSet represents the configuration of a daemon set.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the desired behavior of this daemon set. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is the current status of this daemon set. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the desired behavior of this daemon set. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is the current status of this daemon set. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (DaemonSet) SwaggerDoc() map[string]string { @@ -76,7 +76,7 @@ func (DaemonSet) SwaggerDoc() map[string]string { var map_DaemonSetList = map[string]string{ "": "DaemonSetList is a collection of daemon sets.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is a list of daemon sets.", } @@ -86,8 +86,8 @@ func (DaemonSetList) SwaggerDoc() map[string]string { var map_DaemonSetSpec = map[string]string{ "": "DaemonSetSpec is the specification of a daemon set.", - "selector": "Selector is a label query over pods that are managed by the daemon set. Must match in order to be controlled. If empty, defaulted to labels on Pod template. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "template": "Template is the object that describes the pod that will be created. The DaemonSet will create exactly one copy of this pod on every node that matches the template's node selector (or on every node if no node selector is specified). More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template", + "selector": "Selector is a label query over pods that are managed by the daemon set. Must match in order to be controlled. If empty, defaulted to labels on Pod template. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "template": "Template is the object that describes the pod that will be created. The DaemonSet will create exactly one copy of this pod on every node that matches the template's node selector (or on every node if no node selector is specified). More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template", } func (DaemonSetSpec) SwaggerDoc() map[string]string { @@ -96,9 +96,9 @@ func (DaemonSetSpec) SwaggerDoc() map[string]string { var map_DaemonSetStatus = map[string]string{ "": "DaemonSetStatus represents the current status of a daemon set.", - "currentNumberScheduled": "CurrentNumberScheduled is the number of nodes that are running at least 1 daemon pod and are supposed to run the daemon pod. More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md", - "numberMisscheduled": "NumberMisscheduled is the number of nodes that are running the daemon pod, but are not supposed to run the daemon pod. More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md", - "desiredNumberScheduled": "DesiredNumberScheduled is the total number of nodes that should be running the daemon pod (including nodes correctly running the daemon pod). More info: http://releases.k8s.io/release-1.3/docs/admin/daemons.md", + "currentNumberScheduled": "CurrentNumberScheduled is the number of nodes that are running at least 1 daemon pod and are supposed to run the daemon pod. More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md", + "numberMisscheduled": "NumberMisscheduled is the number of nodes that are running the daemon pod, but are not supposed to run the daemon pod. More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md", + "desiredNumberScheduled": "DesiredNumberScheduled is the total number of nodes that should be running the daemon pod (including nodes correctly running the daemon pod). More info: http://releases.k8s.io/HEAD/docs/admin/daemons.md", } func (DaemonSetStatus) SwaggerDoc() map[string]string { @@ -217,8 +217,8 @@ func (HTTPIngressRuleValue) SwaggerDoc() map[string]string { var map_HorizontalPodAutoscaler = map[string]string{ "": "configuration of a horizontal pod autoscaler.", - "metadata": "Standard object metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status.", + "metadata": "Standard object metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "behaviour of autoscaler. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.", "status": "current information about the autoscaler.", } @@ -283,9 +283,9 @@ func (IDRange) SwaggerDoc() map[string]string { var map_Ingress = map[string]string{ "": "Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec is the desired state of the Ingress. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is the current state of the Ingress. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec is the desired state of the Ingress. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is the current state of the Ingress. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Ingress) SwaggerDoc() map[string]string { @@ -304,7 +304,7 @@ func (IngressBackend) SwaggerDoc() map[string]string { var map_IngressList = map[string]string{ "": "IngressList is a collection of Ingress.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Ingress.", } @@ -361,9 +361,9 @@ func (IngressTLS) SwaggerDoc() map[string]string { var map_Job = map[string]string{ "": "Job represents the configuration of a single job.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec is a structure defining the expected behavior of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is a structure describing current status of a job. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (Job) SwaggerDoc() map[string]string { @@ -386,7 +386,7 @@ func (JobCondition) SwaggerDoc() map[string]string { var map_JobList = map[string]string{ "": "JobList is a collection of jobs.", - "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of Job.", } @@ -396,12 +396,12 @@ func (JobList) SwaggerDoc() map[string]string { var map_JobSpec = map[string]string{ "": "JobSpec describes how the job execution will look like.", - "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", - "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "parallelism": "Parallelism specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", + "completions": "Completions specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "activeDeadlineSeconds": "Optional duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer", - "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "autoSelector": "AutoSelector controls generation of pod labels and pod selectors. It was not present in the original extensions/v1beta1 Job definition, but exists to allow conversion from batch/v1 Jobs, where it corresponds to, but has the opposite meaning as, ManualSelector. More info: http://releases.k8s.io/release-1.3/docs/design/selector-generation.md", - "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "selector": "Selector is a label query over pods that should match the pod count. Normally, the system sets this field for you. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "autoSelector": "AutoSelector controls generation of pod labels and pod selectors. It was not present in the original extensions/v1beta1 Job definition, but exists to allow conversion from batch/v1 Jobs, where it corresponds to, but has the opposite meaning as, ManualSelector. More info: http://releases.k8s.io/HEAD/docs/design/selector-generation.md", + "template": "Template is the object that describes the pod that will be created when executing a job. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", } func (JobSpec) SwaggerDoc() map[string]string { @@ -410,7 +410,7 @@ func (JobSpec) SwaggerDoc() map[string]string { var map_JobStatus = map[string]string{ "": "JobStatus represents the current state of a Job.", - "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/release-1.3/docs/user-guide/jobs.md", + "conditions": "Conditions represent the latest available observations of an object's current state. More info: http://releases.k8s.io/HEAD/docs/user-guide/jobs.md", "startTime": "StartTime represents time when the job was acknowledged by the Job Manager. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "completionTime": "CompletionTime represents time when the job was completed. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC.", "active": "Active is the number of actively running pods.", @@ -457,7 +457,7 @@ func (ListOptions) SwaggerDoc() map[string]string { } var map_NetworkPolicy = map[string]string{ - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "spec": "Specification of the desired behavior for this NetworkPolicy.", } @@ -477,7 +477,7 @@ func (NetworkPolicyIngressRule) SwaggerDoc() map[string]string { var map_NetworkPolicyList = map[string]string{ "": "Network Policy List is a list of NetworkPolicy objects.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is a list of schema objects.", } @@ -514,7 +514,7 @@ func (NetworkPolicySpec) SwaggerDoc() map[string]string { var map_PodSecurityPolicy = map[string]string{ "": "Pod Security Policy governs the ability to make requests that affect the Security Context that will be applied to a pod and container.", - "metadata": "Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "spec": "spec defines the policy enforced.", } @@ -524,7 +524,7 @@ func (PodSecurityPolicy) SwaggerDoc() map[string]string { var map_PodSecurityPolicyList = map[string]string{ "": "Pod Security Policy List is a list of PodSecurityPolicy objects.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is a list of schema objects.", } @@ -556,9 +556,9 @@ func (PodSecurityPolicySpec) SwaggerDoc() map[string]string { var map_ReplicaSet = map[string]string{ "": "ReplicaSet represents the configuration of a ReplicaSet.", - "metadata": "If the Labels of a ReplicaSet are empty, they are defaulted to be the same as the Pod(s) that the ReplicaSet manages. Standard object's metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", - "spec": "Spec defines the specification of the desired behavior of the ReplicaSet. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", - "status": "Status is the most recently observed status of the ReplicaSet. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status", + "metadata": "If the Labels of a ReplicaSet are empty, they are defaulted to be the same as the Pod(s) that the ReplicaSet manages. Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "spec": "Spec defines the specification of the desired behavior of the ReplicaSet. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", + "status": "Status is the most recently observed status of the ReplicaSet. This data may be out of date by some window of time. Populated by the system. Read-only. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status", } func (ReplicaSet) SwaggerDoc() map[string]string { @@ -567,8 +567,8 @@ func (ReplicaSet) SwaggerDoc() map[string]string { var map_ReplicaSetList = map[string]string{ "": "ReplicaSetList is a collection of ReplicaSets.", - "metadata": "Standard list metadata. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "items": "List of ReplicaSets. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md", + "metadata": "Standard list metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "items": "List of ReplicaSets. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md", } func (ReplicaSetList) SwaggerDoc() map[string]string { @@ -577,9 +577,9 @@ func (ReplicaSetList) SwaggerDoc() map[string]string { var map_ReplicaSetSpec = map[string]string{ "": "ReplicaSetSpec is the specification of a ReplicaSet.", - "replicas": "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller", - "selector": "Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "template": "Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#pod-template", + "replicas": "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", + "selector": "Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "template": "Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#pod-template", } func (ReplicaSetSpec) SwaggerDoc() map[string]string { @@ -588,7 +588,7 @@ func (ReplicaSetSpec) SwaggerDoc() map[string]string { var map_ReplicaSetStatus = map[string]string{ "": "ReplicaSetStatus represents the current status of a ReplicaSet.", - "replicas": "Replicas is the most recently oberved number of replicas. More info: http://releases.k8s.io/release-1.3/docs/user-guide/replication-controller.md#what-is-a-replication-controller", + "replicas": "Replicas is the most recently oberved number of replicas. More info: http://releases.k8s.io/HEAD/docs/user-guide/replication-controller.md#what-is-a-replication-controller", "fullyLabeledReplicas": "The number of pods that have labels matching the labels of the pod template of the replicaset.", "observedGeneration": "ObservedGeneration reflects the generation of the most recently observed ReplicaSet.", } @@ -636,7 +636,7 @@ func (RunAsUserStrategyOptions) SwaggerDoc() map[string]string { var map_SELinuxStrategyOptions = map[string]string{ "": "SELinux Strategy Options defines the strategy type and any options used to create the strategy.", "rule": "type is the strategy that will dictate the allowable labels that may be set.", - "seLinuxOptions": "seLinuxOptions required to run as; required for MustRunAs More info: http://releases.k8s.io/release-1.3/docs/design/security_context.md#security-context", + "seLinuxOptions": "seLinuxOptions required to run as; required for MustRunAs More info: http://releases.k8s.io/HEAD/docs/design/security_context.md#security-context", } func (SELinuxStrategyOptions) SwaggerDoc() map[string]string { @@ -645,9 +645,9 @@ func (SELinuxStrategyOptions) SwaggerDoc() map[string]string { var map_Scale = map[string]string{ "": "represents a scaling request for a resource.", - "metadata": "Standard object metadata; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata.", - "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status.", - "status": "current status of the scale. More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#spec-and-status. Read-only.", + "metadata": "Standard object metadata; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata.", + "spec": "defines the behavior of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status.", + "status": "current status of the scale. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#spec-and-status. Read-only.", } func (Scale) SwaggerDoc() map[string]string { @@ -666,18 +666,39 @@ func (ScaleSpec) SwaggerDoc() map[string]string { var map_ScaleStatus = map[string]string{ "": "represents the current status of a scale subresource.", "replicas": "actual number of observed instances of the scaled object.", - "selector": "label query over pods that should match the replicas count. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", - "targetSelector": "label selector for pods that should match the replicas count. This is a serializated version of both map-based and more expressive set-based selectors. This is done to avoid introspection in the clients. The string will be in the same format as the query-param syntax. If the target type only supports map-based selectors, both this field and map-based selector field are populated. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors", + "selector": "label query over pods that should match the replicas count. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", + "targetSelector": "label selector for pods that should match the replicas count. This is a serializated version of both map-based and more expressive set-based selectors. This is done to avoid introspection in the clients. The string will be in the same format as the query-param syntax. If the target type only supports map-based selectors, both this field and map-based selector field are populated. More info: http://releases.k8s.io/HEAD/docs/user-guide/labels.md#label-selectors", } func (ScaleStatus) SwaggerDoc() map[string]string { return map_ScaleStatus } +var map_StorageClass = map[string]string{ + "": "StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.\n\nStorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.", + "metadata": "Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "provisioner": "Provisioner indicates the type of the provisioner.", + "parameters": "Parameters holds the parameters for the provisioner that should create volumes of this storage class.", +} + +func (StorageClass) SwaggerDoc() map[string]string { + return map_StorageClass +} + +var map_StorageClassList = map[string]string{ + "": "StorageClassList is a collection of storage classes.", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", + "items": "Items is the list of StorageClasses", +} + +func (StorageClassList) SwaggerDoc() map[string]string { + return map_StorageClassList +} + var map_SubresourceReference = map[string]string{ "": "SubresourceReference contains enough information to let you inspect or modify the referred subresource.", - "kind": "Kind of the referent; More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#types-kinds", - "name": "Name of the referent; More info: http://releases.k8s.io/release-1.3/docs/user-guide/identifiers.md#names", + "kind": "Kind of the referent; More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds", + "name": "Name of the referent; More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names", "apiVersion": "API version of the referent", "subresource": "Subresource name of the referent", } @@ -719,7 +740,7 @@ func (ThirdPartyResourceData) SwaggerDoc() map[string]string { var map_ThirdPartyResourceDataList = map[string]string{ "": "ThirdPartyResrouceDataList is a list of ThirdPartyResourceData.", - "metadata": "Standard list metadata More info: http://releases.k8s.io/release-1.3/docs/devel/api-conventions.md#metadata", + "metadata": "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata", "items": "Items is the list of ThirdpartyResourceData.", } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.conversion.go similarity index 91% rename from vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.conversion.go index 445394f16a59..c29edf0973ba 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -62,6 +62,8 @@ func init() { Convert_extensions_DeploymentStatus_To_v1beta1_DeploymentStatus, Convert_v1beta1_DeploymentStrategy_To_extensions_DeploymentStrategy, Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy, + Convert_v1beta1_ExportOptions_To_api_ExportOptions, + Convert_api_ExportOptions_To_v1beta1_ExportOptions, Convert_v1beta1_FSGroupStrategyOptions_To_extensions_FSGroupStrategyOptions, Convert_extensions_FSGroupStrategyOptions_To_v1beta1_FSGroupStrategyOptions, Convert_v1beta1_HTTPIngressPath_To_extensions_HTTPIngressPath, @@ -110,6 +112,8 @@ func init() { Convert_unversioned_LabelSelector_To_v1beta1_LabelSelector, Convert_v1beta1_LabelSelectorRequirement_To_unversioned_LabelSelectorRequirement, Convert_unversioned_LabelSelectorRequirement_To_v1beta1_LabelSelectorRequirement, + Convert_v1beta1_ListOptions_To_api_ListOptions, + Convert_api_ListOptions_To_v1beta1_ListOptions, Convert_v1beta1_NetworkPolicy_To_extensions_NetworkPolicy, Convert_extensions_NetworkPolicy_To_v1beta1_NetworkPolicy, Convert_v1beta1_NetworkPolicyIngressRule_To_extensions_NetworkPolicyIngressRule, @@ -152,6 +156,10 @@ func init() { Convert_extensions_ScaleSpec_To_v1beta1_ScaleSpec, Convert_v1beta1_ScaleStatus_To_extensions_ScaleStatus, Convert_extensions_ScaleStatus_To_v1beta1_ScaleStatus, + Convert_v1beta1_StorageClass_To_extensions_StorageClass, + Convert_extensions_StorageClass_To_v1beta1_StorageClass, + Convert_v1beta1_StorageClassList_To_extensions_StorageClassList, + Convert_extensions_StorageClassList_To_v1beta1_StorageClassList, Convert_v1beta1_SupplementalGroupsStrategyOptions_To_extensions_SupplementalGroupsStrategyOptions, Convert_extensions_SupplementalGroupsStrategyOptions_To_v1beta1_SupplementalGroupsStrategyOptions, Convert_v1beta1_ThirdPartyResource_To_extensions_ThirdPartyResource, @@ -590,6 +598,74 @@ func Convert_extensions_DeploymentRollback_To_v1beta1_DeploymentRollback(in *ext return autoConvert_extensions_DeploymentRollback_To_v1beta1_DeploymentRollback(in, out, s) } +func autoConvert_v1beta1_DeploymentSpec_To_extensions_DeploymentSpec(in *DeploymentSpec, out *extensions.DeploymentSpec, s conversion.Scope) error { + if err := api.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := Convert_v1beta1_LabelSelector_To_unversioned_LabelSelector(*in, *out, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + if err := Convert_v1beta1_DeploymentStrategy_To_extensions_DeploymentStrategy(&in.Strategy, &out.Strategy, s); err != nil { + return err + } + out.MinReadySeconds = in.MinReadySeconds + out.RevisionHistoryLimit = in.RevisionHistoryLimit + out.Paused = in.Paused + if in.RollbackTo != nil { + in, out := &in.RollbackTo, &out.RollbackTo + *out = new(extensions.RollbackConfig) + if err := Convert_v1beta1_RollbackConfig_To_extensions_RollbackConfig(*in, *out, s); err != nil { + return err + } + } else { + out.RollbackTo = nil + } + return nil +} + +func autoConvert_extensions_DeploymentSpec_To_v1beta1_DeploymentSpec(in *extensions.DeploymentSpec, out *DeploymentSpec, s conversion.Scope) error { + if err := api.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := Convert_unversioned_LabelSelector_To_v1beta1_LabelSelector(*in, *out, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + if err := Convert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy(&in.Strategy, &out.Strategy, s); err != nil { + return err + } + out.MinReadySeconds = in.MinReadySeconds + out.RevisionHistoryLimit = in.RevisionHistoryLimit + out.Paused = in.Paused + if in.RollbackTo != nil { + in, out := &in.RollbackTo, &out.RollbackTo + *out = new(RollbackConfig) + if err := Convert_extensions_RollbackConfig_To_v1beta1_RollbackConfig(*in, *out, s); err != nil { + return err + } + } else { + out.RollbackTo = nil + } + return nil +} + func autoConvert_v1beta1_DeploymentStatus_To_extensions_DeploymentStatus(in *DeploymentStatus, out *extensions.DeploymentStatus, s conversion.Scope) error { out.ObservedGeneration = in.ObservedGeneration out.Replicas = in.Replicas @@ -644,6 +720,32 @@ func autoConvert_extensions_DeploymentStrategy_To_v1beta1_DeploymentStrategy(in return nil } +func autoConvert_v1beta1_ExportOptions_To_api_ExportOptions(in *ExportOptions, out *api.ExportOptions, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Export = in.Export + out.Exact = in.Exact + return nil +} + +func Convert_v1beta1_ExportOptions_To_api_ExportOptions(in *ExportOptions, out *api.ExportOptions, s conversion.Scope) error { + return autoConvert_v1beta1_ExportOptions_To_api_ExportOptions(in, out, s) +} + +func autoConvert_api_ExportOptions_To_v1beta1_ExportOptions(in *api.ExportOptions, out *ExportOptions, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + out.Export = in.Export + out.Exact = in.Exact + return nil +} + +func Convert_api_ExportOptions_To_v1beta1_ExportOptions(in *api.ExportOptions, out *ExportOptions, s conversion.Scope) error { + return autoConvert_api_ExportOptions_To_v1beta1_ExportOptions(in, out, s) +} + func autoConvert_v1beta1_FSGroupStrategyOptions_To_extensions_FSGroupStrategyOptions(in *FSGroupStrategyOptions, out *extensions.FSGroupStrategyOptions, s conversion.Scope) error { out.Rule = extensions.FSGroupStrategyType(in.Rule) if in.Ranges != nil { @@ -1440,6 +1542,46 @@ func Convert_unversioned_LabelSelectorRequirement_To_v1beta1_LabelSelectorRequir return autoConvert_unversioned_LabelSelectorRequirement_To_v1beta1_LabelSelectorRequirement(in, out, s) } +func autoConvert_v1beta1_ListOptions_To_api_ListOptions(in *ListOptions, out *api.ListOptions, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_string_To_labels_Selector(&in.LabelSelector, &out.LabelSelector, s); err != nil { + return err + } + if err := api.Convert_string_To_fields_Selector(&in.FieldSelector, &out.FieldSelector, s); err != nil { + return err + } + out.Watch = in.Watch + out.ResourceVersion = in.ResourceVersion + out.TimeoutSeconds = in.TimeoutSeconds + return nil +} + +func Convert_v1beta1_ListOptions_To_api_ListOptions(in *ListOptions, out *api.ListOptions, s conversion.Scope) error { + return autoConvert_v1beta1_ListOptions_To_api_ListOptions(in, out, s) +} + +func autoConvert_api_ListOptions_To_v1beta1_ListOptions(in *api.ListOptions, out *ListOptions, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_labels_Selector_To_string(&in.LabelSelector, &out.LabelSelector, s); err != nil { + return err + } + if err := api.Convert_fields_Selector_To_string(&in.FieldSelector, &out.FieldSelector, s); err != nil { + return err + } + out.Watch = in.Watch + out.ResourceVersion = in.ResourceVersion + out.TimeoutSeconds = in.TimeoutSeconds + return nil +} + +func Convert_api_ListOptions_To_v1beta1_ListOptions(in *api.ListOptions, out *ListOptions, s conversion.Scope) error { + return autoConvert_api_ListOptions_To_v1beta1_ListOptions(in, out, s) +} + func autoConvert_v1beta1_NetworkPolicy_To_extensions_NetworkPolicy(in *NetworkPolicy, out *extensions.NetworkPolicy, s conversion.Scope) error { SetDefaults_NetworkPolicy(in) if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { @@ -2038,6 +2180,44 @@ func Convert_extensions_ReplicaSetList_To_v1beta1_ReplicaSetList(in *extensions. return autoConvert_extensions_ReplicaSetList_To_v1beta1_ReplicaSetList(in, out, s) } +func autoConvert_v1beta1_ReplicaSetSpec_To_extensions_ReplicaSetSpec(in *ReplicaSetSpec, out *extensions.ReplicaSetSpec, s conversion.Scope) error { + if err := api.Convert_Pointer_int32_To_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := Convert_v1beta1_LabelSelector_To_unversioned_LabelSelector(*in, *out, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.Convert_v1_PodTemplateSpec_To_api_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + +func autoConvert_extensions_ReplicaSetSpec_To_v1beta1_ReplicaSetSpec(in *extensions.ReplicaSetSpec, out *ReplicaSetSpec, s conversion.Scope) error { + if err := api.Convert_int32_To_Pointer_int32(&in.Replicas, &out.Replicas, s); err != nil { + return err + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := Convert_unversioned_LabelSelector_To_v1beta1_LabelSelector(*in, *out, s); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.Convert_api_PodTemplateSpec_To_v1_PodTemplateSpec(&in.Template, &out.Template, s); err != nil { + return err + } + return nil +} + func autoConvert_v1beta1_ReplicaSetStatus_To_extensions_ReplicaSetStatus(in *ReplicaSetStatus, out *extensions.ReplicaSetStatus, s conversion.Scope) error { out.Replicas = in.Replicas out.FullyLabeledReplicas = in.FullyLabeledReplicas @@ -2238,6 +2418,90 @@ func Convert_extensions_ScaleSpec_To_v1beta1_ScaleSpec(in *extensions.ScaleSpec, return autoConvert_extensions_ScaleSpec_To_v1beta1_ScaleSpec(in, out, s) } +func autoConvert_v1beta1_StorageClass_To_extensions_StorageClass(in *StorageClass, out *extensions.StorageClass, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil { + return err + } + out.Provisioner = in.Provisioner + out.Parameters = in.Parameters + return nil +} + +func Convert_v1beta1_StorageClass_To_extensions_StorageClass(in *StorageClass, out *extensions.StorageClass, s conversion.Scope) error { + return autoConvert_v1beta1_StorageClass_To_extensions_StorageClass(in, out, s) +} + +func autoConvert_extensions_StorageClass_To_v1beta1_StorageClass(in *extensions.StorageClass, out *StorageClass, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + // TODO: Inefficient conversion - can we improve it? + if err := s.Convert(&in.ObjectMeta, &out.ObjectMeta, 0); err != nil { + return err + } + out.Provisioner = in.Provisioner + out.Parameters = in.Parameters + return nil +} + +func Convert_extensions_StorageClass_To_v1beta1_StorageClass(in *extensions.StorageClass, out *StorageClass, s conversion.Scope) error { + return autoConvert_extensions_StorageClass_To_v1beta1_StorageClass(in, out, s) +} + +func autoConvert_v1beta1_StorageClassList_To_extensions_StorageClassList(in *StorageClassList, out *extensions.StorageClassList, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_unversioned_ListMeta_To_unversioned_ListMeta(&in.ListMeta, &out.ListMeta, s); err != nil { + return err + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]extensions.StorageClass, len(*in)) + for i := range *in { + if err := Convert_v1beta1_StorageClass_To_extensions_StorageClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_v1beta1_StorageClassList_To_extensions_StorageClassList(in *StorageClassList, out *extensions.StorageClassList, s conversion.Scope) error { + return autoConvert_v1beta1_StorageClassList_To_extensions_StorageClassList(in, out, s) +} + +func autoConvert_extensions_StorageClassList_To_v1beta1_StorageClassList(in *extensions.StorageClassList, out *StorageClassList, s conversion.Scope) error { + if err := api.Convert_unversioned_TypeMeta_To_unversioned_TypeMeta(&in.TypeMeta, &out.TypeMeta, s); err != nil { + return err + } + if err := api.Convert_unversioned_ListMeta_To_unversioned_ListMeta(&in.ListMeta, &out.ListMeta, s); err != nil { + return err + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]StorageClass, len(*in)) + for i := range *in { + if err := Convert_extensions_StorageClass_To_v1beta1_StorageClass(&(*in)[i], &(*out)[i], s); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil +} + +func Convert_extensions_StorageClassList_To_v1beta1_StorageClassList(in *extensions.StorageClassList, out *StorageClassList, s conversion.Scope) error { + return autoConvert_extensions_StorageClassList_To_v1beta1_StorageClassList(in, out, s) +} + func autoConvert_v1beta1_SupplementalGroupsStrategyOptions_To_extensions_SupplementalGroupsStrategyOptions(in *SupplementalGroupsStrategyOptions, out *extensions.SupplementalGroupsStrategyOptions, s conversion.Scope) error { out.Rule = extensions.SupplementalGroupsStrategyType(in.Rule) if in.Ranges != nil { diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..9c5332d245d0 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,1492 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1beta1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + intstr "k8s.io/kubernetes/pkg/util/intstr" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_APIVersion, InType: reflect.TypeOf(func() *APIVersion { var x *APIVersion; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CPUTargetUtilization, InType: reflect.TypeOf(func() *CPUTargetUtilization { var x *CPUTargetUtilization; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricCurrentStatus, InType: reflect.TypeOf(func() *CustomMetricCurrentStatus { var x *CustomMetricCurrentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricCurrentStatusList, InType: reflect.TypeOf(func() *CustomMetricCurrentStatusList { var x *CustomMetricCurrentStatusList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricTarget, InType: reflect.TypeOf(func() *CustomMetricTarget { var x *CustomMetricTarget; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_CustomMetricTargetList, InType: reflect.TypeOf(func() *CustomMetricTargetList { var x *CustomMetricTargetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSet, InType: reflect.TypeOf(func() *DaemonSet { var x *DaemonSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetList, InType: reflect.TypeOf(func() *DaemonSetList { var x *DaemonSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetSpec, InType: reflect.TypeOf(func() *DaemonSetSpec { var x *DaemonSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DaemonSetStatus, InType: reflect.TypeOf(func() *DaemonSetStatus { var x *DaemonSetStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Deployment, InType: reflect.TypeOf(func() *Deployment { var x *Deployment; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentList, InType: reflect.TypeOf(func() *DeploymentList { var x *DeploymentList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentRollback, InType: reflect.TypeOf(func() *DeploymentRollback { var x *DeploymentRollback; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentSpec, InType: reflect.TypeOf(func() *DeploymentSpec { var x *DeploymentSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentStatus, InType: reflect.TypeOf(func() *DeploymentStatus { var x *DeploymentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_DeploymentStrategy, InType: reflect.TypeOf(func() *DeploymentStrategy { var x *DeploymentStrategy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ExportOptions, InType: reflect.TypeOf(func() *ExportOptions { var x *ExportOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_FSGroupStrategyOptions, InType: reflect.TypeOf(func() *FSGroupStrategyOptions { var x *FSGroupStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HTTPIngressPath, InType: reflect.TypeOf(func() *HTTPIngressPath { var x *HTTPIngressPath; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HTTPIngressRuleValue, InType: reflect.TypeOf(func() *HTTPIngressRuleValue { var x *HTTPIngressRuleValue; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscaler, InType: reflect.TypeOf(func() *HorizontalPodAutoscaler { var x *HorizontalPodAutoscaler; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerList, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerList { var x *HorizontalPodAutoscalerList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerSpec, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerSpec { var x *HorizontalPodAutoscalerSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HorizontalPodAutoscalerStatus, InType: reflect.TypeOf(func() *HorizontalPodAutoscalerStatus { var x *HorizontalPodAutoscalerStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_HostPortRange, InType: reflect.TypeOf(func() *HostPortRange { var x *HostPortRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IDRange, InType: reflect.TypeOf(func() *IDRange { var x *IDRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Ingress, InType: reflect.TypeOf(func() *Ingress { var x *Ingress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressBackend, InType: reflect.TypeOf(func() *IngressBackend { var x *IngressBackend; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressList, InType: reflect.TypeOf(func() *IngressList { var x *IngressList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressRule, InType: reflect.TypeOf(func() *IngressRule { var x *IngressRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressRuleValue, InType: reflect.TypeOf(func() *IngressRuleValue { var x *IngressRuleValue; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressSpec, InType: reflect.TypeOf(func() *IngressSpec { var x *IngressSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressStatus, InType: reflect.TypeOf(func() *IngressStatus { var x *IngressStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_IngressTLS, InType: reflect.TypeOf(func() *IngressTLS { var x *IngressTLS; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Job, InType: reflect.TypeOf(func() *Job { var x *Job; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_JobCondition, InType: reflect.TypeOf(func() *JobCondition { var x *JobCondition; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_JobList, InType: reflect.TypeOf(func() *JobList { var x *JobList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_JobSpec, InType: reflect.TypeOf(func() *JobSpec { var x *JobSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_JobStatus, InType: reflect.TypeOf(func() *JobStatus { var x *JobStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_LabelSelector, InType: reflect.TypeOf(func() *LabelSelector { var x *LabelSelector; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_LabelSelectorRequirement, InType: reflect.TypeOf(func() *LabelSelectorRequirement { var x *LabelSelectorRequirement; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ListOptions, InType: reflect.TypeOf(func() *ListOptions { var x *ListOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicy, InType: reflect.TypeOf(func() *NetworkPolicy { var x *NetworkPolicy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyIngressRule, InType: reflect.TypeOf(func() *NetworkPolicyIngressRule { var x *NetworkPolicyIngressRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyList, InType: reflect.TypeOf(func() *NetworkPolicyList { var x *NetworkPolicyList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyPeer, InType: reflect.TypeOf(func() *NetworkPolicyPeer { var x *NetworkPolicyPeer; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicyPort, InType: reflect.TypeOf(func() *NetworkPolicyPort { var x *NetworkPolicyPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_NetworkPolicySpec, InType: reflect.TypeOf(func() *NetworkPolicySpec { var x *NetworkPolicySpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicy, InType: reflect.TypeOf(func() *PodSecurityPolicy { var x *PodSecurityPolicy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicyList, InType: reflect.TypeOf(func() *PodSecurityPolicyList { var x *PodSecurityPolicyList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_PodSecurityPolicySpec, InType: reflect.TypeOf(func() *PodSecurityPolicySpec { var x *PodSecurityPolicySpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSet, InType: reflect.TypeOf(func() *ReplicaSet { var x *ReplicaSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetList, InType: reflect.TypeOf(func() *ReplicaSetList { var x *ReplicaSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetSpec, InType: reflect.TypeOf(func() *ReplicaSetSpec { var x *ReplicaSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicaSetStatus, InType: reflect.TypeOf(func() *ReplicaSetStatus { var x *ReplicaSetStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ReplicationControllerDummy, InType: reflect.TypeOf(func() *ReplicationControllerDummy { var x *ReplicationControllerDummy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RollbackConfig, InType: reflect.TypeOf(func() *RollbackConfig { var x *RollbackConfig; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RollingUpdateDeployment, InType: reflect.TypeOf(func() *RollingUpdateDeployment { var x *RollingUpdateDeployment; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_RunAsUserStrategyOptions, InType: reflect.TypeOf(func() *RunAsUserStrategyOptions { var x *RunAsUserStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SELinuxStrategyOptions, InType: reflect.TypeOf(func() *SELinuxStrategyOptions { var x *SELinuxStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_Scale, InType: reflect.TypeOf(func() *Scale { var x *Scale; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ScaleSpec, InType: reflect.TypeOf(func() *ScaleSpec { var x *ScaleSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ScaleStatus, InType: reflect.TypeOf(func() *ScaleStatus { var x *ScaleStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_StorageClass, InType: reflect.TypeOf(func() *StorageClass { var x *StorageClass; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_StorageClassList, InType: reflect.TypeOf(func() *StorageClassList { var x *StorageClassList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SubresourceReference, InType: reflect.TypeOf(func() *SubresourceReference { var x *SubresourceReference; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_SupplementalGroupsStrategyOptions, InType: reflect.TypeOf(func() *SupplementalGroupsStrategyOptions { var x *SupplementalGroupsStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResource, InType: reflect.TypeOf(func() *ThirdPartyResource { var x *ThirdPartyResource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceData, InType: reflect.TypeOf(func() *ThirdPartyResourceData { var x *ThirdPartyResourceData; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceDataList, InType: reflect.TypeOf(func() *ThirdPartyResourceDataList { var x *ThirdPartyResourceDataList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1beta1_ThirdPartyResourceList, InType: reflect.TypeOf(func() *ThirdPartyResourceList { var x *ThirdPartyResourceList; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1beta1_APIVersion(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIVersion) + out := out.(*APIVersion) + out.Name = in.Name + return nil + } +} + +func DeepCopy_v1beta1_CPUTargetUtilization(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CPUTargetUtilization) + out := out.(*CPUTargetUtilization) + out.TargetPercentage = in.TargetPercentage + return nil + } +} + +func DeepCopy_v1beta1_CustomMetricCurrentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricCurrentStatus) + out := out.(*CustomMetricCurrentStatus) + out.Name = in.Name + out.CurrentValue = in.CurrentValue.DeepCopy() + return nil + } +} + +func DeepCopy_v1beta1_CustomMetricCurrentStatusList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricCurrentStatusList) + out := out.(*CustomMetricCurrentStatusList) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CustomMetricCurrentStatus, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_CustomMetricCurrentStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_CustomMetricTarget(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricTarget) + out := out.(*CustomMetricTarget) + out.Name = in.Name + out.TargetValue = in.TargetValue.DeepCopy() + return nil + } +} + +func DeepCopy_v1beta1_CustomMetricTargetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricTargetList) + out := out.(*CustomMetricTargetList) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CustomMetricTarget, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_CustomMetricTarget(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_DaemonSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSet) + out := out.(*DaemonSet) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_DaemonSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_DaemonSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetList) + out := out.(*DaemonSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DaemonSet, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_DaemonSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_DaemonSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetSpec) + out := out.(*DaemonSetSpec) + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_DaemonSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetStatus) + out := out.(*DaemonSetStatus) + out.CurrentNumberScheduled = in.CurrentNumberScheduled + out.NumberMisscheduled = in.NumberMisscheduled + out.DesiredNumberScheduled = in.DesiredNumberScheduled + return nil + } +} + +func DeepCopy_v1beta1_Deployment(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Deployment) + out := out.(*Deployment) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_DeploymentSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_DeploymentList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentList) + out := out.(*DeploymentList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Deployment, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_Deployment(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_DeploymentRollback(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentRollback) + out := out.(*DeploymentRollback) + out.TypeMeta = in.TypeMeta + out.Name = in.Name + if in.UpdatedAnnotations != nil { + in, out := &in.UpdatedAnnotations, &out.UpdatedAnnotations + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.UpdatedAnnotations = nil + } + out.RollbackTo = in.RollbackTo + return nil + } +} + +func DeepCopy_v1beta1_DeploymentSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentSpec) + out := out.(*DeploymentSpec) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } else { + out.Replicas = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_DeploymentStrategy(&in.Strategy, &out.Strategy, c); err != nil { + return err + } + out.MinReadySeconds = in.MinReadySeconds + if in.RevisionHistoryLimit != nil { + in, out := &in.RevisionHistoryLimit, &out.RevisionHistoryLimit + *out = new(int32) + **out = **in + } else { + out.RevisionHistoryLimit = nil + } + out.Paused = in.Paused + if in.RollbackTo != nil { + in, out := &in.RollbackTo, &out.RollbackTo + *out = new(RollbackConfig) + **out = **in + } else { + out.RollbackTo = nil + } + return nil + } +} + +func DeepCopy_v1beta1_DeploymentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentStatus) + out := out.(*DeploymentStatus) + out.ObservedGeneration = in.ObservedGeneration + out.Replicas = in.Replicas + out.UpdatedReplicas = in.UpdatedReplicas + out.AvailableReplicas = in.AvailableReplicas + out.UnavailableReplicas = in.UnavailableReplicas + return nil + } +} + +func DeepCopy_v1beta1_DeploymentStrategy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentStrategy) + out := out.(*DeploymentStrategy) + out.Type = in.Type + if in.RollingUpdate != nil { + in, out := &in.RollingUpdate, &out.RollingUpdate + *out = new(RollingUpdateDeployment) + if err := DeepCopy_v1beta1_RollingUpdateDeployment(*in, *out, c); err != nil { + return err + } + } else { + out.RollingUpdate = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ExportOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ExportOptions) + out := out.(*ExportOptions) + out.TypeMeta = in.TypeMeta + out.Export = in.Export + out.Exact = in.Exact + return nil + } +} + +func DeepCopy_v1beta1_FSGroupStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FSGroupStrategyOptions) + out := out.(*FSGroupStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_v1beta1_HTTPIngressPath(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPIngressPath) + out := out.(*HTTPIngressPath) + out.Path = in.Path + out.Backend = in.Backend + return nil + } +} + +func DeepCopy_v1beta1_HTTPIngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPIngressRuleValue) + out := out.(*HTTPIngressRuleValue) + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]HTTPIngressPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Paths = nil + } + return nil + } +} + +func DeepCopy_v1beta1_HorizontalPodAutoscaler(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscaler) + out := out.(*HorizontalPodAutoscaler) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_HorizontalPodAutoscalerList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerList) + out := out.(*HorizontalPodAutoscalerList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]HorizontalPodAutoscaler, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_HorizontalPodAutoscalerSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerSpec) + out := out.(*HorizontalPodAutoscalerSpec) + out.ScaleRef = in.ScaleRef + if in.MinReplicas != nil { + in, out := &in.MinReplicas, &out.MinReplicas + *out = new(int32) + **out = **in + } else { + out.MinReplicas = nil + } + out.MaxReplicas = in.MaxReplicas + if in.CPUUtilization != nil { + in, out := &in.CPUUtilization, &out.CPUUtilization + *out = new(CPUTargetUtilization) + **out = **in + } else { + out.CPUUtilization = nil + } + return nil + } +} + +func DeepCopy_v1beta1_HorizontalPodAutoscalerStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HorizontalPodAutoscalerStatus) + out := out.(*HorizontalPodAutoscalerStatus) + if in.ObservedGeneration != nil { + in, out := &in.ObservedGeneration, &out.ObservedGeneration + *out = new(int64) + **out = **in + } else { + out.ObservedGeneration = nil + } + if in.LastScaleTime != nil { + in, out := &in.LastScaleTime, &out.LastScaleTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.LastScaleTime = nil + } + out.CurrentReplicas = in.CurrentReplicas + out.DesiredReplicas = in.DesiredReplicas + if in.CurrentCPUUtilizationPercentage != nil { + in, out := &in.CurrentCPUUtilizationPercentage, &out.CurrentCPUUtilizationPercentage + *out = new(int32) + **out = **in + } else { + out.CurrentCPUUtilizationPercentage = nil + } + return nil + } +} + +func DeepCopy_v1beta1_HostPortRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HostPortRange) + out := out.(*HostPortRange) + out.Min = in.Min + out.Max = in.Max + return nil + } +} + +func DeepCopy_v1beta1_IDRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IDRange) + out := out.(*IDRange) + out.Min = in.Min + out.Max = in.Max + return nil + } +} + +func DeepCopy_v1beta1_Ingress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Ingress) + out := out.(*Ingress) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_IngressSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_IngressStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_IngressBackend(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressBackend) + out := out.(*IngressBackend) + out.ServiceName = in.ServiceName + out.ServicePort = in.ServicePort + return nil + } +} + +func DeepCopy_v1beta1_IngressList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressList) + out := out.(*IngressList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Ingress, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_Ingress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_IngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressRule) + out := out.(*IngressRule) + out.Host = in.Host + if err := DeepCopy_v1beta1_IngressRuleValue(&in.IngressRuleValue, &out.IngressRuleValue, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_IngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressRuleValue) + out := out.(*IngressRuleValue) + if in.HTTP != nil { + in, out := &in.HTTP, &out.HTTP + *out = new(HTTPIngressRuleValue) + if err := DeepCopy_v1beta1_HTTPIngressRuleValue(*in, *out, c); err != nil { + return err + } + } else { + out.HTTP = nil + } + return nil + } +} + +func DeepCopy_v1beta1_IngressSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressSpec) + out := out.(*IngressSpec) + if in.Backend != nil { + in, out := &in.Backend, &out.Backend + *out = new(IngressBackend) + **out = **in + } else { + out.Backend = nil + } + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = make([]IngressTLS, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_IngressTLS(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.TLS = nil + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]IngressRule, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_IngressRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_v1beta1_IngressStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressStatus) + out := out.(*IngressStatus) + if err := v1.DeepCopy_v1_LoadBalancerStatus(&in.LoadBalancer, &out.LoadBalancer, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_IngressTLS(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressTLS) + out := out.(*IngressTLS) + if in.Hosts != nil { + in, out := &in.Hosts, &out.Hosts + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Hosts = nil + } + out.SecretName = in.SecretName + return nil + } +} + +func DeepCopy_v1beta1_Job(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Job) + out := out.(*Job) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_JobSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_JobStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_JobCondition(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobCondition) + out := out.(*JobCondition) + out.Type = in.Type + out.Status = in.Status + out.LastProbeTime = in.LastProbeTime.DeepCopy() + out.LastTransitionTime = in.LastTransitionTime.DeepCopy() + out.Reason = in.Reason + out.Message = in.Message + return nil + } +} + +func DeepCopy_v1beta1_JobList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobList) + out := out.(*JobList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Job, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_Job(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_JobSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobSpec) + out := out.(*JobSpec) + if in.Parallelism != nil { + in, out := &in.Parallelism, &out.Parallelism + *out = new(int32) + **out = **in + } else { + out.Parallelism = nil + } + if in.Completions != nil { + in, out := &in.Completions, &out.Completions + *out = new(int32) + **out = **in + } else { + out.Completions = nil + } + if in.ActiveDeadlineSeconds != nil { + in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds + *out = new(int64) + **out = **in + } else { + out.ActiveDeadlineSeconds = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if in.AutoSelector != nil { + in, out := &in.AutoSelector, &out.AutoSelector + *out = new(bool) + **out = **in + } else { + out.AutoSelector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_JobStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*JobStatus) + out := out.(*JobStatus) + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]JobCondition, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_JobCondition(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Conditions = nil + } + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.StartTime = nil + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = new(unversioned.Time) + **out = (*in).DeepCopy() + } else { + out.CompletionTime = nil + } + out.Active = in.Active + out.Succeeded = in.Succeeded + out.Failed = in.Failed + return nil + } +} + +func DeepCopy_v1beta1_LabelSelector(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelector) + out := out.(*LabelSelector) + if in.MatchLabels != nil { + in, out := &in.MatchLabels, &out.MatchLabels + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.MatchLabels = nil + } + if in.MatchExpressions != nil { + in, out := &in.MatchExpressions, &out.MatchExpressions + *out = make([]LabelSelectorRequirement, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_LabelSelectorRequirement(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.MatchExpressions = nil + } + return nil + } +} + +func DeepCopy_v1beta1_LabelSelectorRequirement(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*LabelSelectorRequirement) + out := out.(*LabelSelectorRequirement) + out.Key = in.Key + out.Operator = in.Operator + if in.Values != nil { + in, out := &in.Values, &out.Values + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Values = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ListOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ListOptions) + out := out.(*ListOptions) + out.TypeMeta = in.TypeMeta + out.LabelSelector = in.LabelSelector + out.FieldSelector = in.FieldSelector + out.Watch = in.Watch + out.ResourceVersion = in.ResourceVersion + if in.TimeoutSeconds != nil { + in, out := &in.TimeoutSeconds, &out.TimeoutSeconds + *out = new(int64) + **out = **in + } else { + out.TimeoutSeconds = nil + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicy) + out := out.(*NetworkPolicy) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_NetworkPolicySpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicyIngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyIngressRule) + out := out.(*NetworkPolicyIngressRule) + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]NetworkPolicyPort, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_NetworkPolicyPort(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Ports = nil + } + if in.From != nil { + in, out := &in.From, &out.From + *out = make([]NetworkPolicyPeer, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_NetworkPolicyPeer(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.From = nil + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyList) + out := out.(*NetworkPolicyList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]NetworkPolicy, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_NetworkPolicy(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicyPeer(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyPeer) + out := out.(*NetworkPolicyPeer) + if in.PodSelector != nil { + in, out := &in.PodSelector, &out.PodSelector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.PodSelector = nil + } + if in.NamespaceSelector != nil { + in, out := &in.NamespaceSelector, &out.NamespaceSelector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.NamespaceSelector = nil + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicyPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyPort) + out := out.(*NetworkPolicyPort) + if in.Protocol != nil { + in, out := &in.Protocol, &out.Protocol + *out = new(v1.Protocol) + **out = **in + } else { + out.Protocol = nil + } + if in.Port != nil { + in, out := &in.Port, &out.Port + *out = new(intstr.IntOrString) + **out = **in + } else { + out.Port = nil + } + return nil + } +} + +func DeepCopy_v1beta1_NetworkPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicySpec) + out := out.(*NetworkPolicySpec) + if err := DeepCopy_v1beta1_LabelSelector(&in.PodSelector, &out.PodSelector, c); err != nil { + return err + } + if in.Ingress != nil { + in, out := &in.Ingress, &out.Ingress + *out = make([]NetworkPolicyIngressRule, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_NetworkPolicyIngressRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Ingress = nil + } + return nil + } +} + +func DeepCopy_v1beta1_PodSecurityPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicy) + out := out.(*PodSecurityPolicy) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_PodSecurityPolicySpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_PodSecurityPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicyList) + out := out.(*PodSecurityPolicyList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodSecurityPolicy, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_PodSecurityPolicy(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_PodSecurityPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicySpec) + out := out.(*PodSecurityPolicySpec) + out.Privileged = in.Privileged + if in.DefaultAddCapabilities != nil { + in, out := &in.DefaultAddCapabilities, &out.DefaultAddCapabilities + *out = make([]v1.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.DefaultAddCapabilities = nil + } + if in.RequiredDropCapabilities != nil { + in, out := &in.RequiredDropCapabilities, &out.RequiredDropCapabilities + *out = make([]v1.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.RequiredDropCapabilities = nil + } + if in.AllowedCapabilities != nil { + in, out := &in.AllowedCapabilities, &out.AllowedCapabilities + *out = make([]v1.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AllowedCapabilities = nil + } + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]FSType, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Volumes = nil + } + out.HostNetwork = in.HostNetwork + if in.HostPorts != nil { + in, out := &in.HostPorts, &out.HostPorts + *out = make([]HostPortRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.HostPorts = nil + } + out.HostPID = in.HostPID + out.HostIPC = in.HostIPC + if err := DeepCopy_v1beta1_SELinuxStrategyOptions(&in.SELinux, &out.SELinux, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_RunAsUserStrategyOptions(&in.RunAsUser, &out.RunAsUser, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(&in.SupplementalGroups, &out.SupplementalGroups, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_FSGroupStrategyOptions(&in.FSGroup, &out.FSGroup, c); err != nil { + return err + } + out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem + return nil + } +} + +func DeepCopy_v1beta1_ReplicaSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSet) + out := out.(*ReplicaSet) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1beta1_ReplicaSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1beta1_ReplicaSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetList) + out := out.(*ReplicaSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ReplicaSet, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_ReplicaSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ReplicaSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetSpec) + out := out.(*ReplicaSetSpec) + if in.Replicas != nil { + in, out := &in.Replicas, &out.Replicas + *out = new(int32) + **out = **in + } else { + out.Replicas = nil + } + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(LabelSelector) + if err := DeepCopy_v1beta1_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := v1.DeepCopy_v1_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_ReplicaSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetStatus) + out := out.(*ReplicaSetStatus) + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil + } +} + +func DeepCopy_v1beta1_ReplicationControllerDummy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerDummy) + out := out.(*ReplicationControllerDummy) + out.TypeMeta = in.TypeMeta + return nil + } +} + +func DeepCopy_v1beta1_RollbackConfig(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RollbackConfig) + out := out.(*RollbackConfig) + out.Revision = in.Revision + return nil + } +} + +func DeepCopy_v1beta1_RollingUpdateDeployment(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RollingUpdateDeployment) + out := out.(*RollingUpdateDeployment) + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } else { + out.MaxUnavailable = nil + } + if in.MaxSurge != nil { + in, out := &in.MaxSurge, &out.MaxSurge + *out = new(intstr.IntOrString) + **out = **in + } else { + out.MaxSurge = nil + } + return nil + } +} + +func DeepCopy_v1beta1_RunAsUserStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RunAsUserStrategyOptions) + out := out.(*RunAsUserStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_v1beta1_SELinuxStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SELinuxStrategyOptions) + out := out.(*SELinuxStrategyOptions) + out.Rule = in.Rule + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(v1.SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + return nil + } +} + +func DeepCopy_v1beta1_Scale(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Scale) + out := out.(*Scale) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + if err := DeepCopy_v1beta1_ScaleStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_v1beta1_ScaleSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleSpec) + out := out.(*ScaleSpec) + out.Replicas = in.Replicas + return nil + } +} + +func DeepCopy_v1beta1_ScaleStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleStatus) + out := out.(*ScaleStatus) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Selector = nil + } + out.TargetSelector = in.TargetSelector + return nil + } +} + +func DeepCopy_v1beta1_StorageClass(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StorageClass) + out := out.(*StorageClass) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Provisioner = in.Provisioner + if in.Parameters != nil { + in, out := &in.Parameters, &out.Parameters + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Parameters = nil + } + return nil + } +} + +func DeepCopy_v1beta1_StorageClassList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StorageClassList) + out := out.(*StorageClassList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]StorageClass, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_StorageClass(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_SubresourceReference(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SubresourceReference) + out := out.(*SubresourceReference) + out.Kind = in.Kind + out.Name = in.Name + out.APIVersion = in.APIVersion + out.Subresource = in.Subresource + return nil + } +} + +func DeepCopy_v1beta1_SupplementalGroupsStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SupplementalGroupsStrategyOptions) + out := out.(*SupplementalGroupsStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ThirdPartyResource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResource) + out := out.(*ThirdPartyResource) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Description = in.Description + if in.Versions != nil { + in, out := &in.Versions, &out.Versions + *out = make([]APIVersion, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Versions = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ThirdPartyResourceData(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceData) + out := out.(*ThirdPartyResourceData) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ThirdPartyResourceDataList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceDataList) + out := out.(*ThirdPartyResourceDataList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ThirdPartyResourceData, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_ThirdPartyResourceData(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1beta1_ThirdPartyResourceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceList) + out := out.(*ThirdPartyResourceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ThirdPartyResource, len(*in)) + for i := range *in { + if err := DeepCopy_v1beta1_ThirdPartyResource(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go index d0405c3770f5..9476b98479cd 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -147,18 +147,24 @@ var ValidateDeploymentName = apivalidation.NameIsDNSSubdomain func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - if intOrPercent.Type == intstr.String { - if !validation.IsValidPercent(intOrPercent.StrVal) { - allErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, "must be an integer or percentage (e.g '5%')")) + switch intOrPercent.Type { + case intstr.String: + for _, msg := range validation.IsValidPercent(intOrPercent.StrVal) { + allErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, msg)) } - } else if intOrPercent.Type == intstr.Int { + case intstr.Int: allErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(intOrPercent.IntValue()), fldPath)...) + default: + allErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, "must be an integer or percentage (e.g '5%%')")) } return allErrs } func getPercentValue(intOrStringValue intstr.IntOrString) (int, bool) { - if intOrStringValue.Type != intstr.String || !validation.IsValidPercent(intOrStringValue.StrVal) { + if intOrStringValue.Type != intstr.String { + return 0, false + } + if len(validation.IsValidPercent(intOrStringValue.StrVal)) != 0 { return 0, false } value, _ := strconv.Atoi(intOrStringValue.StrVal[:len(intOrStringValue.StrVal)-1]) @@ -422,16 +428,7 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceName"), backend.ServiceName, msg)) } } - if backend.ServicePort.Type == intstr.String { - for _, msg := range validation.IsDNS1123Label(backend.ServicePort.StrVal) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, msg)) - } - if !validation.IsValidPortName(backend.ServicePort.StrVal) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) - } - } else if !validation.IsValidPortNum(backend.ServicePort.IntValue()) { - allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort, apivalidation.PortRangeErrorMsg)) - } + allErrs = append(allErrs, apivalidation.ValidatePortNumOrName(backend.ServicePort, fldPath.Child("servicePort"))...) return allErrs } @@ -744,3 +741,65 @@ func ValidateNetworkPolicyUpdate(update, old *extensions.NetworkPolicy) field.Er } return allErrs } + +// ValidateStorageClass validates a StorageClass. +func ValidateStorageClass(storageClass *extensions.StorageClass) field.ErrorList { + allErrs := apivalidation.ValidateObjectMeta(&storageClass.ObjectMeta, false, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata")) + allErrs = append(allErrs, validateProvisioner(storageClass.Provisioner, field.NewPath("provisioner"))...) + allErrs = append(allErrs, validateParameters(storageClass.Parameters, field.NewPath("parameters"))...) + + return allErrs +} + +// ValidateStorageClassUpdate tests if an update to StorageClass is valid. +func ValidateStorageClassUpdate(storageClass, oldStorageClass *extensions.StorageClass) field.ErrorList { + allErrs := apivalidation.ValidateObjectMetaUpdate(&storageClass.ObjectMeta, &oldStorageClass.ObjectMeta, field.NewPath("metadata")) + if !reflect.DeepEqual(oldStorageClass.Parameters, storageClass.Parameters) { + allErrs = append(allErrs, field.Forbidden(field.NewPath("parameters"), "updates to parameters are forbidden.")) + } + + if strings.Compare(storageClass.Provisioner, oldStorageClass.Provisioner) != 0 { + allErrs = append(allErrs, field.Forbidden(field.NewPath("provisioner"), "updates to provisioner are forbidden.")) + } + return allErrs +} + +// validateProvisioner tests if provisioner is a valid qualified name. +func validateProvisioner(provisioner string, fldPath *field.Path) field.ErrorList { + allErrs := field.ErrorList{} + if len(provisioner) == 0 { + allErrs = append(allErrs, field.Required(fldPath, provisioner)) + } + if len(provisioner) > 0 { + for _, msg := range validation.IsQualifiedName(strings.ToLower(provisioner)) { + allErrs = append(allErrs, field.Invalid(fldPath, provisioner, msg)) + } + } + return allErrs +} + +const maxProvisionerParameterSize = 256 * (1 << 10) // 256 kB +const maxProvisionerParameterLen = 512 + +// validateParameters tests that keys are qualified names and that provisionerParameter are < 256kB. +func validateParameters(params map[string]string, fldPath *field.Path) field.ErrorList { + var totalSize int64 + allErrs := field.ErrorList{} + + if len(params) > maxProvisionerParameterLen { + allErrs = append(allErrs, field.TooLong(fldPath, "Provisioner Parameters exceeded max allowed", maxProvisionerParameterLen)) + return allErrs + } + + for k, v := range params { + if len(k) < 1 { + allErrs = append(allErrs, field.Invalid(fldPath, k, "field can not be empty.")) + } + totalSize += (int64)(len(k)) + (int64)(len(v)) + } + + if totalSize > maxProvisionerParameterSize { + allErrs = append(allErrs, field.TooLong(fldPath, "", maxProvisionerParameterSize)) + } + return allErrs +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/zz_generated.deepcopy.go new file mode 100644 index 000000000000..58c48c35eac6 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/extensions/zz_generated.deepcopy.go @@ -0,0 +1,1121 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package extensions + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + intstr "k8s.io/kubernetes/pkg/util/intstr" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_APIVersion, InType: reflect.TypeOf(func() *APIVersion { var x *APIVersion; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_CustomMetricCurrentStatus, InType: reflect.TypeOf(func() *CustomMetricCurrentStatus { var x *CustomMetricCurrentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_CustomMetricCurrentStatusList, InType: reflect.TypeOf(func() *CustomMetricCurrentStatusList { var x *CustomMetricCurrentStatusList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_CustomMetricTarget, InType: reflect.TypeOf(func() *CustomMetricTarget { var x *CustomMetricTarget; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_CustomMetricTargetList, InType: reflect.TypeOf(func() *CustomMetricTargetList { var x *CustomMetricTargetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DaemonSet, InType: reflect.TypeOf(func() *DaemonSet { var x *DaemonSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DaemonSetList, InType: reflect.TypeOf(func() *DaemonSetList { var x *DaemonSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DaemonSetSpec, InType: reflect.TypeOf(func() *DaemonSetSpec { var x *DaemonSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DaemonSetStatus, InType: reflect.TypeOf(func() *DaemonSetStatus { var x *DaemonSetStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_Deployment, InType: reflect.TypeOf(func() *Deployment { var x *Deployment; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DeploymentList, InType: reflect.TypeOf(func() *DeploymentList { var x *DeploymentList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DeploymentRollback, InType: reflect.TypeOf(func() *DeploymentRollback { var x *DeploymentRollback; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DeploymentSpec, InType: reflect.TypeOf(func() *DeploymentSpec { var x *DeploymentSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DeploymentStatus, InType: reflect.TypeOf(func() *DeploymentStatus { var x *DeploymentStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_DeploymentStrategy, InType: reflect.TypeOf(func() *DeploymentStrategy { var x *DeploymentStrategy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_FSGroupStrategyOptions, InType: reflect.TypeOf(func() *FSGroupStrategyOptions { var x *FSGroupStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_HTTPIngressPath, InType: reflect.TypeOf(func() *HTTPIngressPath { var x *HTTPIngressPath; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_HTTPIngressRuleValue, InType: reflect.TypeOf(func() *HTTPIngressRuleValue { var x *HTTPIngressRuleValue; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_HostPortRange, InType: reflect.TypeOf(func() *HostPortRange { var x *HostPortRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IDRange, InType: reflect.TypeOf(func() *IDRange { var x *IDRange; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_Ingress, InType: reflect.TypeOf(func() *Ingress { var x *Ingress; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressBackend, InType: reflect.TypeOf(func() *IngressBackend { var x *IngressBackend; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressList, InType: reflect.TypeOf(func() *IngressList { var x *IngressList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressRule, InType: reflect.TypeOf(func() *IngressRule { var x *IngressRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressRuleValue, InType: reflect.TypeOf(func() *IngressRuleValue { var x *IngressRuleValue; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressSpec, InType: reflect.TypeOf(func() *IngressSpec { var x *IngressSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressStatus, InType: reflect.TypeOf(func() *IngressStatus { var x *IngressStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_IngressTLS, InType: reflect.TypeOf(func() *IngressTLS { var x *IngressTLS; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicy, InType: reflect.TypeOf(func() *NetworkPolicy { var x *NetworkPolicy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicyIngressRule, InType: reflect.TypeOf(func() *NetworkPolicyIngressRule { var x *NetworkPolicyIngressRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicyList, InType: reflect.TypeOf(func() *NetworkPolicyList { var x *NetworkPolicyList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicyPeer, InType: reflect.TypeOf(func() *NetworkPolicyPeer { var x *NetworkPolicyPeer; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicyPort, InType: reflect.TypeOf(func() *NetworkPolicyPort { var x *NetworkPolicyPort; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_NetworkPolicySpec, InType: reflect.TypeOf(func() *NetworkPolicySpec { var x *NetworkPolicySpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_PodSecurityPolicy, InType: reflect.TypeOf(func() *PodSecurityPolicy { var x *PodSecurityPolicy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_PodSecurityPolicyList, InType: reflect.TypeOf(func() *PodSecurityPolicyList { var x *PodSecurityPolicyList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_PodSecurityPolicySpec, InType: reflect.TypeOf(func() *PodSecurityPolicySpec { var x *PodSecurityPolicySpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ReplicaSet, InType: reflect.TypeOf(func() *ReplicaSet { var x *ReplicaSet; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ReplicaSetList, InType: reflect.TypeOf(func() *ReplicaSetList { var x *ReplicaSetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ReplicaSetSpec, InType: reflect.TypeOf(func() *ReplicaSetSpec { var x *ReplicaSetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ReplicaSetStatus, InType: reflect.TypeOf(func() *ReplicaSetStatus { var x *ReplicaSetStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ReplicationControllerDummy, InType: reflect.TypeOf(func() *ReplicationControllerDummy { var x *ReplicationControllerDummy; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_RollbackConfig, InType: reflect.TypeOf(func() *RollbackConfig { var x *RollbackConfig; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_RollingUpdateDeployment, InType: reflect.TypeOf(func() *RollingUpdateDeployment { var x *RollingUpdateDeployment; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_RunAsUserStrategyOptions, InType: reflect.TypeOf(func() *RunAsUserStrategyOptions { var x *RunAsUserStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_SELinuxStrategyOptions, InType: reflect.TypeOf(func() *SELinuxStrategyOptions { var x *SELinuxStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_Scale, InType: reflect.TypeOf(func() *Scale { var x *Scale; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ScaleSpec, InType: reflect.TypeOf(func() *ScaleSpec { var x *ScaleSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ScaleStatus, InType: reflect.TypeOf(func() *ScaleStatus { var x *ScaleStatus; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_StorageClass, InType: reflect.TypeOf(func() *StorageClass { var x *StorageClass; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_StorageClassList, InType: reflect.TypeOf(func() *StorageClassList { var x *StorageClassList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_SupplementalGroupsStrategyOptions, InType: reflect.TypeOf(func() *SupplementalGroupsStrategyOptions { var x *SupplementalGroupsStrategyOptions; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ThirdPartyResource, InType: reflect.TypeOf(func() *ThirdPartyResource { var x *ThirdPartyResource; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ThirdPartyResourceData, InType: reflect.TypeOf(func() *ThirdPartyResourceData { var x *ThirdPartyResourceData; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ThirdPartyResourceDataList, InType: reflect.TypeOf(func() *ThirdPartyResourceDataList { var x *ThirdPartyResourceDataList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_extensions_ThirdPartyResourceList, InType: reflect.TypeOf(func() *ThirdPartyResourceList { var x *ThirdPartyResourceList; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_extensions_APIVersion(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*APIVersion) + out := out.(*APIVersion) + out.Name = in.Name + return nil + } +} + +func DeepCopy_extensions_CustomMetricCurrentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricCurrentStatus) + out := out.(*CustomMetricCurrentStatus) + out.Name = in.Name + out.CurrentValue = in.CurrentValue.DeepCopy() + return nil + } +} + +func DeepCopy_extensions_CustomMetricCurrentStatusList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricCurrentStatusList) + out := out.(*CustomMetricCurrentStatusList) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CustomMetricCurrentStatus, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_CustomMetricCurrentStatus(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_CustomMetricTarget(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricTarget) + out := out.(*CustomMetricTarget) + out.Name = in.Name + out.TargetValue = in.TargetValue.DeepCopy() + return nil + } +} + +func DeepCopy_extensions_CustomMetricTargetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*CustomMetricTargetList) + out := out.(*CustomMetricTargetList) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CustomMetricTarget, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_CustomMetricTarget(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_DaemonSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSet) + out := out.(*DaemonSet) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_DaemonSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_extensions_DaemonSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetList) + out := out.(*DaemonSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]DaemonSet, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_DaemonSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_DaemonSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetSpec) + out := out.(*DaemonSetSpec) + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_DaemonSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DaemonSetStatus) + out := out.(*DaemonSetStatus) + out.CurrentNumberScheduled = in.CurrentNumberScheduled + out.NumberMisscheduled = in.NumberMisscheduled + out.DesiredNumberScheduled = in.DesiredNumberScheduled + return nil + } +} + +func DeepCopy_extensions_Deployment(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Deployment) + out := out.(*Deployment) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_DeploymentSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_extensions_DeploymentList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentList) + out := out.(*DeploymentList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Deployment, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_Deployment(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_DeploymentRollback(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentRollback) + out := out.(*DeploymentRollback) + out.TypeMeta = in.TypeMeta + out.Name = in.Name + if in.UpdatedAnnotations != nil { + in, out := &in.UpdatedAnnotations, &out.UpdatedAnnotations + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.UpdatedAnnotations = nil + } + out.RollbackTo = in.RollbackTo + return nil + } +} + +func DeepCopy_extensions_DeploymentSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentSpec) + out := out.(*DeploymentSpec) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + if err := DeepCopy_extensions_DeploymentStrategy(&in.Strategy, &out.Strategy, c); err != nil { + return err + } + out.MinReadySeconds = in.MinReadySeconds + if in.RevisionHistoryLimit != nil { + in, out := &in.RevisionHistoryLimit, &out.RevisionHistoryLimit + *out = new(int32) + **out = **in + } else { + out.RevisionHistoryLimit = nil + } + out.Paused = in.Paused + if in.RollbackTo != nil { + in, out := &in.RollbackTo, &out.RollbackTo + *out = new(RollbackConfig) + **out = **in + } else { + out.RollbackTo = nil + } + return nil + } +} + +func DeepCopy_extensions_DeploymentStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentStatus) + out := out.(*DeploymentStatus) + out.ObservedGeneration = in.ObservedGeneration + out.Replicas = in.Replicas + out.UpdatedReplicas = in.UpdatedReplicas + out.AvailableReplicas = in.AvailableReplicas + out.UnavailableReplicas = in.UnavailableReplicas + return nil + } +} + +func DeepCopy_extensions_DeploymentStrategy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*DeploymentStrategy) + out := out.(*DeploymentStrategy) + out.Type = in.Type + if in.RollingUpdate != nil { + in, out := &in.RollingUpdate, &out.RollingUpdate + *out = new(RollingUpdateDeployment) + **out = **in + } else { + out.RollingUpdate = nil + } + return nil + } +} + +func DeepCopy_extensions_FSGroupStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*FSGroupStrategyOptions) + out := out.(*FSGroupStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_extensions_HTTPIngressPath(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPIngressPath) + out := out.(*HTTPIngressPath) + out.Path = in.Path + out.Backend = in.Backend + return nil + } +} + +func DeepCopy_extensions_HTTPIngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HTTPIngressRuleValue) + out := out.(*HTTPIngressRuleValue) + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]HTTPIngressPath, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Paths = nil + } + return nil + } +} + +func DeepCopy_extensions_HostPortRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*HostPortRange) + out := out.(*HostPortRange) + out.Min = in.Min + out.Max = in.Max + return nil + } +} + +func DeepCopy_extensions_IDRange(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IDRange) + out := out.(*IDRange) + out.Min = in.Min + out.Max = in.Max + return nil + } +} + +func DeepCopy_extensions_Ingress(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Ingress) + out := out.(*Ingress) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_IngressSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + if err := DeepCopy_extensions_IngressStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_IngressBackend(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressBackend) + out := out.(*IngressBackend) + out.ServiceName = in.ServiceName + out.ServicePort = in.ServicePort + return nil + } +} + +func DeepCopy_extensions_IngressList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressList) + out := out.(*IngressList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Ingress, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_Ingress(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_IngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressRule) + out := out.(*IngressRule) + out.Host = in.Host + if err := DeepCopy_extensions_IngressRuleValue(&in.IngressRuleValue, &out.IngressRuleValue, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_IngressRuleValue(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressRuleValue) + out := out.(*IngressRuleValue) + if in.HTTP != nil { + in, out := &in.HTTP, &out.HTTP + *out = new(HTTPIngressRuleValue) + if err := DeepCopy_extensions_HTTPIngressRuleValue(*in, *out, c); err != nil { + return err + } + } else { + out.HTTP = nil + } + return nil + } +} + +func DeepCopy_extensions_IngressSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressSpec) + out := out.(*IngressSpec) + if in.Backend != nil { + in, out := &in.Backend, &out.Backend + *out = new(IngressBackend) + **out = **in + } else { + out.Backend = nil + } + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = make([]IngressTLS, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_IngressTLS(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.TLS = nil + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]IngressRule, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_IngressRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_extensions_IngressStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressStatus) + out := out.(*IngressStatus) + if err := api.DeepCopy_api_LoadBalancerStatus(&in.LoadBalancer, &out.LoadBalancer, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_IngressTLS(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*IngressTLS) + out := out.(*IngressTLS) + if in.Hosts != nil { + in, out := &in.Hosts, &out.Hosts + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Hosts = nil + } + out.SecretName = in.SecretName + return nil + } +} + +func DeepCopy_extensions_NetworkPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicy) + out := out.(*NetworkPolicy) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_NetworkPolicySpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_NetworkPolicyIngressRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyIngressRule) + out := out.(*NetworkPolicyIngressRule) + if in.Ports != nil { + in, out := &in.Ports, &out.Ports + *out = make([]NetworkPolicyPort, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_NetworkPolicyPort(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Ports = nil + } + if in.From != nil { + in, out := &in.From, &out.From + *out = make([]NetworkPolicyPeer, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_NetworkPolicyPeer(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.From = nil + } + return nil + } +} + +func DeepCopy_extensions_NetworkPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyList) + out := out.(*NetworkPolicyList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]NetworkPolicy, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_NetworkPolicy(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_NetworkPolicyPeer(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyPeer) + out := out.(*NetworkPolicyPeer) + if in.PodSelector != nil { + in, out := &in.PodSelector, &out.PodSelector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.PodSelector = nil + } + if in.NamespaceSelector != nil { + in, out := &in.NamespaceSelector, &out.NamespaceSelector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.NamespaceSelector = nil + } + return nil + } +} + +func DeepCopy_extensions_NetworkPolicyPort(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicyPort) + out := out.(*NetworkPolicyPort) + if in.Protocol != nil { + in, out := &in.Protocol, &out.Protocol + *out = new(api.Protocol) + **out = **in + } else { + out.Protocol = nil + } + if in.Port != nil { + in, out := &in.Port, &out.Port + *out = new(intstr.IntOrString) + **out = **in + } else { + out.Port = nil + } + return nil + } +} + +func DeepCopy_extensions_NetworkPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*NetworkPolicySpec) + out := out.(*NetworkPolicySpec) + if err := unversioned.DeepCopy_unversioned_LabelSelector(&in.PodSelector, &out.PodSelector, c); err != nil { + return err + } + if in.Ingress != nil { + in, out := &in.Ingress, &out.Ingress + *out = make([]NetworkPolicyIngressRule, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_NetworkPolicyIngressRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Ingress = nil + } + return nil + } +} + +func DeepCopy_extensions_PodSecurityPolicy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicy) + out := out.(*PodSecurityPolicy) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_PodSecurityPolicySpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_PodSecurityPolicyList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicyList) + out := out.(*PodSecurityPolicyList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodSecurityPolicy, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_PodSecurityPolicy(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_PodSecurityPolicySpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodSecurityPolicySpec) + out := out.(*PodSecurityPolicySpec) + out.Privileged = in.Privileged + if in.DefaultAddCapabilities != nil { + in, out := &in.DefaultAddCapabilities, &out.DefaultAddCapabilities + *out = make([]api.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.DefaultAddCapabilities = nil + } + if in.RequiredDropCapabilities != nil { + in, out := &in.RequiredDropCapabilities, &out.RequiredDropCapabilities + *out = make([]api.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.RequiredDropCapabilities = nil + } + if in.AllowedCapabilities != nil { + in, out := &in.AllowedCapabilities, &out.AllowedCapabilities + *out = make([]api.Capability, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.AllowedCapabilities = nil + } + if in.Volumes != nil { + in, out := &in.Volumes, &out.Volumes + *out = make([]FSType, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Volumes = nil + } + out.HostNetwork = in.HostNetwork + if in.HostPorts != nil { + in, out := &in.HostPorts, &out.HostPorts + *out = make([]HostPortRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.HostPorts = nil + } + out.HostPID = in.HostPID + out.HostIPC = in.HostIPC + if err := DeepCopy_extensions_SELinuxStrategyOptions(&in.SELinux, &out.SELinux, c); err != nil { + return err + } + if err := DeepCopy_extensions_RunAsUserStrategyOptions(&in.RunAsUser, &out.RunAsUser, c); err != nil { + return err + } + if err := DeepCopy_extensions_SupplementalGroupsStrategyOptions(&in.SupplementalGroups, &out.SupplementalGroups, c); err != nil { + return err + } + if err := DeepCopy_extensions_FSGroupStrategyOptions(&in.FSGroup, &out.FSGroup, c); err != nil { + return err + } + out.ReadOnlyRootFilesystem = in.ReadOnlyRootFilesystem + return nil + } +} + +func DeepCopy_extensions_ReplicaSet(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSet) + out := out.(*ReplicaSet) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_extensions_ReplicaSetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_extensions_ReplicaSetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetList) + out := out.(*ReplicaSetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ReplicaSet, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_ReplicaSet(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_ReplicaSetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetSpec) + out := out.(*ReplicaSetSpec) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + if err := api.DeepCopy_api_PodTemplateSpec(&in.Template, &out.Template, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_ReplicaSetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicaSetStatus) + out := out.(*ReplicaSetStatus) + out.Replicas = in.Replicas + out.FullyLabeledReplicas = in.FullyLabeledReplicas + out.ObservedGeneration = in.ObservedGeneration + return nil + } +} + +func DeepCopy_extensions_ReplicationControllerDummy(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ReplicationControllerDummy) + out := out.(*ReplicationControllerDummy) + out.TypeMeta = in.TypeMeta + return nil + } +} + +func DeepCopy_extensions_RollbackConfig(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RollbackConfig) + out := out.(*RollbackConfig) + out.Revision = in.Revision + return nil + } +} + +func DeepCopy_extensions_RollingUpdateDeployment(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RollingUpdateDeployment) + out := out.(*RollingUpdateDeployment) + out.MaxUnavailable = in.MaxUnavailable + out.MaxSurge = in.MaxSurge + return nil + } +} + +func DeepCopy_extensions_RunAsUserStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RunAsUserStrategyOptions) + out := out.(*RunAsUserStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_extensions_SELinuxStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SELinuxStrategyOptions) + out := out.(*SELinuxStrategyOptions) + out.Rule = in.Rule + if in.SELinuxOptions != nil { + in, out := &in.SELinuxOptions, &out.SELinuxOptions + *out = new(api.SELinuxOptions) + **out = **in + } else { + out.SELinuxOptions = nil + } + return nil + } +} + +func DeepCopy_extensions_Scale(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Scale) + out := out.(*Scale) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Spec = in.Spec + if err := DeepCopy_extensions_ScaleStatus(&in.Status, &out.Status, c); err != nil { + return err + } + return nil + } +} + +func DeepCopy_extensions_ScaleSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleSpec) + out := out.(*ScaleSpec) + out.Replicas = in.Replicas + return nil + } +} + +func DeepCopy_extensions_ScaleStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ScaleStatus) + out := out.(*ScaleStatus) + out.Replicas = in.Replicas + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + return nil + } +} + +func DeepCopy_extensions_StorageClass(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StorageClass) + out := out.(*StorageClass) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Provisioner = in.Provisioner + if in.Parameters != nil { + in, out := &in.Parameters, &out.Parameters + *out = make(map[string]string) + for key, val := range *in { + (*out)[key] = val + } + } else { + out.Parameters = nil + } + return nil + } +} + +func DeepCopy_extensions_StorageClassList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*StorageClassList) + out := out.(*StorageClassList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]StorageClass, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_StorageClass(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_SupplementalGroupsStrategyOptions(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*SupplementalGroupsStrategyOptions) + out := out.(*SupplementalGroupsStrategyOptions) + out.Rule = in.Rule + if in.Ranges != nil { + in, out := &in.Ranges, &out.Ranges + *out = make([]IDRange, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Ranges = nil + } + return nil + } +} + +func DeepCopy_extensions_ThirdPartyResource(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResource) + out := out.(*ThirdPartyResource) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + out.Description = in.Description + if in.Versions != nil { + in, out := &in.Versions, &out.Versions + *out = make([]APIVersion, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Versions = nil + } + return nil + } +} + +func DeepCopy_extensions_ThirdPartyResourceData(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceData) + out := out.(*ThirdPartyResourceData) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Data != nil { + in, out := &in.Data, &out.Data + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Data = nil + } + return nil + } +} + +func DeepCopy_extensions_ThirdPartyResourceDataList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceDataList) + out := out.(*ThirdPartyResourceDataList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ThirdPartyResourceData, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_ThirdPartyResourceData(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_extensions_ThirdPartyResourceList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ThirdPartyResourceList) + out := out.(*ThirdPartyResourceList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ThirdPartyResource, len(*in)) + for i := range *in { + if err := DeepCopy_extensions_ThirdPartyResource(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/deep_copy_generated.go deleted file mode 100644 index 390e4b4a7b48..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/deep_copy_generated.go +++ /dev/null @@ -1,101 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package policy - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_policy_PodDisruptionBudget, - DeepCopy_policy_PodDisruptionBudgetList, - DeepCopy_policy_PodDisruptionBudgetSpec, - DeepCopy_policy_PodDisruptionBudgetStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_policy_PodDisruptionBudget(in PodDisruptionBudget, out *PodDisruptionBudget, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_policy_PodDisruptionBudgetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_policy_PodDisruptionBudgetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_policy_PodDisruptionBudgetList(in PodDisruptionBudgetList, out *PodDisruptionBudgetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodDisruptionBudget, len(in)) - for i := range in { - if err := DeepCopy_policy_PodDisruptionBudget(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_policy_PodDisruptionBudgetSpec(in PodDisruptionBudgetSpec, out *PodDisruptionBudgetSpec, c *conversion.Cloner) error { - if err := intstr.DeepCopy_intstr_IntOrString(in.MinAvailable, &out.MinAvailable, c); err != nil { - return err - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - return nil -} - -func DeepCopy_policy_PodDisruptionBudgetStatus(in PodDisruptionBudgetStatus, out *PodDisruptionBudgetStatus, c *conversion.Cloner) error { - out.PodDisruptionAllowed = in.PodDisruptionAllowed - out.CurrentHealthy = in.CurrentHealthy - out.DesiredHealthy = in.DesiredHealthy - out.ExpectedPods = in.ExpectedPods - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/doc.go new file mode 100644 index 000000000000..876858cd9a76 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// +k8s:deepcopy-gen=package,register + +package policy diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/install/install.go index 7882a0c53108..90489a74414b 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/register.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/register.go index 76ea1a55244f..e61c82b287cc 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/types.generated.go index 08be370f1584..06652687a215 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/types.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/types.go index 2ecf41bcffd3..adc31e59f15d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -49,7 +49,8 @@ type PodDisruptionBudgetStatus struct { ExpectedPods int32 `json:"expectedPods"` } -// +genclient=true,noMethods=true +// +genclient=true +// +noMethods=true // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods type PodDisruptionBudget struct { diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/deep_copy_generated.go deleted file mode 100644 index 74680aff846a..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/deep_copy_generated.go +++ /dev/null @@ -1,102 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" - intstr "k8s.io/kubernetes/pkg/util/intstr" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1alpha1_PodDisruptionBudget, - DeepCopy_v1alpha1_PodDisruptionBudgetList, - DeepCopy_v1alpha1_PodDisruptionBudgetSpec, - DeepCopy_v1alpha1_PodDisruptionBudgetStatus, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1alpha1_PodDisruptionBudget(in PodDisruptionBudget, out *PodDisruptionBudget, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if err := DeepCopy_v1alpha1_PodDisruptionBudgetSpec(in.Spec, &out.Spec, c); err != nil { - return err - } - if err := DeepCopy_v1alpha1_PodDisruptionBudgetStatus(in.Status, &out.Status, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_PodDisruptionBudgetList(in PodDisruptionBudgetList, out *PodDisruptionBudgetList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]PodDisruptionBudget, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_PodDisruptionBudget(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_PodDisruptionBudgetSpec(in PodDisruptionBudgetSpec, out *PodDisruptionBudgetSpec, c *conversion.Cloner) error { - if err := intstr.DeepCopy_intstr_IntOrString(in.MinAvailable, &out.MinAvailable, c); err != nil { - return err - } - if in.Selector != nil { - in, out := in.Selector, &out.Selector - *out = new(unversioned.LabelSelector) - if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { - return err - } - } else { - out.Selector = nil - } - return nil -} - -func DeepCopy_v1alpha1_PodDisruptionBudgetStatus(in PodDisruptionBudgetStatus, out *PodDisruptionBudgetStatus, c *conversion.Cloner) error { - out.PodDisruptionAllowed = in.PodDisruptionAllowed - out.CurrentHealthy = in.CurrentHealthy - out.DesiredHealthy = in.DesiredHealthy - out.ExpectedPods = in.ExpectedPods - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/doc.go index 5cb716c29952..985d4bbf071a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/policy + // Package policy is for any kind of policy object. Suitable examples, even if // they aren't all here, are PodDisruptionBudget, PodSecurityPolicy, // NetworkPolicy, etc. -// +genconversion=true package v1alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.pb.go index 867a6b0a6dda..46a12f75e993 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,9 @@ import math "math" import k8s_io_kubernetes_pkg_api_unversioned "k8s.io/kubernetes/pkg/api/unversioned" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -45,21 +48,17 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *PodDisruptionBudget) Reset() { *m = PodDisruptionBudget{} } -func (m *PodDisruptionBudget) String() string { return proto.CompactTextString(m) } -func (*PodDisruptionBudget) ProtoMessage() {} +func (m *PodDisruptionBudget) Reset() { *m = PodDisruptionBudget{} } +func (*PodDisruptionBudget) ProtoMessage() {} -func (m *PodDisruptionBudgetList) Reset() { *m = PodDisruptionBudgetList{} } -func (m *PodDisruptionBudgetList) String() string { return proto.CompactTextString(m) } -func (*PodDisruptionBudgetList) ProtoMessage() {} +func (m *PodDisruptionBudgetList) Reset() { *m = PodDisruptionBudgetList{} } +func (*PodDisruptionBudgetList) ProtoMessage() {} -func (m *PodDisruptionBudgetSpec) Reset() { *m = PodDisruptionBudgetSpec{} } -func (m *PodDisruptionBudgetSpec) String() string { return proto.CompactTextString(m) } -func (*PodDisruptionBudgetSpec) ProtoMessage() {} +func (m *PodDisruptionBudgetSpec) Reset() { *m = PodDisruptionBudgetSpec{} } +func (*PodDisruptionBudgetSpec) ProtoMessage() {} -func (m *PodDisruptionBudgetStatus) Reset() { *m = PodDisruptionBudgetStatus{} } -func (m *PodDisruptionBudgetStatus) String() string { return proto.CompactTextString(m) } -func (*PodDisruptionBudgetStatus) ProtoMessage() {} +func (m *PodDisruptionBudgetStatus) Reset() { *m = PodDisruptionBudgetStatus{} } +func (*PodDisruptionBudgetStatus) ProtoMessage() {} func init() { proto.RegisterType((*PodDisruptionBudget)(nil), "k8s.io.kubernetes.pkg.apis.policy.v1alpha1.PodDisruptionBudget") @@ -306,6 +305,61 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *PodDisruptionBudget) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodDisruptionBudget{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "PodDisruptionBudgetSpec", "PodDisruptionBudgetSpec", 1), `&`, ``, 1) + `,`, + `Status:` + strings.Replace(strings.Replace(this.Status.String(), "PodDisruptionBudgetStatus", "PodDisruptionBudgetStatus", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodDisruptionBudgetList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodDisruptionBudgetList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "PodDisruptionBudget", "PodDisruptionBudget", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodDisruptionBudgetSpec) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodDisruptionBudgetSpec{`, + `MinAvailable:` + strings.Replace(strings.Replace(this.MinAvailable.String(), "IntOrString", "k8s_io_kubernetes_pkg_util_intstr.IntOrString", 1), `&`, ``, 1) + `,`, + `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LabelSelector", "k8s_io_kubernetes_pkg_api_unversioned.LabelSelector", 1) + `,`, + `}`, + }, "") + return s +} +func (this *PodDisruptionBudgetStatus) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PodDisruptionBudgetStatus{`, + `PodDisruptionAllowed:` + fmt.Sprintf("%v", this.PodDisruptionAllowed) + `,`, + `CurrentHealthy:` + fmt.Sprintf("%v", this.CurrentHealthy) + `,`, + `DesiredHealthy:` + fmt.Sprintf("%v", this.DesiredHealthy) + `,`, + `ExpectedPods:` + fmt.Sprintf("%v", this.ExpectedPods) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *PodDisruptionBudget) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.proto index 866d0ae57882..d04a0af8cd24 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/register.go index a6a94d96d007..6a82e3f9ce1c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.generated.go index 7ed4308bcc64..6592c9c3116e 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.go index 1f3265ae272e..efe136fda2a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ type PodDisruptionBudgetStatus struct { ExpectedPods int32 `json:"expectedPods" protobuf:"varint,4,opt,name=expectedPods"` } -// +genclient=true,noMethods=true +// +genclient=true +// +noMethods=true // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods type PodDisruptionBudget struct { diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types_swagger_doc_generated.go index 8ca1782f4f98..b12ce0fd263c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.conversion.go index 23aaa9a3787d..c524ca24a3d5 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..99d807b7edd1 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,108 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PodDisruptionBudget, InType: reflect.TypeOf(func() *PodDisruptionBudget { var x *PodDisruptionBudget; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PodDisruptionBudgetList, InType: reflect.TypeOf(func() *PodDisruptionBudgetList { var x *PodDisruptionBudgetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PodDisruptionBudgetSpec, InType: reflect.TypeOf(func() *PodDisruptionBudgetSpec { var x *PodDisruptionBudgetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PodDisruptionBudgetStatus, InType: reflect.TypeOf(func() *PodDisruptionBudgetStatus { var x *PodDisruptionBudgetStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1alpha1_PodDisruptionBudget(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudget) + out := out.(*PodDisruptionBudget) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_v1alpha1_PodDisruptionBudgetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_v1alpha1_PodDisruptionBudgetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetList) + out := out.(*PodDisruptionBudgetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodDisruptionBudget, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_PodDisruptionBudget(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_PodDisruptionBudgetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetSpec) + out := out.(*PodDisruptionBudgetSpec) + out.MinAvailable = in.MinAvailable + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_PodDisruptionBudgetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetStatus) + out := out.(*PodDisruptionBudgetStatus) + out.PodDisruptionAllowed = in.PodDisruptionAllowed + out.CurrentHealthy = in.CurrentHealthy + out.DesiredHealthy = in.DesiredHealthy + out.ExpectedPods = in.ExpectedPods + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/validation/validation.go index 6d40450ba880..e11498e70754 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/policy/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/policy/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/policy/zz_generated.deepcopy.go new file mode 100644 index 000000000000..fb095543665a --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/policy/zz_generated.deepcopy.go @@ -0,0 +1,107 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package policy + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + conversion "k8s.io/kubernetes/pkg/conversion" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_policy_PodDisruptionBudget, InType: reflect.TypeOf(func() *PodDisruptionBudget { var x *PodDisruptionBudget; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_policy_PodDisruptionBudgetList, InType: reflect.TypeOf(func() *PodDisruptionBudgetList { var x *PodDisruptionBudgetList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_policy_PodDisruptionBudgetSpec, InType: reflect.TypeOf(func() *PodDisruptionBudgetSpec { var x *PodDisruptionBudgetSpec; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_policy_PodDisruptionBudgetStatus, InType: reflect.TypeOf(func() *PodDisruptionBudgetStatus { var x *PodDisruptionBudgetStatus; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_policy_PodDisruptionBudget(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudget) + out := out.(*PodDisruptionBudget) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if err := DeepCopy_policy_PodDisruptionBudgetSpec(&in.Spec, &out.Spec, c); err != nil { + return err + } + out.Status = in.Status + return nil + } +} + +func DeepCopy_policy_PodDisruptionBudgetList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetList) + out := out.(*PodDisruptionBudgetList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodDisruptionBudget, len(*in)) + for i := range *in { + if err := DeepCopy_policy_PodDisruptionBudget(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_policy_PodDisruptionBudgetSpec(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetSpec) + out := out.(*PodDisruptionBudgetSpec) + out.MinAvailable = in.MinAvailable + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(unversioned.LabelSelector) + if err := unversioned.DeepCopy_unversioned_LabelSelector(*in, *out, c); err != nil { + return err + } + } else { + out.Selector = nil + } + return nil + } +} + +func DeepCopy_policy_PodDisruptionBudgetStatus(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PodDisruptionBudgetStatus) + out := out.(*PodDisruptionBudgetStatus) + out.PodDisruptionAllowed = in.PodDisruptionAllowed + out.CurrentHealthy = in.CurrentHealthy + out.DesiredHealthy = in.DesiredHealthy + out.ExpectedPods = in.ExpectedPods + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/deep_copy_generated.go deleted file mode 100644 index 5e9339a989bc..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/deep_copy_generated.go +++ /dev/null @@ -1,274 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package rbac - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - conversion "k8s.io/kubernetes/pkg/conversion" - runtime "k8s.io/kubernetes/pkg/runtime" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_rbac_ClusterRole, - DeepCopy_rbac_ClusterRoleBinding, - DeepCopy_rbac_ClusterRoleBindingList, - DeepCopy_rbac_ClusterRoleList, - DeepCopy_rbac_PolicyRule, - DeepCopy_rbac_Role, - DeepCopy_rbac_RoleBinding, - DeepCopy_rbac_RoleBindingList, - DeepCopy_rbac_RoleList, - DeepCopy_rbac_Subject, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_rbac_ClusterRole(in ClusterRole, out *ClusterRole, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]PolicyRule, len(in)) - for i := range in { - if err := DeepCopy_rbac_PolicyRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_rbac_ClusterRoleBinding(in ClusterRoleBinding, out *ClusterRoleBinding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subjects != nil { - in, out := in.Subjects, &out.Subjects - *out = make([]Subject, len(in)) - for i := range in { - if err := DeepCopy_rbac_Subject(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subjects = nil - } - if err := api.DeepCopy_api_ObjectReference(in.RoleRef, &out.RoleRef, c); err != nil { - return err - } - return nil -} - -func DeepCopy_rbac_ClusterRoleBindingList(in ClusterRoleBindingList, out *ClusterRoleBindingList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ClusterRoleBinding, len(in)) - for i := range in { - if err := DeepCopy_rbac_ClusterRoleBinding(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_rbac_ClusterRoleList(in ClusterRoleList, out *ClusterRoleList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ClusterRole, len(in)) - for i := range in { - if err := DeepCopy_rbac_ClusterRole(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_rbac_PolicyRule(in PolicyRule, out *PolicyRule, c *conversion.Cloner) error { - if in.Verbs != nil { - in, out := in.Verbs, &out.Verbs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Verbs = nil - } - if in.AttributeRestrictions == nil { - out.AttributeRestrictions = nil - } else if newVal, err := c.DeepCopy(in.AttributeRestrictions); err != nil { - return err - } else { - out.AttributeRestrictions = newVal.(runtime.Object) - } - if in.APIGroups != nil { - in, out := in.APIGroups, &out.APIGroups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.APIGroups = nil - } - if in.Resources != nil { - in, out := in.Resources, &out.Resources - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Resources = nil - } - if in.ResourceNames != nil { - in, out := in.ResourceNames, &out.ResourceNames - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.ResourceNames = nil - } - if in.NonResourceURLs != nil { - in, out := in.NonResourceURLs, &out.NonResourceURLs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.NonResourceURLs = nil - } - return nil -} - -func DeepCopy_rbac_Role(in Role, out *Role, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]PolicyRule, len(in)) - for i := range in { - if err := DeepCopy_rbac_PolicyRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_rbac_RoleBinding(in RoleBinding, out *RoleBinding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subjects != nil { - in, out := in.Subjects, &out.Subjects - *out = make([]Subject, len(in)) - for i := range in { - if err := DeepCopy_rbac_Subject(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subjects = nil - } - if err := api.DeepCopy_api_ObjectReference(in.RoleRef, &out.RoleRef, c); err != nil { - return err - } - return nil -} - -func DeepCopy_rbac_RoleBindingList(in RoleBindingList, out *RoleBindingList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]RoleBinding, len(in)) - for i := range in { - if err := DeepCopy_rbac_RoleBinding(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_rbac_RoleList(in RoleList, out *RoleList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Role, len(in)) - for i := range in { - if err := DeepCopy_rbac_Role(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_rbac_Subject(in Subject, out *Subject, c *conversion.Cloner) error { - out.Kind = in.Kind - out.APIVersion = in.APIVersion - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/doc.go index 15f91da2c380..e4ce69b40b94 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// +k8s:deepcopy-gen=package,register + // +groupName=rbac.authorization.k8s.io package rbac diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/install/install.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/install/install.go index 8cac247f4cad..0f6dc91b9bb0 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/install/install.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/install/install.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/register.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/register.go index 58464d74d7e1..5d89656e5a13 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/types.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/types.go index a35eb7db9572..44a38971b457 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -126,7 +126,8 @@ type RoleList struct { Items []Role } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. type ClusterRole struct { @@ -138,7 +139,8 @@ type ClusterRole struct { Rules []PolicyRule } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, // and adds who information via Subject. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/deep_copy_generated.go deleted file mode 100644 index f898a434baf5..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/deep_copy_generated.go +++ /dev/null @@ -1,271 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1alpha1 - -import ( - api "k8s.io/kubernetes/pkg/api" - unversioned "k8s.io/kubernetes/pkg/api/unversioned" - v1 "k8s.io/kubernetes/pkg/api/v1" - conversion "k8s.io/kubernetes/pkg/conversion" - runtime "k8s.io/kubernetes/pkg/runtime" -) - -func init() { - if err := api.Scheme.AddGeneratedDeepCopyFuncs( - DeepCopy_v1alpha1_ClusterRole, - DeepCopy_v1alpha1_ClusterRoleBinding, - DeepCopy_v1alpha1_ClusterRoleBindingList, - DeepCopy_v1alpha1_ClusterRoleList, - DeepCopy_v1alpha1_PolicyRule, - DeepCopy_v1alpha1_Role, - DeepCopy_v1alpha1_RoleBinding, - DeepCopy_v1alpha1_RoleBindingList, - DeepCopy_v1alpha1_RoleList, - DeepCopy_v1alpha1_Subject, - ); err != nil { - // if one of the deep copy functions is malformed, detect it immediately. - panic(err) - } -} - -func DeepCopy_v1alpha1_ClusterRole(in ClusterRole, out *ClusterRole, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]PolicyRule, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_PolicyRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_v1alpha1_ClusterRoleBinding(in ClusterRoleBinding, out *ClusterRoleBinding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subjects != nil { - in, out := in.Subjects, &out.Subjects - *out = make([]Subject, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_Subject(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subjects = nil - } - if err := v1.DeepCopy_v1_ObjectReference(in.RoleRef, &out.RoleRef, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_ClusterRoleBindingList(in ClusterRoleBindingList, out *ClusterRoleBindingList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ClusterRoleBinding, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_ClusterRoleBinding(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_ClusterRoleList(in ClusterRoleList, out *ClusterRoleList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]ClusterRole, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_ClusterRole(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_PolicyRule(in PolicyRule, out *PolicyRule, c *conversion.Cloner) error { - if in.Verbs != nil { - in, out := in.Verbs, &out.Verbs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Verbs = nil - } - if err := runtime.DeepCopy_runtime_RawExtension(in.AttributeRestrictions, &out.AttributeRestrictions, c); err != nil { - return err - } - if in.APIGroups != nil { - in, out := in.APIGroups, &out.APIGroups - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.APIGroups = nil - } - if in.Resources != nil { - in, out := in.Resources, &out.Resources - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.Resources = nil - } - if in.ResourceNames != nil { - in, out := in.ResourceNames, &out.ResourceNames - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.ResourceNames = nil - } - if in.NonResourceURLs != nil { - in, out := in.NonResourceURLs, &out.NonResourceURLs - *out = make([]string, len(in)) - copy(*out, in) - } else { - out.NonResourceURLs = nil - } - return nil -} - -func DeepCopy_v1alpha1_Role(in Role, out *Role, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Rules != nil { - in, out := in.Rules, &out.Rules - *out = make([]PolicyRule, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_PolicyRule(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Rules = nil - } - return nil -} - -func DeepCopy_v1alpha1_RoleBinding(in RoleBinding, out *RoleBinding, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := v1.DeepCopy_v1_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil { - return err - } - if in.Subjects != nil { - in, out := in.Subjects, &out.Subjects - *out = make([]Subject, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_Subject(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Subjects = nil - } - if err := v1.DeepCopy_v1_ObjectReference(in.RoleRef, &out.RoleRef, c); err != nil { - return err - } - return nil -} - -func DeepCopy_v1alpha1_RoleBindingList(in RoleBindingList, out *RoleBindingList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]RoleBinding, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_RoleBinding(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_RoleList(in RoleList, out *RoleList, c *conversion.Cloner) error { - if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil { - return err - } - if in.Items != nil { - in, out := in.Items, &out.Items - *out = make([]Role, len(in)) - for i := range in { - if err := DeepCopy_v1alpha1_Role(in[i], &(*out)[i], c); err != nil { - return err - } - } - } else { - out.Items = nil - } - return nil -} - -func DeepCopy_v1alpha1_Subject(in Subject, out *Subject, c *conversion.Cloner) error { - out.Kind = in.Kind - out.APIVersion = in.APIVersion - out.Name = in.Name - out.Namespace = in.Namespace - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/doc.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/doc.go index 6873ebb101ff..e471bd384bff 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,5 +15,7 @@ limitations under the License. */ // +groupName=rbac.authorization.k8s.io -// +genconversion=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=k8s.io/kubernetes/pkg/apis/rbac + package v1alpha1 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.pb.go index 54b03ed15d1d..8065e1a888bd 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -42,6 +42,9 @@ import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -49,45 +52,35 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *ClusterRole) Reset() { *m = ClusterRole{} } -func (m *ClusterRole) String() string { return proto.CompactTextString(m) } -func (*ClusterRole) ProtoMessage() {} +func (m *ClusterRole) Reset() { *m = ClusterRole{} } +func (*ClusterRole) ProtoMessage() {} -func (m *ClusterRoleBinding) Reset() { *m = ClusterRoleBinding{} } -func (m *ClusterRoleBinding) String() string { return proto.CompactTextString(m) } -func (*ClusterRoleBinding) ProtoMessage() {} +func (m *ClusterRoleBinding) Reset() { *m = ClusterRoleBinding{} } +func (*ClusterRoleBinding) ProtoMessage() {} -func (m *ClusterRoleBindingList) Reset() { *m = ClusterRoleBindingList{} } -func (m *ClusterRoleBindingList) String() string { return proto.CompactTextString(m) } -func (*ClusterRoleBindingList) ProtoMessage() {} +func (m *ClusterRoleBindingList) Reset() { *m = ClusterRoleBindingList{} } +func (*ClusterRoleBindingList) ProtoMessage() {} -func (m *ClusterRoleList) Reset() { *m = ClusterRoleList{} } -func (m *ClusterRoleList) String() string { return proto.CompactTextString(m) } -func (*ClusterRoleList) ProtoMessage() {} +func (m *ClusterRoleList) Reset() { *m = ClusterRoleList{} } +func (*ClusterRoleList) ProtoMessage() {} -func (m *PolicyRule) Reset() { *m = PolicyRule{} } -func (m *PolicyRule) String() string { return proto.CompactTextString(m) } -func (*PolicyRule) ProtoMessage() {} +func (m *PolicyRule) Reset() { *m = PolicyRule{} } +func (*PolicyRule) ProtoMessage() {} -func (m *Role) Reset() { *m = Role{} } -func (m *Role) String() string { return proto.CompactTextString(m) } -func (*Role) ProtoMessage() {} +func (m *Role) Reset() { *m = Role{} } +func (*Role) ProtoMessage() {} -func (m *RoleBinding) Reset() { *m = RoleBinding{} } -func (m *RoleBinding) String() string { return proto.CompactTextString(m) } -func (*RoleBinding) ProtoMessage() {} +func (m *RoleBinding) Reset() { *m = RoleBinding{} } +func (*RoleBinding) ProtoMessage() {} -func (m *RoleBindingList) Reset() { *m = RoleBindingList{} } -func (m *RoleBindingList) String() string { return proto.CompactTextString(m) } -func (*RoleBindingList) ProtoMessage() {} +func (m *RoleBindingList) Reset() { *m = RoleBindingList{} } +func (*RoleBindingList) ProtoMessage() {} -func (m *RoleList) Reset() { *m = RoleList{} } -func (m *RoleList) String() string { return proto.CompactTextString(m) } -func (*RoleList) ProtoMessage() {} +func (m *RoleList) Reset() { *m = RoleList{} } +func (*RoleList) ProtoMessage() {} -func (m *Subject) Reset() { *m = Subject{} } -func (m *Subject) String() string { return proto.CompactTextString(m) } -func (*Subject) ProtoMessage() {} +func (m *Subject) Reset() { *m = Subject{} } +func (*Subject) ProtoMessage() {} func init() { proto.RegisterType((*ClusterRole)(nil), "k8s.io.kubernetes.pkg.apis.rbac.v1alpha1.ClusterRole") @@ -764,6 +757,132 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *ClusterRole) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterRole{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Rules:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Rules), "PolicyRule", "PolicyRule", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ClusterRoleBinding) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterRoleBinding{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Subjects:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Subjects), "Subject", "Subject", 1), `&`, ``, 1) + `,`, + `RoleRef:` + strings.Replace(strings.Replace(this.RoleRef.String(), "ObjectReference", "k8s_io_kubernetes_pkg_api_v1.ObjectReference", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ClusterRoleBindingList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterRoleBindingList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ClusterRoleBinding", "ClusterRoleBinding", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *ClusterRoleList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&ClusterRoleList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "ClusterRole", "ClusterRole", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *PolicyRule) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&PolicyRule{`, + `Verbs:` + fmt.Sprintf("%v", this.Verbs) + `,`, + `AttributeRestrictions:` + strings.Replace(strings.Replace(this.AttributeRestrictions.String(), "RawExtension", "k8s_io_kubernetes_pkg_runtime.RawExtension", 1), `&`, ``, 1) + `,`, + `APIGroups:` + fmt.Sprintf("%v", this.APIGroups) + `,`, + `Resources:` + fmt.Sprintf("%v", this.Resources) + `,`, + `ResourceNames:` + fmt.Sprintf("%v", this.ResourceNames) + `,`, + `NonResourceURLs:` + fmt.Sprintf("%v", this.NonResourceURLs) + `,`, + `}`, + }, "") + return s +} +func (this *Role) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Role{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Rules:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Rules), "PolicyRule", "PolicyRule", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *RoleBinding) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RoleBinding{`, + `ObjectMeta:` + strings.Replace(strings.Replace(this.ObjectMeta.String(), "ObjectMeta", "k8s_io_kubernetes_pkg_api_v1.ObjectMeta", 1), `&`, ``, 1) + `,`, + `Subjects:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Subjects), "Subject", "Subject", 1), `&`, ``, 1) + `,`, + `RoleRef:` + strings.Replace(strings.Replace(this.RoleRef.String(), "ObjectReference", "k8s_io_kubernetes_pkg_api_v1.ObjectReference", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *RoleBindingList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RoleBindingList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "RoleBinding", "RoleBinding", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *RoleList) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RoleList{`, + `ListMeta:` + strings.Replace(strings.Replace(this.ListMeta.String(), "ListMeta", "k8s_io_kubernetes_pkg_api_unversioned.ListMeta", 1), `&`, ``, 1) + `,`, + `Items:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Items), "Role", "Role", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func (this *Subject) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Subject{`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `Name:` + fmt.Sprintf("%v", this.Name) + `,`, + `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *ClusterRole) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.proto b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.proto index 15c63b2f5174..062f815b81b3 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/register.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/register.go index eadcb4fbdabb..cff47206bbd8 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.generated.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.generated.go index 58965dec0fcb..bf7b3db2bf32 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.go index 52eacfe3fcfe..a260facea9b4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,7 +113,8 @@ type RoleList struct { Items []Role `json:"items" protobuf:"bytes,2,rep,name=items"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding. type ClusterRole struct { @@ -125,7 +126,8 @@ type ClusterRole struct { Rules []PolicyRule `json:"rules" protobuf:"bytes,2,rep,name=rules"` } -// +genclient=true,nonNamespaced=true +// +genclient=true +// +nonNamespaced=true // ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, // and adds who information via Subject. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types_swagger_doc_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types_swagger_doc_generated.go index b88c93c0346a..f1c6fdbdf613 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types_swagger_doc_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/types_swagger_doc_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/conversion_generated.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/conversion_generated.go rename to vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go index f176aa090663..558814677104 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/conversion_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.conversion.go @@ -1,7 +1,7 @@ // +build !ignore_autogenerated /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000000..f0145a6ac81f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,279 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + api "k8s.io/kubernetes/pkg/api" + v1 "k8s.io/kubernetes/pkg/api/v1" + conversion "k8s.io/kubernetes/pkg/conversion" + runtime "k8s.io/kubernetes/pkg/runtime" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ClusterRole, InType: reflect.TypeOf(func() *ClusterRole { var x *ClusterRole; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ClusterRoleBinding, InType: reflect.TypeOf(func() *ClusterRoleBinding { var x *ClusterRoleBinding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ClusterRoleBindingList, InType: reflect.TypeOf(func() *ClusterRoleBindingList { var x *ClusterRoleBindingList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_ClusterRoleList, InType: reflect.TypeOf(func() *ClusterRoleList { var x *ClusterRoleList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_PolicyRule, InType: reflect.TypeOf(func() *PolicyRule { var x *PolicyRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_Role, InType: reflect.TypeOf(func() *Role { var x *Role; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_RoleBinding, InType: reflect.TypeOf(func() *RoleBinding { var x *RoleBinding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_RoleBindingList, InType: reflect.TypeOf(func() *RoleBindingList { var x *RoleBindingList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_RoleList, InType: reflect.TypeOf(func() *RoleList { var x *RoleList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_v1alpha1_Subject, InType: reflect.TypeOf(func() *Subject { var x *Subject; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_v1alpha1_ClusterRole(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRole) + out := out.(*ClusterRole) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]PolicyRule, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_PolicyRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_ClusterRoleBinding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleBinding) + out := out.(*ClusterRoleBinding) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subjects != nil { + in, out := &in.Subjects, &out.Subjects + *out = make([]Subject, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Subjects = nil + } + out.RoleRef = in.RoleRef + return nil + } +} + +func DeepCopy_v1alpha1_ClusterRoleBindingList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleBindingList) + out := out.(*ClusterRoleBindingList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterRoleBinding, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_ClusterRoleBinding(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_ClusterRoleList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleList) + out := out.(*ClusterRoleList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterRole, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_ClusterRole(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_PolicyRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PolicyRule) + out := out.(*PolicyRule) + if in.Verbs != nil { + in, out := &in.Verbs, &out.Verbs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Verbs = nil + } + if err := runtime.DeepCopy_runtime_RawExtension(&in.AttributeRestrictions, &out.AttributeRestrictions, c); err != nil { + return err + } + if in.APIGroups != nil { + in, out := &in.APIGroups, &out.APIGroups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.APIGroups = nil + } + if in.Resources != nil { + in, out := &in.Resources, &out.Resources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Resources = nil + } + if in.ResourceNames != nil { + in, out := &in.ResourceNames, &out.ResourceNames + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.ResourceNames = nil + } + if in.NonResourceURLs != nil { + in, out := &in.NonResourceURLs, &out.NonResourceURLs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.NonResourceURLs = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_Role(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Role) + out := out.(*Role) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]PolicyRule, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_PolicyRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_RoleBinding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleBinding) + out := out.(*RoleBinding) + out.TypeMeta = in.TypeMeta + if err := v1.DeepCopy_v1_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subjects != nil { + in, out := &in.Subjects, &out.Subjects + *out = make([]Subject, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Subjects = nil + } + out.RoleRef = in.RoleRef + return nil + } +} + +func DeepCopy_v1alpha1_RoleBindingList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleBindingList) + out := out.(*RoleBindingList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]RoleBinding, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_RoleBinding(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_RoleList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleList) + out := out.(*RoleList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Role, len(*in)) + for i := range *in { + if err := DeepCopy_v1alpha1_Role(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_v1alpha1_Subject(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Subject) + out := out.(*Subject) + out.Kind = in.Kind + out.APIVersion = in.APIVersion + out.Name = in.Name + out.Namespace = in.Namespace + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/cast.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/cast.go index 1f5e83fdcbd6..77edea1a0fe9 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/cast.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/cast.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/policy_comparator.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/policy_comparator.go index 1e5e74faa175..53dcba5bc601 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/policy_comparator.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/policy_comparator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,7 +16,11 @@ limitations under the License. package validation -import "k8s.io/kubernetes/pkg/apis/rbac" +import ( + "strings" + + "k8s.io/kubernetes/pkg/apis/rbac" +) // Covers determines whether or not the ownerRules cover the servantRules in terms of allowed actions. // It returns whether or not the ownerRules cover and a list of the rules that the ownerRules do not cover. @@ -69,9 +73,11 @@ func breakdownRule(rule rbac.PolicyRule) []rbac.PolicyRule { } } - // Non-resource URLs are unique because they don't combine with other policy rule fields. + // Non-resource URLs are unique because they only combine with verbs. for _, nonResourceURL := range rule.NonResourceURLs { - subrules = append(subrules, rbac.PolicyRule{NonResourceURLs: []string{nonResourceURL}}) + for _, verb := range rule.Verbs { + subrules = append(subrules, rbac.PolicyRule{NonResourceURLs: []string{nonResourceURL}, Verbs: []string{verb}}) + } } return subrules @@ -99,6 +105,29 @@ func hasAll(set, contains []string) bool { return true } +func nonResourceURLsCoversAll(set, covers []string) bool { + for _, path := range covers { + covered := false + for _, owner := range set { + if nonResourceURLCovers(owner, path) { + covered = true + break + } + } + if !covered { + return false + } + } + return true +} + +func nonResourceURLCovers(ownerPath, subPath string) bool { + if ownerPath == subPath { + return true + } + return strings.HasSuffix(ownerPath, "*") && strings.HasPrefix(subPath, strings.TrimRight(ownerPath, "*")) +} + // ruleCovers determines whether the ownerRule (which may have multiple verbs, resources, and resourceNames) covers // the subrule (which may only contain at most one verb, resource, and resourceName) func ruleCovers(ownerRule, subRule rbac.PolicyRule) bool { @@ -106,7 +135,7 @@ func ruleCovers(ownerRule, subRule rbac.PolicyRule) bool { verbMatches := has(ownerRule.Verbs, rbac.VerbAll) || hasAll(ownerRule.Verbs, subRule.Verbs) groupMatches := has(ownerRule.APIGroups, rbac.APIGroupAll) || hasAll(ownerRule.APIGroups, subRule.APIGroups) resourceMatches := has(ownerRule.Resources, rbac.ResourceAll) || hasAll(ownerRule.Resources, subRule.Resources) - nonResourceURLMatches := has(ownerRule.NonResourceURLs, rbac.NonResourceAll) || hasAll(ownerRule.NonResourceURLs, subRule.NonResourceURLs) + nonResourceURLMatches := nonResourceURLsCoversAll(ownerRule.NonResourceURLs, subRule.NonResourceURLs) resourceNameMatches := false diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/rulevalidation.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/rulevalidation.go index 57c1db93619e..60490fee1a12 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/rulevalidation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/rulevalidation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/validation.go index c43f733037b8..574a7b6dedbc 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apis/rbac/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/apis/rbac/zz_generated.deepcopy.go new file mode 100644 index 000000000000..72026d9bb112 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/apis/rbac/zz_generated.deepcopy.go @@ -0,0 +1,282 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package rbac + +import ( + api "k8s.io/kubernetes/pkg/api" + conversion "k8s.io/kubernetes/pkg/conversion" + runtime "k8s.io/kubernetes/pkg/runtime" + reflect "reflect" +) + +func init() { + if err := api.Scheme.AddGeneratedDeepCopyFuncs( + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_ClusterRole, InType: reflect.TypeOf(func() *ClusterRole { var x *ClusterRole; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_ClusterRoleBinding, InType: reflect.TypeOf(func() *ClusterRoleBinding { var x *ClusterRoleBinding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_ClusterRoleBindingList, InType: reflect.TypeOf(func() *ClusterRoleBindingList { var x *ClusterRoleBindingList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_ClusterRoleList, InType: reflect.TypeOf(func() *ClusterRoleList { var x *ClusterRoleList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_PolicyRule, InType: reflect.TypeOf(func() *PolicyRule { var x *PolicyRule; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_Role, InType: reflect.TypeOf(func() *Role { var x *Role; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_RoleBinding, InType: reflect.TypeOf(func() *RoleBinding { var x *RoleBinding; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_RoleBindingList, InType: reflect.TypeOf(func() *RoleBindingList { var x *RoleBindingList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_RoleList, InType: reflect.TypeOf(func() *RoleList { var x *RoleList; return x }())}, + conversion.GeneratedDeepCopyFunc{Fn: DeepCopy_rbac_Subject, InType: reflect.TypeOf(func() *Subject { var x *Subject; return x }())}, + ); err != nil { + // if one of the deep copy functions is malformed, detect it immediately. + panic(err) + } +} + +func DeepCopy_rbac_ClusterRole(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRole) + out := out.(*ClusterRole) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]PolicyRule, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_PolicyRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_rbac_ClusterRoleBinding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleBinding) + out := out.(*ClusterRoleBinding) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subjects != nil { + in, out := &in.Subjects, &out.Subjects + *out = make([]Subject, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Subjects = nil + } + out.RoleRef = in.RoleRef + return nil + } +} + +func DeepCopy_rbac_ClusterRoleBindingList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleBindingList) + out := out.(*ClusterRoleBindingList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterRoleBinding, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_ClusterRoleBinding(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_rbac_ClusterRoleList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*ClusterRoleList) + out := out.(*ClusterRoleList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterRole, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_ClusterRole(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_rbac_PolicyRule(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*PolicyRule) + out := out.(*PolicyRule) + if in.Verbs != nil { + in, out := &in.Verbs, &out.Verbs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Verbs = nil + } + if in.AttributeRestrictions == nil { + out.AttributeRestrictions = nil + } else if newVal, err := c.DeepCopy(&in.AttributeRestrictions); err != nil { + return err + } else { + out.AttributeRestrictions = *newVal.(*runtime.Object) + } + if in.APIGroups != nil { + in, out := &in.APIGroups, &out.APIGroups + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.APIGroups = nil + } + if in.Resources != nil { + in, out := &in.Resources, &out.Resources + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.Resources = nil + } + if in.ResourceNames != nil { + in, out := &in.ResourceNames, &out.ResourceNames + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.ResourceNames = nil + } + if in.NonResourceURLs != nil { + in, out := &in.NonResourceURLs, &out.NonResourceURLs + *out = make([]string, len(*in)) + copy(*out, *in) + } else { + out.NonResourceURLs = nil + } + return nil + } +} + +func DeepCopy_rbac_Role(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Role) + out := out.(*Role) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]PolicyRule, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_PolicyRule(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Rules = nil + } + return nil + } +} + +func DeepCopy_rbac_RoleBinding(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleBinding) + out := out.(*RoleBinding) + out.TypeMeta = in.TypeMeta + if err := api.DeepCopy_api_ObjectMeta(&in.ObjectMeta, &out.ObjectMeta, c); err != nil { + return err + } + if in.Subjects != nil { + in, out := &in.Subjects, &out.Subjects + *out = make([]Subject, len(*in)) + for i := range *in { + (*out)[i] = (*in)[i] + } + } else { + out.Subjects = nil + } + out.RoleRef = in.RoleRef + return nil + } +} + +func DeepCopy_rbac_RoleBindingList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleBindingList) + out := out.(*RoleBindingList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]RoleBinding, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_RoleBinding(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_rbac_RoleList(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RoleList) + out := out.(*RoleList) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Role, len(*in)) + for i := range *in { + if err := DeepCopy_rbac_Role(&(*in)[i], &(*out)[i], c); err != nil { + return err + } + } + } else { + out.Items = nil + } + return nil + } +} + +func DeepCopy_rbac_Subject(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Subject) + out := out.(*Subject) + out.Kind = in.Kind + out.APIVersion = in.APIVersion + out.Name = in.Name + out.Namespace = in.Namespace + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/api_installer.go b/vendor/k8s.io/kubernetes/pkg/apiserver/api_installer.go index 30690dd7c0e1..49be3ca3fad2 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/api_installer.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/api_installer.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/apiserver.go b/vendor/k8s.io/kubernetes/pkg/apiserver/apiserver.go index 9a72bad6b048..1876016522a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/apiserver.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/apiserver.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -166,7 +166,6 @@ func (g *APIGroupVersion) newInstaller() *APIInstaller { // TODO: document all handlers // InstallVersionHandler registers the APIServer's `/version` handler func InstallVersionHandler(mux Mux, container *restful.Container) { - // Set up a service to return the git code version. versionWS := new(restful.WebService) versionWS.Path("/version") diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/authenticator/authn.go b/vendor/k8s.io/kubernetes/pkg/apiserver/authenticator/authn.go index 56dfcf8ad121..feba1dbef821 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/authenticator/authn.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/authenticator/authn.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -156,8 +156,6 @@ func newAuthenticatorFromOIDCIssuerURL(issuerURL, clientID, caFile, usernameClai CAFile: caFile, UsernameClaim: usernameClaim, GroupsClaim: groupsClaim, - MaxRetries: oidc.DefaultRetries, - RetryBackoff: oidc.DefaultBackoff, }) if err != nil { return nil, err diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/authz.go b/vendor/k8s.io/kubernetes/pkg/apiserver/authz.go index 2e7013df1b3b..7a19f2d4fcd7 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/authz.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/authz.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ type Attributes struct { // It is useful in tests and when using kubernetes in an open manner. type alwaysAllowAuthorizer struct{} -func (alwaysAllowAuthorizer) Authorize(a authorizer.Attributes) (err error) { - return nil +func (alwaysAllowAuthorizer) Authorize(a authorizer.Attributes) (authorized bool, reason string, err error) { + return true, "", nil } func NewAlwaysAllowAuthorizer() authorizer.Authorizer { @@ -55,14 +55,27 @@ func NewAlwaysAllowAuthorizer() authorizer.Authorizer { // It is useful in unit tests to force an operation to be forbidden. type alwaysDenyAuthorizer struct{} -func (alwaysDenyAuthorizer) Authorize(a authorizer.Attributes) (err error) { - return errors.New("Everything is forbidden.") +func (alwaysDenyAuthorizer) Authorize(a authorizer.Attributes) (authorized bool, reason string, err error) { + return false, "Everything is forbidden.", nil } func NewAlwaysDenyAuthorizer() authorizer.Authorizer { return new(alwaysDenyAuthorizer) } +// alwaysFailAuthorizer is an implementation of authorizer.Attributes +// which always says no to an authorization request. +// It is useful in unit tests to force an operation to fail with error. +type alwaysFailAuthorizer struct{} + +func (alwaysFailAuthorizer) Authorize(a authorizer.Attributes) (authorized bool, reason string, err error) { + return false, "", errors.New("Authorization failure.") +} + +func NewAlwaysFailAuthorizer() authorizer.Authorizer { + return new(alwaysFailAuthorizer) +} + const ( ModeAlwaysAllow string = "AlwaysAllow" ModeAlwaysDeny string = "AlwaysDeny" diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/doc.go b/vendor/k8s.io/kubernetes/pkg/apiserver/doc.go index 7a919d2ca618..df1224d97133 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/errors.go b/vendor/k8s.io/kubernetes/pkg/apiserver/errors.go old mode 100644 new mode 100755 index 4f9d16a26881..e75e4bd826a4 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -88,6 +88,13 @@ func forbidden(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Forbidden: %#v", req.RequestURI) } +// internalError renders a simple internal error +func internalError(w http.ResponseWriter, req *http.Request, err error) { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, "Internal Server Error: %#v", req.RequestURI) + runtime.HandleError(err) +} + // errAPIPrefixNotFound indicates that a RequestInfo resolution failed because the request isn't under // any known API prefixes type errAPIPrefixNotFound struct { @@ -126,7 +133,7 @@ func (e errNotAcceptable) Status() unversioned.Status { } } -// errNotAcceptable indicates Content-Type is not recognized +// errUnsupportedMediaType indicates Content-Type is not recognized // TODO: move to api/errors if other code needs to return this type errUnsupportedMediaType struct { accepted []string diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/handlers.go b/vendor/k8s.io/kubernetes/pkg/apiserver/handlers.go index 64c839746712..4f593127361a 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/handlers.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/handlers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import ( "k8s.io/kubernetes/pkg/auth/user" "k8s.io/kubernetes/pkg/httplog" "k8s.io/kubernetes/pkg/serviceaccount" + "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" ) @@ -137,12 +138,10 @@ func tooManyRequests(req *http.Request, w http.ResponseWriter) { // RecoverPanics wraps an http Handler to recover and log panics. func RecoverPanics(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - defer func() { - if x := recover(); x != nil { - http.Error(w, "apis panic. Look in log for details.", http.StatusInternalServerError) - glog.Errorf("APIServer panic'd on %v %v: %v\n%s\n", req.Method, req.RequestURI, x, debug.Stack()) - } - }() + defer runtime.HandleCrash(func(err interface{}) { + http.Error(w, "This request caused apisever to panic. Look in log for details.", http.StatusInternalServerError) + glog.Errorf("APIServer panic'd on %v %v: %v\n%s\n", req.Method, req.RequestURI, err, debug.Stack()) + }) defer httplog.NewLogged(req, &w).StacktraceWhen( httplog.StatusIsNot( http.StatusOK, @@ -447,8 +446,13 @@ func WithImpersonation(handler http.Handler, requestContextMapper api.RequestCon actingAsAttributes.Name = name } - err := a.Authorize(actingAsAttributes) + authorized, reason, err := a.Authorize(actingAsAttributes) if err != nil { + internalError(w, req, err) + return + } + if !authorized { + glog.V(4).Infof("Forbidden: %#v, Reason: %s", req.RequestURI, reason) forbidden(w, req) return } @@ -481,12 +485,17 @@ func WithImpersonation(handler http.Handler, requestContextMapper api.RequestCon // WithAuthorizationCheck passes all authorized requests on to handler, and returns a forbidden error otherwise. func WithAuthorizationCheck(handler http.Handler, getAttribs RequestAttributeGetter, a authorizer.Authorizer) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - err := a.Authorize(getAttribs.GetAttribs(req)) - if err == nil { - handler.ServeHTTP(w, req) + authorized, reason, err := a.Authorize(getAttribs.GetAttribs(req)) + if err != nil { + internalError(w, req, err) return } - forbidden(w, req) + if !authorized { + glog.V(4).Infof("Forbidden: %#v, Reason: %s", req.RequestURI, reason) + forbidden(w, req) + return + } + handler.ServeHTTP(w, req) }) } diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/index.go b/vendor/k8s.io/kubernetes/pkg/apiserver/index.go index c01174d75d19..eaeeb92e41f3 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/index.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/index.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/metrics/metrics.go b/vendor/k8s.io/kubernetes/pkg/apiserver/metrics/metrics.go index dc7fe7009aef..15c5173078ba 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/metrics/metrics.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/metrics/metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/mux_helper.go b/vendor/k8s.io/kubernetes/pkg/apiserver/mux_helper.go index 48953321c13d..d8e2388f53f4 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/mux_helper.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/mux_helper.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/negotiate.go b/vendor/k8s.io/kubernetes/pkg/apiserver/negotiate.go index a9fedfc9af6a..f51e68ad2755 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/negotiate.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/negotiate.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/proxy.go b/vendor/k8s.io/kubernetes/pkg/apiserver/proxy.go index 4b3d00d77de4..403d219ee939 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/proxy.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/proxy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/resthandler.go b/vendor/k8s.io/kubernetes/pkg/apiserver/resthandler.go index c59183735603..7cbb05a21f97 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/resthandler.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/resthandler.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/validator.go b/vendor/k8s.io/kubernetes/pkg/apiserver/validator.go index 05fa79bf2ffe..7e155013fa7c 100644 --- a/vendor/k8s.io/kubernetes/pkg/apiserver/validator.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/validator.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/apiserver/watch.go b/vendor/k8s.io/kubernetes/pkg/apiserver/watch.go old mode 100644 new mode 100755 index 220074edf296..fb57f33119df --- a/vendor/k8s.io/kubernetes/pkg/apiserver/watch.go +++ b/vendor/k8s.io/kubernetes/pkg/apiserver/watch.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -120,7 +120,7 @@ type WatchServer struct { t timeoutFactory } -// Serve serves a series of encoded events via HTTP with Transfer-Encoding: chunked +// ServeHTTP serves a series of encoded events via HTTP with Transfer-Encoding: chunked // or over a websocket connection. func (s *WatchServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { w = httplog.Unlogged(w) diff --git a/vendor/k8s.io/kubernetes/pkg/auth/authenticator/bearertoken/bearertoken.go b/vendor/k8s.io/kubernetes/pkg/auth/authenticator/bearertoken/bearertoken.go index eff338bfba83..35f523d6820e 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/authenticator/bearertoken/bearertoken.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/authenticator/bearertoken/bearertoken.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/auth/authenticator/interfaces.go b/vendor/k8s.io/kubernetes/pkg/auth/authenticator/interfaces.go index 2da820cc0894..1eafe605c610 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/authenticator/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/authenticator/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/abac/abac.go b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/abac/abac.go index c3bfedcc4d8e..75db334e819b 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/abac/abac.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/abac/abac.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ package abac import ( "bufio" - "errors" "fmt" "os" "strings" @@ -133,12 +132,19 @@ func matches(p api.Policy, a authorizer.Attributes) bool { func subjectMatches(p api.Policy, a authorizer.Attributes) bool { matched := false + username := "" + groups := []string{} + if user := a.GetUser(); user != nil { + username = user.GetName() + groups = user.GetGroups() + } + // If the policy specified a user, ensure it matches if len(p.Spec.User) > 0 { if p.Spec.User == "*" { matched = true } else { - matched = p.Spec.User == a.GetUserName() + matched = p.Spec.User == username if !matched { return false } @@ -151,7 +157,7 @@ func subjectMatches(p api.Policy, a authorizer.Attributes) bool { matched = true } else { matched = false - for _, group := range a.GetGroups() { + for _, group := range groups { if p.Spec.Group == group { matched = true } @@ -215,13 +221,13 @@ func resourceMatches(p api.Policy, a authorizer.Attributes) bool { } // Authorizer implements authorizer.Authorize -func (pl policyList) Authorize(a authorizer.Attributes) error { +func (pl policyList) Authorize(a authorizer.Attributes) (bool, string, error) { for _, p := range pl { if matches(*p, a) { - return nil + return true, "", nil } } - return errors.New("No policy matched.") + return false, "No policy matched.", nil // TODO: Benchmark how much time policy matching takes with a medium size // policy file, compared to other steps such as encoding/decoding. // Then, add Caching only if needed. diff --git a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/interfaces.go b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/interfaces.go index d4f02efbd4ad..e23ea45960b9 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,14 +25,8 @@ import ( // Attributes is an interface used by an Authorizer to get information about a request // that is used to make an authorization decision. type Attributes interface { - // The user string which the request was authenticated as, or empty if - // no authentication occurred and the request was allowed to proceed. - GetUserName() string - - // The list of group names the authenticated user is a member of. Can be - // empty if the authenticated user is not in any groups, or if no - // authentication occurred. - GetGroups() []string + // GetUser returns the user.Info object to authorize + GetUser() user.Info // GetVerb returns the kube verb associated with API requests (this includes get, list, watch, create, update, patch, delete, and proxy), // or the lowercased HTTP verb associated with non-API requests (this includes get, put, post, patch, and delete) @@ -73,12 +67,12 @@ type Attributes interface { // zero or more calls to methods of the Attributes interface. It returns nil when an action is // authorized, otherwise it returns an error. type Authorizer interface { - Authorize(a Attributes) (err error) + Authorize(a Attributes) (authorized bool, reason string, err error) } -type AuthorizerFunc func(a Attributes) error +type AuthorizerFunc func(a Attributes) (bool, string, error) -func (f AuthorizerFunc) Authorize(a Attributes) error { +func (f AuthorizerFunc) Authorize(a Attributes) (bool, string, error) { return f(a) } @@ -101,12 +95,8 @@ type AttributesRecord struct { Path string } -func (a AttributesRecord) GetUserName() string { - return a.User.GetName() -} - -func (a AttributesRecord) GetGroups() []string { - return a.User.GetGroups() +func (a AttributesRecord) GetUser() user.Info { + return a.User } func (a AttributesRecord) GetVerb() string { diff --git a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/union/union.go b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/union/union.go index 255ad0823ac7..880d8c79eb39 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/authorizer/union/union.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/authorizer/union/union.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,6 +17,8 @@ limitations under the License. package union import ( + "strings" + "k8s.io/kubernetes/pkg/auth/authorizer" utilerrors "k8s.io/kubernetes/pkg/util/errors" ) @@ -30,16 +32,26 @@ func New(authorizationHandlers ...authorizer.Authorizer) authorizer.Authorizer { } // Authorizes against a chain of authorizer.Authorizer objects and returns nil if successful and returns error if unsuccessful -func (authzHandler unionAuthzHandler) Authorize(a authorizer.Attributes) error { - var errlist []error +func (authzHandler unionAuthzHandler) Authorize(a authorizer.Attributes) (bool, string, error) { + var ( + errlist []error + reasonlist []string + ) for _, currAuthzHandler := range authzHandler { - err := currAuthzHandler.Authorize(a) + authorized, reason, err := currAuthzHandler.Authorize(a) + if err != nil { errlist = append(errlist, err) continue } - return nil + if !authorized { + if reason != "" { + reasonlist = append(reasonlist, reason) + } + continue + } + return true, reason, nil } - return utilerrors.NewAggregate(errlist) + return false, strings.Join(reasonlist, "\n"), utilerrors.NewAggregate(errlist) } diff --git a/vendor/k8s.io/kubernetes/pkg/auth/handlers/handlers.go b/vendor/k8s.io/kubernetes/pkg/auth/handlers/handlers.go index d005752f16a7..0f6e226e9c01 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/handlers/handlers.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/handlers/handlers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/auth/user/doc.go b/vendor/k8s.io/kubernetes/pkg/auth/user/doc.go index b11258494e7c..570c51ae995d 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/user/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/user/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/auth/user/user.go b/vendor/k8s.io/kubernetes/pkg/auth/user/user.go index c4a4c00d5bff..99261965d810 100644 --- a/vendor/k8s.io/kubernetes/pkg/auth/user/user.go +++ b/vendor/k8s.io/kubernetes/pkg/auth/user/user.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities.go b/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities.go index d0a882c54782..96146c6b0933 100644 --- a/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities.go +++ b/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ func Initialize(c Capabilities) { }) } -// Setup the capability set. It wraps Initialize for improving usibility. +// Setup the capability set. It wraps Initialize for improving usability. func Setup(allowPrivileged bool, privilegedSources PrivilegedSources, perConnectionBytesPerSec int64) { Initialize(Capabilities{ AllowPrivileged: allowPrivileged, diff --git a/vendor/k8s.io/kubernetes/pkg/capabilities/doc.go b/vendor/k8s.io/kubernetes/pkg/capabilities/doc.go index 81143a78e1fa..e2042a881e9f 100644 --- a/vendor/k8s.io/kubernetes/pkg/capabilities/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/capabilities/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,5 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package capbabilities manages system level capabilities +// package capabilities manages system level capabilities package capabilities diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/delta_fifo.go b/vendor/k8s.io/kubernetes/pkg/client/cache/delta_fifo.go index 3cb077faf7e6..5a7f4a90f623 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/delta_fifo.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/delta_fifo.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -228,15 +228,21 @@ func (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error { } f.lock.Lock() defer f.lock.Unlock() + f.addIfNotPresent(id, deltas) + return nil +} + +// addIfNotPresent inserts deltas under id if it does not exist, and assumes the caller +// already holds the fifo lock. +func (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas) { f.populated = true if _, exists := f.items[id]; exists { - return nil + return } f.queue = append(f.queue, id) f.items[id] = deltas f.cond.Broadcast() - return nil } // re-listing and watching can deliver the same update multiple times in any @@ -387,7 +393,9 @@ func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err err // is returned, so if you don't successfully process it, you need to add it back // with AddIfNotPresent(). // process function is called under lock, so it is safe update data structures -// in it that need to be in sync with the queue (e.g. knownKeys). +// in it that need to be in sync with the queue (e.g. knownKeys). The PopProcessFunc +// may return an instance of ErrRequeue with a nested error to indicate the current +// item should be requeued (equivalent to calling AddIfNotPresent under the lock). // // Pop returns a 'Deltas', which has a complete list of all the things // that happened to the object (deltas) while it was sitting in the queue. @@ -409,9 +417,14 @@ func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) { continue } delete(f.items, id) + err := process(item) + if e, ok := err.(ErrRequeue); ok { + f.addIfNotPresent(id, item) + err = e.Err + } // Don't need to copyDeltas here, because we're transferring // ownership to the caller. - return item, process(item) + return item, err } } diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/doc.go b/vendor/k8s.io/kubernetes/pkg/client/cache/doc.go index 16600cf24238..4f593f0d3d8a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go b/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go index ad8684e8c377..88ef89b3ee91 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ( "time" "github.com/golang/glog" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" ) // ExpirationCache implements the store interface @@ -38,7 +38,7 @@ import ( type ExpirationCache struct { cacheStorage ThreadSafeStore keyFunc KeyFunc - clock util.Clock + clock clock.Clock expirationPolicy ExpirationPolicy // expirationLock is a write lock used to guarantee that we don't clobber // newly inserted objects because of a stale expiration timestamp comparison @@ -58,7 +58,7 @@ type TTLPolicy struct { Ttl time.Duration // Clock used to calculate ttl expiration - Clock util.Clock + Clock clock.Clock } // IsExpired returns true if the given object is older than the ttl, or it can't @@ -73,7 +73,7 @@ type timestampedEntry struct { timestamp time.Time } -// getTimestampedEntry returnes the timestampedEntry stored under the given key. +// getTimestampedEntry returns the timestampedEntry stored under the given key. func (c *ExpirationCache) getTimestampedEntry(key string) (*timestampedEntry, bool) { item, _ := c.cacheStorage.Get(key) if tsEntry, ok := item.(*timestampedEntry); ok { @@ -202,7 +202,7 @@ func NewTTLStore(keyFunc KeyFunc, ttl time.Duration) Store { return &ExpirationCache{ cacheStorage: NewThreadSafeStore(Indexers{}, Indices{}), keyFunc: keyFunc, - clock: util.RealClock{}, - expirationPolicy: &TTLPolicy{ttl, util.RealClock{}}, + clock: clock.RealClock{}, + expirationPolicy: &TTLPolicy{ttl, clock.RealClock{}}, } } diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go b/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go index 3b95977050e1..da180b77f1c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/expiration_cache_fakes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ limitations under the License. package cache import ( - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/sets" ) @@ -43,7 +43,7 @@ func (p *FakeExpirationPolicy) IsExpired(obj *timestampedEntry) bool { return !p.NeverExpire.Has(key) } -func NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock util.Clock) Store { +func NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store { cacheStorage := NewThreadSafeStore(Indexers{}, Indices{}) return &ExpirationCache{ cacheStorage: &fakeThreadSafeMap{cacheStorage, deletedKeys}, diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/fake_custom_store.go b/vendor/k8s.io/kubernetes/pkg/client/cache/fake_custom_store.go index ccd69ef7bfdd..8d71c247497a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/fake_custom_store.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/fake_custom_store.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/fifo.go b/vendor/k8s.io/kubernetes/pkg/client/cache/fifo.go index eaa35e62cb67..a6d5e0ab839b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/fifo.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/fifo.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,12 +26,28 @@ import ( // It is supposed to process the element popped from the queue. type PopProcessFunc func(interface{}) error +// ErrRequeue may be returned by a PopProcessFunc to safely requeue +// the current item. The value of Err will be returned from Pop. +type ErrRequeue struct { + // Err is returned by the Pop function + Err error +} + +func (e ErrRequeue) Error() string { + if e.Err == nil { + return "the popped item should be requeued without returning an error" + } + return e.Err.Error() +} + // Queue is exactly like a Store, but has a Pop() method too. type Queue interface { Store // Pop blocks until it has something to process. // It returns the object that was process and the result of processing. + // The PopProcessFunc may return an ErrRequeue{...} to indicate the item + // should be requeued before releasing the lock on the queue. Pop(PopProcessFunc) (interface{}, error) // AddIfNotPresent adds a value previously @@ -129,15 +145,21 @@ func (f *FIFO) AddIfNotPresent(obj interface{}) error { } f.lock.Lock() defer f.lock.Unlock() + f.addIfNotPresent(id, obj) + return nil +} + +// addIfNotPresent assumes the fifo lock is already held and adds the the provided +// item to the queue under id if it does not already exist. +func (f *FIFO) addIfNotPresent(id string, obj interface{}) { f.populated = true if _, exists := f.items[id]; exists { - return nil + return } f.queue = append(f.queue, id) f.items[id] = obj f.cond.Broadcast() - return nil } // Update is the same as Add in this implementation. @@ -224,7 +246,12 @@ func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) { continue } delete(f.items, id) - return item, process(item) + err := process(item) + if e, ok := err.(ErrRequeue); ok { + f.addIfNotPresent(id, item) + err = e.Err + } + return item, err } } diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/index.go b/vendor/k8s.io/kubernetes/pkg/client/cache/index.go index 572f2c06b69e..437988050ac0 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/index.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/index.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/listers.go b/vendor/k8s.io/kubernetes/pkg/client/cache/listers.go index 90c9c62f9b72..4b96cf43cbd1 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/listers.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/listers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/apps" "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/apis/certificates" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/labels" ) @@ -122,7 +123,7 @@ func (s *StoreToPodLister) Exists(pod *api.Pod) (bool, error) { // NodeConditionPredicate is a function that indicates whether the given node's conditions meet // some set of criteria defined by the function. -type NodeConditionPredicate func(node api.Node) bool +type NodeConditionPredicate func(node *api.Node) bool // StoreToNodeLister makes a Store have the List method of the client.NodeInterface // The Store must contain (only) Nodes. @@ -151,11 +152,11 @@ type storeToNodeConditionLister struct { } // List returns a list of nodes that match the conditions defined by the predicate functions in the storeToNodeConditionLister. -func (s storeToNodeConditionLister) List() (nodes api.NodeList, err error) { +func (s storeToNodeConditionLister) List() (nodes []*api.Node, err error) { for _, m := range s.store.List() { - node := *m.(*api.Node) + node := m.(*api.Node) if s.predicate(node) { - nodes.Items = append(nodes.Items, node) + nodes = append(nodes, node) } else { glog.V(5).Infof("Node %s matches none of the conditions", node.Name) } @@ -670,3 +671,42 @@ func (s *StoreToPetSetLister) GetPodPetSets(pod *api.Pod) (psList []apps.PetSet, } return } + +// StoreToCertificateRequestLister gives a store List and Exists methods. The store must contain only CertificateRequests. +type StoreToCertificateRequestLister struct { + Store +} + +// Exists checks if the given csr exists in the store. +func (s *StoreToCertificateRequestLister) Exists(csr *certificates.CertificateSigningRequest) (bool, error) { + _, exists, err := s.Store.Get(csr) + if err != nil { + return false, err + } + return exists, nil +} + +// StoreToCertificateRequestLister lists all csrs in the store. +func (s *StoreToCertificateRequestLister) List() (csrs certificates.CertificateSigningRequestList, err error) { + for _, c := range s.Store.List() { + csrs.Items = append(csrs.Items, *(c.(*certificates.CertificateSigningRequest))) + } + return csrs, nil +} + +// IndexerToNamespaceLister gives an Indexer List method +type IndexerToNamespaceLister struct { + Indexer +} + +// List returns a list of namespaces +func (i *IndexerToNamespaceLister) List(selector labels.Selector) (namespaces []*api.Namespace, err error) { + for _, m := range i.Indexer.List() { + namespace := m.(*api.Namespace) + if selector.Matches(labels.Set(namespace.Labels)) { + namespaces = append(namespaces, namespace) + } + } + + return namespaces, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/listwatch.go b/vendor/k8s.io/kubernetes/pkg/client/cache/listwatch.go index 06c2f611bf66..ff56c0b7bf4f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/listwatch.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/listwatch.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go b/vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go index 3a5025a28a7e..7e6adf404a3e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/reflector.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -164,7 +164,7 @@ func hasPackage(file string, ignoredPackages []string) bool { return false } -// trimPackagePrefix reduces dulpicate values off the front of a package name. +// trimPackagePrefix reduces duplicate values off the front of a package name. func trimPackagePrefix(file string) string { if l := strings.LastIndex(file, "k8s.io/kubernetes/pkg/"); l >= 0 { return file[l+len("k8s.io/kubernetes/"):] diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/store.go b/vendor/k8s.io/kubernetes/pkg/client/cache/store.go old mode 100644 new mode 100755 index 71115f2ce5dd..4cd2479bdc53 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/store.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/store.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -99,7 +99,7 @@ func SplitMetaNamespaceKey(key string) (namespace, name string, err error) { // name only, no namespace return "", parts[0], nil case 2: - // name and namespace + // namespace and name return parts[0], parts[1], nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/thread_safe_store.go b/vendor/k8s.io/kubernetes/pkg/client/cache/thread_safe_store.go index 11077e25b2ee..9d88ce33df3c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/thread_safe_store.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/thread_safe_store.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -261,12 +261,13 @@ func (c *threadSafeMap) deleteFromIndices(obj interface{}, key string) error { } index := c.indices[name] + if index == nil { + continue + } for _, indexValue := range indexValues { - if index != nil { - set := index[indexValue] - if set != nil { - set.Delete(key) - } + set := index[indexValue] + if set != nil { + set.Delete(key) } } } diff --git a/vendor/k8s.io/kubernetes/pkg/client/cache/undelta_store.go b/vendor/k8s.io/kubernetes/pkg/client/cache/undelta_store.go index 4a8a4500e343..117df46c48d2 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/cache/undelta_store.go +++ b/vendor/k8s.io/kubernetes/pkg/client/cache/undelta_store.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/chaosclient/chaosclient.go b/vendor/k8s.io/kubernetes/pkg/client/chaosclient/chaosclient.go index a0ed4b4c157a..18fc9bbc3345 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/chaosclient/chaosclient.go +++ b/vendor/k8s.io/kubernetes/pkg/client/chaosclient/chaosclient.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go index 8b958a581ce9..010dd530369d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/clientset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import ( "github.com/golang/glog" unversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned" unversionedbatch "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned" + unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned" unversionedrbac "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned" @@ -35,6 +36,7 @@ type Interface interface { Autoscaling() unversionedautoscaling.AutoscalingInterface Batch() unversionedbatch.BatchInterface Rbac() unversionedrbac.RbacInterface + Certificates() unversionedcertificates.CertificatesInterface } // Clientset contains the clients for groups. Each group has exactly one @@ -46,6 +48,7 @@ type Clientset struct { *unversionedautoscaling.AutoscalingClient *unversionedbatch.BatchClient *unversionedrbac.RbacClient + *unversionedcertificates.CertificatesClient } // Core retrieves the CoreClient @@ -88,6 +91,14 @@ func (c *Clientset) Rbac() unversionedrbac.RbacInterface { return c.RbacClient } +// Certificates retrieves the CertificatesClient +func (c *Clientset) Certificates() unversionedcertificates.CertificatesInterface { + if c == nil { + return nil + } + return c.CertificatesClient +} + // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { return c.DiscoveryClient @@ -121,6 +132,10 @@ func NewForConfig(c *restclient.Config) (*Clientset, error) { if err != nil { return nil, err } + clientset.CertificatesClient, err = unversionedcertificates.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } clientset.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { @@ -139,6 +154,7 @@ func NewForConfigOrDie(c *restclient.Config) *Clientset { clientset.AutoscalingClient = unversionedautoscaling.NewForConfigOrDie(c) clientset.BatchClient = unversionedbatch.NewForConfigOrDie(c) clientset.RbacClient = unversionedrbac.NewForConfigOrDie(c) + clientset.CertificatesClient = unversionedcertificates.NewForConfigOrDie(c) clientset.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &clientset @@ -152,6 +168,7 @@ func New(c *restclient.RESTClient) *Clientset { clientset.AutoscalingClient = unversionedautoscaling.New(c) clientset.BatchClient = unversionedbatch.New(c) clientset.RbacClient = unversionedrbac.New(c) + clientset.CertificatesClient = unversionedcertificates.New(c) clientset.DiscoveryClient = discovery.NewDiscoveryClient(c) return &clientset diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/doc.go index 3934caa42ca9..cf081af2ca60 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go index 699b2f4e153f..8d18af79b814 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/clientset_generated.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,8 @@ import ( fakeunversionedautoscaling "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake" unversionedbatch "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned" fakeunversionedbatch "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake" + unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned" + fakeunversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" fakeunversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake" unversionedextensions "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned" @@ -37,9 +39,12 @@ import ( "k8s.io/kubernetes/pkg/watch" ) -// Clientset returns a clientset that will respond with the provided objects +// NewSimpleClientset returns a clientset that will respond with the provided objects. +// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, +// without applying any validations and/or defaults. It shouldn't be considered a replacement +// for a real clientset and is mostly useful in simple unit tests. func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := core.NewObjects(api.Scheme, api.Codecs.UniversalDecoder()) + o := core.NewObjectTracker(api.Scheme, api.Codecs.UniversalDecoder()) for _, obj := range objects { if err := o.Add(obj); err != nil { panic(err) @@ -91,3 +96,8 @@ func (c *Clientset) Batch() unversionedbatch.BatchInterface { func (c *Clientset) Rbac() unversionedrbac.RbacInterface { return &fakeunversionedrbac.FakeRbac{Fake: &c.Fake} } + +// Certificates retrieves the CertificatesClient +func (c *Clientset) Certificates() unversionedcertificates.CertificatesInterface { + return &fakeunversionedcertificates.FakeCertificates{Fake: &c.Fake} +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/doc.go index 559cf8914e1e..937b6ba85222 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/import_known_versions.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/import_known_versions.go index 8bdbe2e6c989..4a922df8ad4a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/import_known_versions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/import_known_versions.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( _ "k8s.io/kubernetes/pkg/apis/authorization/install" _ "k8s.io/kubernetes/pkg/apis/autoscaling/install" _ "k8s.io/kubernetes/pkg/apis/batch/install" + _ "k8s.io/kubernetes/pkg/apis/certificates/install" _ "k8s.io/kubernetes/pkg/apis/componentconfig/install" _ "k8s.io/kubernetes/pkg/apis/extensions/install" _ "k8s.io/kubernetes/pkg/apis/policy/install" diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/autoscaling_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/autoscaling_client.go index 752b5d554e25..71d01ff6dd86 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/autoscaling_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/autoscaling_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/doc.go index 47517b6422dd..1e6a8ff827b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/doc.go index eb358c26c80f..083f78f3a401 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_autoscaling_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_autoscaling_client.go index d25beeebbaed..ab10c6bb0e0e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_autoscaling_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_autoscaling_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_horizontalpodautoscaler.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_horizontalpodautoscaler.go index fb889a446a06..1d97e2383cae 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_horizontalpodautoscaler.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/fake/fake_horizontalpodautoscaler.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeHorizontalPodAutoscalers) Watch(opts api.ListOptions) (watch.Interf InvokesWatch(core.NewWatchAction(horizontalpodautoscalersResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched horizontalPodAutoscaler. +func (c *FakeHorizontalPodAutoscalers) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *autoscaling.HorizontalPodAutoscaler, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(horizontalpodautoscalersResource, c.ns, name, data, subresources...), &autoscaling.HorizontalPodAutoscaler{}) + + if obj == nil { + return nil, err + } + return obj.(*autoscaling.HorizontalPodAutoscaler), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/generated_expansion.go index 39324902aaaf..628b494c0e0b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/generated_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/horizontalpodautoscaler.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/horizontalpodautoscaler.go index ae185ad7fb9b..515be142ede1 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/horizontalpodautoscaler.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/autoscaling/unversioned/horizontalpodautoscaler.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type HorizontalPodAutoscalerInterface interface { Get(name string) (*autoscaling.HorizontalPodAutoscaler, error) List(opts api.ListOptions) (*autoscaling.HorizontalPodAutoscalerList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *autoscaling.HorizontalPodAutoscaler, err error) HorizontalPodAutoscalerExpansion } @@ -148,3 +149,17 @@ func (c *horizontalPodAutoscalers) Watch(opts api.ListOptions) (watch.Interface, VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched horizontalPodAutoscaler. +func (c *horizontalPodAutoscalers) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *autoscaling.HorizontalPodAutoscaler, err error) { + result = &autoscaling.HorizontalPodAutoscaler{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("horizontalpodautoscalers"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/batch_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/batch_client.go index 83d9d749c458..8f2b0e803869 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/batch_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/batch_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/doc.go index 47517b6422dd..1e6a8ff827b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/doc.go index eb358c26c80f..083f78f3a401 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_batch_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_batch_client.go index bf2a41a76a22..b21ca42a40e3 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_batch_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_batch_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_job.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_job.go index 701c102b4119..8cd06b1f5ff1 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_job.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_job.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeJobs) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(jobsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched job. +func (c *FakeJobs) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.Job, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(jobsResource, c.ns, name, data, subresources...), &batch.Job{}) + + if obj == nil { + return nil, err + } + return obj.(*batch.Job), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_scheduledjob.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_scheduledjob.go index db09aa9bc964..c4f467413865 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_scheduledjob.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/fake/fake_scheduledjob.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeScheduledJobs) Watch(opts api.ListOptions) (watch.Interface, error) InvokesWatch(core.NewWatchAction(scheduledjobsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched scheduledJob. +func (c *FakeScheduledJobs) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.ScheduledJob, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(scheduledjobsResource, c.ns, name, data, subresources...), &batch.ScheduledJob{}) + + if obj == nil { + return nil, err + } + return obj.(*batch.ScheduledJob), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/generated_expansion.go index f876ef63fc2a..a12d6f308418 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/generated_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/job.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/job.go index 680c50654c69..8d209fb8d6bf 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/job.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/job.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type JobInterface interface { Get(name string) (*batch.Job, error) List(opts api.ListOptions) (*batch.JobList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.Job, err error) JobExpansion } @@ -148,3 +149,17 @@ func (c *jobs) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched job. +func (c *jobs) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.Job, err error) { + result = &batch.Job{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("jobs"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/scheduledjob.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/scheduledjob.go index 2675d11c48f2..3c3f32ef50fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/scheduledjob.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/unversioned/scheduledjob.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type ScheduledJobInterface interface { Get(name string) (*batch.ScheduledJob, error) List(opts api.ListOptions) (*batch.ScheduledJobList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.ScheduledJob, err error) ScheduledJobExpansion } @@ -148,3 +149,17 @@ func (c *scheduledJobs) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched scheduledJob. +func (c *scheduledJobs) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *batch.ScheduledJob, err error) { + result = &batch.ScheduledJob{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("scheduledjobs"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificates_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificates_client.go new file mode 100644 index 000000000000..f1fdb4559071 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificates_client.go @@ -0,0 +1,101 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + api "k8s.io/kubernetes/pkg/api" + registered "k8s.io/kubernetes/pkg/apimachinery/registered" + restclient "k8s.io/kubernetes/pkg/client/restclient" +) + +type CertificatesInterface interface { + GetRESTClient() *restclient.RESTClient + CertificateSigningRequestsGetter +} + +// CertificatesClient is used to interact with features provided by the Certificates group. +type CertificatesClient struct { + *restclient.RESTClient +} + +func (c *CertificatesClient) CertificateSigningRequests() CertificateSigningRequestInterface { + return newCertificateSigningRequests(c) +} + +// NewForConfig creates a new CertificatesClient for the given config. +func NewForConfig(c *restclient.Config) (*CertificatesClient, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := restclient.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &CertificatesClient{client}, nil +} + +// NewForConfigOrDie creates a new CertificatesClient for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *restclient.Config) *CertificatesClient { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new CertificatesClient for the given RESTClient. +func New(c *restclient.RESTClient) *CertificatesClient { + return &CertificatesClient{c} +} + +func setConfigDefaults(config *restclient.Config) error { + // if certificates group is not registered, return an error + g, err := registered.Group("certificates") + if err != nil { + return err + } + config.APIPath = "/apis" + if config.UserAgent == "" { + config.UserAgent = restclient.DefaultKubernetesUserAgent() + } + // TODO: Unconditionally set the config.Version, until we fix the config. + //if config.Version == "" { + copyGroupVersion := g.GroupVersion + config.GroupVersion = ©GroupVersion + //} + + config.NegotiatedSerializer = api.Codecs + + if config.QPS == 0 { + config.QPS = 5 + } + if config.Burst == 0 { + config.Burst = 10 + } + return nil +} + +// GetRESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *CertificatesClient) GetRESTClient() *restclient.RESTClient { + if c == nil { + return nil + } + return c.RESTClient +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificatesigningrequest.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificatesigningrequest.go new file mode 100644 index 000000000000..e199acf2f663 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/certificatesigningrequest.go @@ -0,0 +1,154 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + api "k8s.io/kubernetes/pkg/api" + certificates "k8s.io/kubernetes/pkg/apis/certificates" + watch "k8s.io/kubernetes/pkg/watch" +) + +// CertificateSigningRequestsGetter has a method to return a CertificateSigningRequestInterface. +// A group's client should implement this interface. +type CertificateSigningRequestsGetter interface { + CertificateSigningRequests() CertificateSigningRequestInterface +} + +// CertificateSigningRequestInterface has methods to work with CertificateSigningRequest resources. +type CertificateSigningRequestInterface interface { + Create(*certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + Update(*certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + UpdateStatus(*certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + Delete(name string, options *api.DeleteOptions) error + DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error + Get(name string) (*certificates.CertificateSigningRequest, error) + List(opts api.ListOptions) (*certificates.CertificateSigningRequestList, error) + Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *certificates.CertificateSigningRequest, err error) + CertificateSigningRequestExpansion +} + +// certificateSigningRequests implements CertificateSigningRequestInterface +type certificateSigningRequests struct { + client *CertificatesClient +} + +// newCertificateSigningRequests returns a CertificateSigningRequests +func newCertificateSigningRequests(c *CertificatesClient) *certificateSigningRequests { + return &certificateSigningRequests{ + client: c, + } +} + +// Create takes the representation of a certificateSigningRequest and creates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any. +func (c *certificateSigningRequests) Create(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Post(). + Resource("certificatesigningrequests"). + Body(certificateSigningRequest). + Do(). + Into(result) + return +} + +// Update takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any. +func (c *certificateSigningRequests) Update(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Put(). + Resource("certificatesigningrequests"). + Name(certificateSigningRequest.Name). + Body(certificateSigningRequest). + Do(). + Into(result) + return +} + +func (c *certificateSigningRequests) UpdateStatus(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Put(). + Resource("certificatesigningrequests"). + Name(certificateSigningRequest.Name). + SubResource("status"). + Body(certificateSigningRequest). + Do(). + Into(result) + return +} + +// Delete takes name of the certificateSigningRequest and deletes it. Returns an error if one occurs. +func (c *certificateSigningRequests) Delete(name string, options *api.DeleteOptions) error { + return c.client.Delete(). + Resource("certificatesigningrequests"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *certificateSigningRequests) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { + return c.client.Delete(). + Resource("certificatesigningrequests"). + VersionedParams(&listOptions, api.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Get takes name of the certificateSigningRequest, and returns the corresponding certificateSigningRequest object, and an error if there is any. +func (c *certificateSigningRequests) Get(name string) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Get(). + Resource("certificatesigningrequests"). + Name(name). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of CertificateSigningRequests that match those selectors. +func (c *certificateSigningRequests) List(opts api.ListOptions) (result *certificates.CertificateSigningRequestList, err error) { + result = &certificates.CertificateSigningRequestList{} + err = c.client.Get(). + Resource("certificatesigningrequests"). + VersionedParams(&opts, api.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested certificateSigningRequests. +func (c *certificateSigningRequests) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.client.Get(). + Prefix("watch"). + Resource("certificatesigningrequests"). + VersionedParams(&opts, api.ParameterCodec). + Watch() +} + +// Patch applies the patch and returns the patched certificateSigningRequest. +func (c *certificateSigningRequests) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Patch(pt). + Resource("certificatesigningrequests"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/doc.go new file mode 100644 index 000000000000..1e6a8ff827b8 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This package is generated by client-gen with the default arguments. + +// This package has the automatically generated typed clients. +package unversioned diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/doc.go new file mode 100644 index 000000000000..083f78f3a401 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This package is generated by client-gen with the default arguments. + +// Package fake has the automatically generated clients. +package fake diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificates_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificates_client.go new file mode 100644 index 000000000000..940b63da7ee2 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificates_client.go @@ -0,0 +1,37 @@ +/* +Copyright 2016 The Kubernetes 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 fake + +import ( + unversioned "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned" + restclient "k8s.io/kubernetes/pkg/client/restclient" + core "k8s.io/kubernetes/pkg/client/testing/core" +) + +type FakeCertificates struct { + *core.Fake +} + +func (c *FakeCertificates) CertificateSigningRequests() unversioned.CertificateSigningRequestInterface { + return &FakeCertificateSigningRequests{c} +} + +// GetRESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeCertificates) GetRESTClient() *restclient.RESTClient { + return nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificatesigningrequest.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificatesigningrequest.go new file mode 100644 index 000000000000..f89638d6db45 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificatesigningrequest.go @@ -0,0 +1,118 @@ +/* +Copyright 2016 The Kubernetes 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 fake + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + certificates "k8s.io/kubernetes/pkg/apis/certificates" + core "k8s.io/kubernetes/pkg/client/testing/core" + labels "k8s.io/kubernetes/pkg/labels" + watch "k8s.io/kubernetes/pkg/watch" +) + +// FakeCertificateSigningRequests implements CertificateSigningRequestInterface +type FakeCertificateSigningRequests struct { + Fake *FakeCertificates +} + +var certificatesigningrequestsResource = unversioned.GroupVersionResource{Group: "certificates", Version: "", Resource: "certificatesigningrequests"} + +func (c *FakeCertificateSigningRequests) Create(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + obj, err := c.Fake. + Invokes(core.NewRootCreateAction(certificatesigningrequestsResource, certificateSigningRequest), &certificates.CertificateSigningRequest{}) + if obj == nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), err +} + +func (c *FakeCertificateSigningRequests) Update(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + obj, err := c.Fake. + Invokes(core.NewRootUpdateAction(certificatesigningrequestsResource, certificateSigningRequest), &certificates.CertificateSigningRequest{}) + if obj == nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), err +} + +func (c *FakeCertificateSigningRequests) UpdateStatus(certificateSigningRequest *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) { + obj, err := c.Fake. + Invokes(core.NewRootUpdateSubresourceAction(certificatesigningrequestsResource, "status", certificateSigningRequest), &certificates.CertificateSigningRequest{}) + if obj == nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), err +} + +func (c *FakeCertificateSigningRequests) Delete(name string, options *api.DeleteOptions) error { + _, err := c.Fake. + Invokes(core.NewRootDeleteAction(certificatesigningrequestsResource, name), &certificates.CertificateSigningRequest{}) + return err +} + +func (c *FakeCertificateSigningRequests) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { + action := core.NewRootDeleteCollectionAction(certificatesigningrequestsResource, listOptions) + + _, err := c.Fake.Invokes(action, &certificates.CertificateSigningRequestList{}) + return err +} + +func (c *FakeCertificateSigningRequests) Get(name string) (result *certificates.CertificateSigningRequest, err error) { + obj, err := c.Fake. + Invokes(core.NewRootGetAction(certificatesigningrequestsResource, name), &certificates.CertificateSigningRequest{}) + if obj == nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), err +} + +func (c *FakeCertificateSigningRequests) List(opts api.ListOptions) (result *certificates.CertificateSigningRequestList, err error) { + obj, err := c.Fake. + Invokes(core.NewRootListAction(certificatesigningrequestsResource, opts), &certificates.CertificateSigningRequestList{}) + if obj == nil { + return nil, err + } + + label := opts.LabelSelector + if label == nil { + label = labels.Everything() + } + list := &certificates.CertificateSigningRequestList{} + for _, item := range obj.(*certificates.CertificateSigningRequestList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested certificateSigningRequests. +func (c *FakeCertificateSigningRequests) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(core.NewRootWatchAction(certificatesigningrequestsResource, opts)) +} + +// Patch applies the patch and returns the patched certificateSigningRequest. +func (c *FakeCertificateSigningRequests) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *certificates.CertificateSigningRequest, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(certificatesigningrequestsResource, name, data, subresources...), &certificates.CertificateSigningRequest{}) + if obj == nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/generated_expansion.go new file mode 100644 index 000000000000..fa61c9dbe116 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/generated_expansion.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +type CertificateSigningRequestExpansion interface{} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/componentstatus.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/componentstatus.go index 0ef0667dad1c..ffdaeb49f04b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/componentstatus.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/componentstatus.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type ComponentStatusInterface interface { Get(name string) (*api.ComponentStatus, error) List(opts api.ListOptions) (*api.ComponentStatusList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ComponentStatus, err error) ComponentStatusExpansion } @@ -124,3 +125,16 @@ func (c *componentStatuses) Watch(opts api.ListOptions) (watch.Interface, error) VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched componentStatus. +func (c *componentStatuses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ComponentStatus, err error) { + result = &api.ComponentStatus{} + err = c.client.Patch(pt). + Resource("componentstatuses"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/configmap.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/configmap.go index b43e53d6c442..c937328dcf41 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/configmap.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/configmap.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type ConfigMapInterface interface { Get(name string) (*api.ConfigMap, error) List(opts api.ListOptions) (*api.ConfigMapList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ConfigMap, err error) ConfigMapExpansion } @@ -133,3 +134,17 @@ func (c *configMaps) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched configMap. +func (c *configMaps) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ConfigMap, err error) { + result = &api.ConfigMap{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("configmaps"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/core_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/core_client.go index 41aee4cf6543..1e066dec9032 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/core_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/core_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/doc.go index 47517b6422dd..1e6a8ff827b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/endpoints.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/endpoints.go index 78e2a08783e6..d5f383d15170 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/endpoints.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/endpoints.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type EndpointsInterface interface { Get(name string) (*api.Endpoints, error) List(opts api.ListOptions) (*api.EndpointsList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Endpoints, err error) EndpointsExpansion } @@ -133,3 +134,17 @@ func (c *endpoints) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched endpoints. +func (c *endpoints) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Endpoints, err error) { + result = &api.Endpoints{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("endpoints"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event.go index 5627690a6a5c..d4edcd37a81b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type EventInterface interface { Get(name string) (*api.Event, error) List(opts api.ListOptions) (*api.EventList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Event, err error) EventExpansion } @@ -133,3 +134,17 @@ func (c *events) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched event. +func (c *events) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Event, err error) { + result = &api.Event{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("events"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event_expansion.go index abdf89aa1c47..f3d6f468d71c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/event_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ type EventExpansion interface { CreateWithEventNamespace(event *api.Event) (*api.Event, error) // UpdateWithEventNamespace is the same as a Update, except that it sends the request to the event.Namespace. UpdateWithEventNamespace(event *api.Event) (*api.Event, error) - Patch(event *api.Event, data []byte) (*api.Event, error) + PatchWithEventNamespace(event *api.Event, data []byte) (*api.Event, error) // Search finds events about the specified object Search(objOrRef runtime.Object) (*api.EventList, error) // Returns the appropriate field selector based on the API version being used to communicate with the server. @@ -73,11 +73,15 @@ func (e *events) UpdateWithEventNamespace(event *api.Event) (*api.Event, error) return result, err } -// Patch modifies an existing event. It returns the copy of the event that the server returns, or an -// error. The namespace and name of the target event is deduced from the incompleteEvent. The -// namespace must either match this event client's namespace, or this event client must have been +// PatchWithEventNamespace modifies an existing event. It returns the copy of +// the event that the server returns, or an error. The namespace and name of the +// target event is deduced from the incompleteEvent. The namespace must either +// match this event client's namespace, or this event client must have been // created with the "" namespace. -func (e *events) Patch(incompleteEvent *api.Event, data []byte) (*api.Event, error) { +func (e *events) PatchWithEventNamespace(incompleteEvent *api.Event, data []byte) (*api.Event, error) { + if e.ns != "" && incompleteEvent.Namespace != e.ns { + return nil, fmt.Errorf("can't patch an event with namespace '%v' in namespace '%v'", incompleteEvent.Namespace, e.ns) + } result := &api.Event{} err := e.client.Patch(api.StrategicMergePatchType). NamespaceIfScoped(incompleteEvent.Namespace, len(incompleteEvent.Namespace) > 0). @@ -153,5 +157,5 @@ func (e *EventSinkImpl) Update(event *api.Event) (*api.Event, error) { } func (e *EventSinkImpl) Patch(event *api.Event, data []byte) (*api.Event, error) { - return e.Interface.Patch(event, data) + return e.Interface.PatchWithEventNamespace(event, data) } diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/doc.go index eb358c26c80f..083f78f3a401 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_componentstatus.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_componentstatus.go index 84dca9984eaf..c4dba0f0e491 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_componentstatus.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_componentstatus.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -96,3 +96,13 @@ func (c *FakeComponentStatuses) Watch(opts api.ListOptions) (watch.Interface, er return c.Fake. InvokesWatch(core.NewRootWatchAction(componentstatusesResource, opts)) } + +// Patch applies the patch and returns the patched componentStatus. +func (c *FakeComponentStatuses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ComponentStatus, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(componentstatusesResource, name, data, subresources...), &api.ComponentStatus{}) + if obj == nil { + return nil, err + } + return obj.(*api.ComponentStatus), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_configmap.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_configmap.go index 8908c26a36cd..a5cb535d59a5 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_configmap.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_configmap.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeConfigMaps) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(configmapsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched configMap. +func (c *FakeConfigMaps) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ConfigMap, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(configmapsResource, c.ns, name, data, subresources...), &api.ConfigMap{}) + + if obj == nil { + return nil, err + } + return obj.(*api.ConfigMap), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_core_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_core_client.go index 533735e7c1ba..71122d91f358 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_core_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_core_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_endpoints.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_endpoints.go index b888d89c0bd8..156a349b73d9 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_endpoints.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_endpoints.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeEndpoints) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(endpointsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched endpoints. +func (c *FakeEndpoints) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Endpoints, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(endpointsResource, c.ns, name, data, subresources...), &api.Endpoints{}) + + if obj == nil { + return nil, err + } + return obj.(*api.Endpoints), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event.go index d86b05a7bd71..8a97a321ac7d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeEvents) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(eventsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched event. +func (c *FakeEvents) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Event, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(eventsResource, c.ns, name, data, subresources...), &api.Event{}) + + if obj == nil { + return nil, err + } + return obj.(*api.Event), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event_expansion.go index b76be860d69d..c9a07517c2fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_event_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -50,11 +50,11 @@ func (c *FakeEvents) UpdateWithEventNamespace(event *api.Event) (*api.Event, err return obj.(*api.Event), err } -// Patch patches an existing event. Returns the copy of the event the server returns, or an error. -func (c *FakeEvents) Patch(event *api.Event, data []byte) (*api.Event, error) { - action := core.NewRootPatchAction(eventsResource, event) +// PatchWithEventNamespace patches an existing event. Returns the copy of the event the server returns, or an error. +func (c *FakeEvents) PatchWithEventNamespace(event *api.Event, data []byte) (*api.Event, error) { + action := core.NewRootPatchAction(eventsResource, event.Name, data) if c.ns != "" { - action = core.NewPatchAction(eventsResource, c.ns, event) + action = core.NewPatchAction(eventsResource, c.ns, event.Name, data) } obj, err := c.Fake.Invokes(action, event) if obj == nil { diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_limitrange.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_limitrange.go index b46f5eba4b8a..801ba4a5fe38 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_limitrange.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_limitrange.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeLimitRanges) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(limitrangesResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched limitRange. +func (c *FakeLimitRanges) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.LimitRange, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(limitrangesResource, c.ns, name, data, subresources...), &api.LimitRange{}) + + if obj == nil { + return nil, err + } + return obj.(*api.LimitRange), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace.go index 233dd8ff9a1d..b2c48f449c2f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -105,3 +105,13 @@ func (c *FakeNamespaces) Watch(opts api.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(core.NewRootWatchAction(namespacesResource, opts)) } + +// Patch applies the patch and returns the patched namespace. +func (c *FakeNamespaces) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Namespace, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(namespacesResource, name, data, subresources...), &api.Namespace{}) + if obj == nil { + return nil, err + } + return obj.(*api.Namespace), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace_expansion.go index 04b3acc14d1e..41eb343e0263 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_namespace_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node.go index 7370e5a2a4b9..e7f410ec985a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -105,3 +105,13 @@ func (c *FakeNodes) Watch(opts api.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(core.NewRootWatchAction(nodesResource, opts)) } + +// Patch applies the patch and returns the patched node. +func (c *FakeNodes) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Node, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(nodesResource, name, data, subresources...), &api.Node{}) + if obj == nil { + return nil, err + } + return obj.(*api.Node), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node_expansion.go index 161d5e74593a..09ddd846765c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_node_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ( func (c *FakeNodes) PatchStatus(nodeName string, data []byte) (*api.Node, error) { obj, err := c.Fake.Invokes( - core.NewPatchSubresourceAction(nodesResource, "status"), &api.Node{}) + core.NewRootPatchSubresourceAction(nodesResource, nodeName, data, "status"), &api.Node{}) if obj == nil { return nil, err } diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolume.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolume.go index fd0ae18ae6d9..2a192a858c1d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolume.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolume.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -105,3 +105,13 @@ func (c *FakePersistentVolumes) Watch(opts api.ListOptions) (watch.Interface, er return c.Fake. InvokesWatch(core.NewRootWatchAction(persistentvolumesResource, opts)) } + +// Patch applies the patch and returns the patched persistentVolume. +func (c *FakePersistentVolumes) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolume, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(persistentvolumesResource, name, data, subresources...), &api.PersistentVolume{}) + if obj == nil { + return nil, err + } + return obj.(*api.PersistentVolume), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolumeclaim.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolumeclaim.go index bd10e834d3a2..6478649ee55f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolumeclaim.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_persistentvolumeclaim.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,3 +113,14 @@ func (c *FakePersistentVolumeClaims) Watch(opts api.ListOptions) (watch.Interfac InvokesWatch(core.NewWatchAction(persistentvolumeclaimsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched persistentVolumeClaim. +func (c *FakePersistentVolumeClaims) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolumeClaim, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(persistentvolumeclaimsResource, c.ns, name, data, subresources...), &api.PersistentVolumeClaim{}) + + if obj == nil { + return nil, err + } + return obj.(*api.PersistentVolumeClaim), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod.go index 98c0b8e3f796..699a521bfe73 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,3 +113,14 @@ func (c *FakePods) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(podsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched pod. +func (c *FakePods) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Pod, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(podsResource, c.ns, name, data, subresources...), &api.Pod{}) + + if obj == nil { + return nil, err + } + return obj.(*api.Pod), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod_expansion.go index 32fd74c027ea..26343982c597 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_pod_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_podtemplate.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_podtemplate.go index c08d06bea0e7..cf1dc413c2b6 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_podtemplate.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_podtemplate.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakePodTemplates) Watch(opts api.ListOptions) (watch.Interface, error) InvokesWatch(core.NewWatchAction(podtemplatesResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched podTemplate. +func (c *FakePodTemplates) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PodTemplate, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(podtemplatesResource, c.ns, name, data, subresources...), &api.PodTemplate{}) + + if obj == nil { + return nil, err + } + return obj.(*api.PodTemplate), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_replicationcontroller.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_replicationcontroller.go index 0a7faddbc440..1a85399e8576 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_replicationcontroller.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_replicationcontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,3 +113,14 @@ func (c *FakeReplicationControllers) Watch(opts api.ListOptions) (watch.Interfac InvokesWatch(core.NewWatchAction(replicationcontrollersResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched replicationController. +func (c *FakeReplicationControllers) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ReplicationController, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(replicationcontrollersResource, c.ns, name, data, subresources...), &api.ReplicationController{}) + + if obj == nil { + return nil, err + } + return obj.(*api.ReplicationController), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_resourcequota.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_resourcequota.go index d91ee2685bb5..b1eb4b5d853d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_resourcequota.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_resourcequota.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,3 +113,14 @@ func (c *FakeResourceQuotas) Watch(opts api.ListOptions) (watch.Interface, error InvokesWatch(core.NewWatchAction(resourcequotasResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched resourceQuota. +func (c *FakeResourceQuotas) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ResourceQuota, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(resourcequotasResource, c.ns, name, data, subresources...), &api.ResourceQuota{}) + + if obj == nil { + return nil, err + } + return obj.(*api.ResourceQuota), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_secret.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_secret.go index 0caaa47cf71c..7075a0e22f27 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_secret.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_secret.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeSecrets) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(secretsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched secret. +func (c *FakeSecrets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Secret, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(secretsResource, c.ns, name, data, subresources...), &api.Secret{}) + + if obj == nil { + return nil, err + } + return obj.(*api.Secret), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service.go index 62eae6481e54..eb4a4baa0eb7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -113,3 +113,14 @@ func (c *FakeServices) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(servicesResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched service. +func (c *FakeServices) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Service, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(servicesResource, c.ns, name, data, subresources...), &api.Service{}) + + if obj == nil { + return nil, err + } + return obj.(*api.Service), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service_expansion.go index 3494b873762e..978585f670bb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_service_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_serviceaccount.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_serviceaccount.go index fbce964a1246..e8c72d35e209 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_serviceaccount.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/fake/fake_serviceaccount.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -103,3 +103,14 @@ func (c *FakeServiceAccounts) Watch(opts api.ListOptions) (watch.Interface, erro InvokesWatch(core.NewWatchAction(serviceaccountsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched serviceAccount. +func (c *FakeServiceAccounts) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ServiceAccount, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(serviceaccountsResource, c.ns, name, data, subresources...), &api.ServiceAccount{}) + + if obj == nil { + return nil, err + } + return obj.(*api.ServiceAccount), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/generated_expansion.go index 546f8e7a1d1c..a61fba53a342 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/generated_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/limitrange.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/limitrange.go index 86cc9b07fa7d..70cd4fb3e2d1 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/limitrange.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/limitrange.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type LimitRangeInterface interface { Get(name string) (*api.LimitRange, error) List(opts api.ListOptions) (*api.LimitRangeList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.LimitRange, err error) LimitRangeExpansion } @@ -133,3 +134,17 @@ func (c *limitRanges) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched limitRange. +func (c *limitRanges) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.LimitRange, err error) { + result = &api.LimitRange{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("limitranges"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace.go index c1c8b4506934..7b39f2b8648f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type NamespaceInterface interface { Get(name string) (*api.Namespace, error) List(opts api.ListOptions) (*api.NamespaceList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Namespace, err error) NamespaceExpansion } @@ -137,3 +138,16 @@ func (c *namespaces) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched namespace. +func (c *namespaces) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Namespace, err error) { + result = &api.Namespace{} + err = c.client.Patch(pt). + Resource("namespaces"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace_expansion.go index 8f47aec484f1..15049da11faf 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/namespace_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node.go index b0c53ef1d4be..8f4ffcd4813e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type NodeInterface interface { Get(name string) (*api.Node, error) List(opts api.ListOptions) (*api.NodeList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Node, err error) NodeExpansion } @@ -137,3 +138,16 @@ func (c *nodes) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched node. +func (c *nodes) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Node, err error) { + result = &api.Node{} + err = c.client.Patch(pt). + Resource("nodes"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node_expansion.go index 3146cdb357e0..767f157b82ec 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/node_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolume.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolume.go index 6b4d0f017fb9..ecca7a375e6b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolume.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolume.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type PersistentVolumeInterface interface { Get(name string) (*api.PersistentVolume, error) List(opts api.ListOptions) (*api.PersistentVolumeList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolume, err error) PersistentVolumeExpansion } @@ -137,3 +138,16 @@ func (c *persistentVolumes) Watch(opts api.ListOptions) (watch.Interface, error) VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched persistentVolume. +func (c *persistentVolumes) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolume, err error) { + result = &api.PersistentVolume{} + err = c.client.Patch(pt). + Resource("persistentvolumes"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolumeclaim.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolumeclaim.go index 2f5b17437367..45d22eb43ff9 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolumeclaim.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/persistentvolumeclaim.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type PersistentVolumeClaimInterface interface { Get(name string) (*api.PersistentVolumeClaim, error) List(opts api.ListOptions) (*api.PersistentVolumeClaimList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolumeClaim, err error) PersistentVolumeClaimExpansion } @@ -147,3 +148,17 @@ func (c *persistentVolumeClaims) Watch(opts api.ListOptions) (watch.Interface, e VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched persistentVolumeClaim. +func (c *persistentVolumeClaims) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PersistentVolumeClaim, err error) { + result = &api.PersistentVolumeClaim{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("persistentvolumeclaims"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod.go index 1cdfc8e714be..595462a0c84d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type PodInterface interface { Get(name string) (*api.Pod, error) List(opts api.ListOptions) (*api.PodList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Pod, err error) PodExpansion } @@ -147,3 +148,17 @@ func (c *pods) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched pod. +func (c *pods) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Pod, err error) { + result = &api.Pod{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("pods"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod_expansion.go index 8ebd29d3084c..a72b843246e8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/pod_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/podtemplate.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/podtemplate.go index cccef29f7181..4494bd34f5fc 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/podtemplate.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/podtemplate.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type PodTemplateInterface interface { Get(name string) (*api.PodTemplate, error) List(opts api.ListOptions) (*api.PodTemplateList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PodTemplate, err error) PodTemplateExpansion } @@ -133,3 +134,17 @@ func (c *podTemplates) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched podTemplate. +func (c *podTemplates) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.PodTemplate, err error) { + result = &api.PodTemplate{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("podtemplates"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/replicationcontroller.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/replicationcontroller.go index 6f9f06625ad2..a1b17576653d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/replicationcontroller.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/replicationcontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ReplicationControllerInterface interface { Get(name string) (*api.ReplicationController, error) List(opts api.ListOptions) (*api.ReplicationControllerList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ReplicationController, err error) ReplicationControllerExpansion } @@ -147,3 +148,17 @@ func (c *replicationControllers) Watch(opts api.ListOptions) (watch.Interface, e VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched replicationController. +func (c *replicationControllers) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ReplicationController, err error) { + result = &api.ReplicationController{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("replicationcontrollers"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/resourcequota.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/resourcequota.go index 2d0da73fb3ae..1aa175b926fb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/resourcequota.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/resourcequota.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ResourceQuotaInterface interface { Get(name string) (*api.ResourceQuota, error) List(opts api.ListOptions) (*api.ResourceQuotaList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ResourceQuota, err error) ResourceQuotaExpansion } @@ -147,3 +148,17 @@ func (c *resourceQuotas) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched resourceQuota. +func (c *resourceQuotas) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ResourceQuota, err error) { + result = &api.ResourceQuota{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("resourcequotas"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/secret.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/secret.go index 101fbdb54e5c..f87263cbbb72 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/secret.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/secret.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type SecretInterface interface { Get(name string) (*api.Secret, error) List(opts api.ListOptions) (*api.SecretList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Secret, err error) SecretExpansion } @@ -133,3 +134,17 @@ func (c *secrets) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched secret. +func (c *secrets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Secret, err error) { + result = &api.Secret{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("secrets"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service.go index 006f601c271f..86fa3b229623 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ServiceInterface interface { Get(name string) (*api.Service, error) List(opts api.ListOptions) (*api.ServiceList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Service, err error) ServiceExpansion } @@ -147,3 +148,17 @@ func (c *services) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched service. +func (c *services) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.Service, err error) { + result = &api.Service{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("services"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service_expansion.go index 89266e6cd869..de8f21c62552 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/service_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/serviceaccount.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/serviceaccount.go index 65f7df2638e1..14c56b2f4a74 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/serviceaccount.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned/serviceaccount.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ type ServiceAccountInterface interface { Get(name string) (*api.ServiceAccount, error) List(opts api.ListOptions) (*api.ServiceAccountList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ServiceAccount, err error) ServiceAccountExpansion } @@ -133,3 +134,17 @@ func (c *serviceAccounts) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched serviceAccount. +func (c *serviceAccounts) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *api.ServiceAccount, err error) { + result = &api.ServiceAccount{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("serviceaccounts"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/daemonset.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/daemonset.go index 96dae5835a22..827677d9d8b7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/daemonset.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/daemonset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type DaemonSetInterface interface { Get(name string) (*extensions.DaemonSet, error) List(opts api.ListOptions) (*extensions.DaemonSetList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.DaemonSet, err error) DaemonSetExpansion } @@ -148,3 +149,17 @@ func (c *daemonSets) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched daemonSet. +func (c *daemonSets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.DaemonSet, err error) { + result = &extensions.DaemonSet{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("daemonsets"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment.go index 3b995c021618..894a7d397c3b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type DeploymentInterface interface { Get(name string) (*extensions.Deployment, error) List(opts api.ListOptions) (*extensions.DeploymentList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Deployment, err error) DeploymentExpansion } @@ -148,3 +149,17 @@ func (c *deployments) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched deployment. +func (c *deployments) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Deployment, err error) { + result = &extensions.Deployment{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("deployments"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment_expansion.go index 9969aecc93fc..4d89330f8481 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/deployment_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/doc.go index 47517b6422dd..1e6a8ff827b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/extensions_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/extensions_client.go index 9b9f4749a64d..7ad44194f90f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/extensions_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/extensions_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ type ExtensionsInterface interface { PodSecurityPoliciesGetter ReplicaSetsGetter ScalesGetter + StorageClassesGetter ThirdPartyResourcesGetter } @@ -62,6 +63,10 @@ func (c *ExtensionsClient) Scales(namespace string) ScaleInterface { return newScales(c, namespace) } +func (c *ExtensionsClient) StorageClasses() StorageClassInterface { + return newStorageClasses(c) +} + func (c *ExtensionsClient) ThirdPartyResources() ThirdPartyResourceInterface { return newThirdPartyResources(c) } diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/doc.go index eb358c26c80f..083f78f3a401 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_daemonset.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_daemonset.go index d53fa797aa6d..befb863aa3d1 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_daemonset.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_daemonset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeDaemonSets) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(daemonsetsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched daemonSet. +func (c *FakeDaemonSets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.DaemonSet, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(daemonsetsResource, c.ns, name, data, subresources...), &extensions.DaemonSet{}) + + if obj == nil { + return nil, err + } + return obj.(*extensions.DaemonSet), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment.go index c70a3a81d5f9..b06ee579297e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeDeployments) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(deploymentsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched deployment. +func (c *FakeDeployments) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Deployment, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(deploymentsResource, c.ns, name, data, subresources...), &extensions.Deployment{}) + + if obj == nil { + return nil, err + } + return obj.(*extensions.Deployment), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment_expansion.go index 3a7c06e50546..8b73f41073fa 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_deployment_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_extensions_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_extensions_client.go index 7c2fa08518a2..cb3bc074d734 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_extensions_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_extensions_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -50,6 +50,10 @@ func (c *FakeExtensions) Scales(namespace string) unversioned.ScaleInterface { return &FakeScales{c, namespace} } +func (c *FakeExtensions) StorageClasses() unversioned.StorageClassInterface { + return &FakeStorageClasses{c} +} + func (c *FakeExtensions) ThirdPartyResources() unversioned.ThirdPartyResourceInterface { return &FakeThirdPartyResources{c} } diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_ingress.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_ingress.go index 68578ce120bf..bb636523d3ed 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_ingress.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_ingress.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeIngresses) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(ingressesResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched ingress. +func (c *FakeIngresses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Ingress, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(ingressesResource, c.ns, name, data, subresources...), &extensions.Ingress{}) + + if obj == nil { + return nil, err + } + return obj.(*extensions.Ingress), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_podsecuritypolicy.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_podsecuritypolicy.go index 52b6f3acd16a..72875c434049 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_podsecuritypolicy.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_podsecuritypolicy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -97,3 +97,13 @@ func (c *FakePodSecurityPolicies) Watch(opts api.ListOptions) (watch.Interface, return c.Fake. InvokesWatch(core.NewRootWatchAction(podsecuritypoliciesResource, opts)) } + +// Patch applies the patch and returns the patched podSecurityPolicy. +func (c *FakePodSecurityPolicies) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.PodSecurityPolicy, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(podsecuritypoliciesResource, name, data, subresources...), &extensions.PodSecurityPolicy{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.PodSecurityPolicy), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_replicaset.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_replicaset.go index 9d7241ca49a4..760c905e5db7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_replicaset.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_replicaset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -114,3 +114,14 @@ func (c *FakeReplicaSets) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(replicasetsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched replicaSet. +func (c *FakeReplicaSets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ReplicaSet, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(replicasetsResource, c.ns, name, data, subresources...), &extensions.ReplicaSet{}) + + if obj == nil { + return nil, err + } + return obj.(*extensions.ReplicaSet), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale.go index d2cfc5f7b789..0179e4edce48 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale_expansion.go index 949836afe546..481b8197f0d0 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_scale_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_storageclass.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_storageclass.go new file mode 100644 index 000000000000..bc9b856b03a4 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_storageclass.go @@ -0,0 +1,109 @@ +/* +Copyright 2016 The Kubernetes 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 fake + +import ( + api "k8s.io/kubernetes/pkg/api" + unversioned "k8s.io/kubernetes/pkg/api/unversioned" + extensions "k8s.io/kubernetes/pkg/apis/extensions" + core "k8s.io/kubernetes/pkg/client/testing/core" + labels "k8s.io/kubernetes/pkg/labels" + watch "k8s.io/kubernetes/pkg/watch" +) + +// FakeStorageClasses implements StorageClassInterface +type FakeStorageClasses struct { + Fake *FakeExtensions +} + +var storageclassesResource = unversioned.GroupVersionResource{Group: "extensions", Version: "", Resource: "storageclasses"} + +func (c *FakeStorageClasses) Create(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + obj, err := c.Fake. + Invokes(core.NewRootCreateAction(storageclassesResource, storageClass), &extensions.StorageClass{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.StorageClass), err +} + +func (c *FakeStorageClasses) Update(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + obj, err := c.Fake. + Invokes(core.NewRootUpdateAction(storageclassesResource, storageClass), &extensions.StorageClass{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.StorageClass), err +} + +func (c *FakeStorageClasses) Delete(name string, options *api.DeleteOptions) error { + _, err := c.Fake. + Invokes(core.NewRootDeleteAction(storageclassesResource, name), &extensions.StorageClass{}) + return err +} + +func (c *FakeStorageClasses) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { + action := core.NewRootDeleteCollectionAction(storageclassesResource, listOptions) + + _, err := c.Fake.Invokes(action, &extensions.StorageClassList{}) + return err +} + +func (c *FakeStorageClasses) Get(name string) (result *extensions.StorageClass, err error) { + obj, err := c.Fake. + Invokes(core.NewRootGetAction(storageclassesResource, name), &extensions.StorageClass{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.StorageClass), err +} + +func (c *FakeStorageClasses) List(opts api.ListOptions) (result *extensions.StorageClassList, err error) { + obj, err := c.Fake. + Invokes(core.NewRootListAction(storageclassesResource, opts), &extensions.StorageClassList{}) + if obj == nil { + return nil, err + } + + label := opts.LabelSelector + if label == nil { + label = labels.Everything() + } + list := &extensions.StorageClassList{} + for _, item := range obj.(*extensions.StorageClassList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested storageClasses. +func (c *FakeStorageClasses) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(core.NewRootWatchAction(storageclassesResource, opts)) +} + +// Patch applies the patch and returns the patched storageClass. +func (c *FakeStorageClasses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.StorageClass, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(storageclassesResource, name, data, subresources...), &extensions.StorageClass{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.StorageClass), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_thirdpartyresource.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_thirdpartyresource.go index 37cbca979ca1..992aefe9aafa 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_thirdpartyresource.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/fake/fake_thirdpartyresource.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -97,3 +97,13 @@ func (c *FakeThirdPartyResources) Watch(opts api.ListOptions) (watch.Interface, return c.Fake. InvokesWatch(core.NewRootWatchAction(thirdpartyresourcesResource, opts)) } + +// Patch applies the patch and returns the patched thirdPartyResource. +func (c *FakeThirdPartyResources) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ThirdPartyResource, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(thirdpartyresourcesResource, name, data, subresources...), &extensions.ThirdPartyResource{}) + if obj == nil { + return nil, err + } + return obj.(*extensions.ThirdPartyResource), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/generated_expansion.go index 7a1999454e6e..b795deed1920 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/generated_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,3 +29,5 @@ type PodSecurityPolicyExpansion interface{} type ThirdPartyResourceExpansion interface{} type ReplicaSetExpansion interface{} + +type StorageClassExpansion interface{} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/ingress.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/ingress.go index a9d950eae89f..7d941ac8702e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/ingress.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/ingress.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type IngressInterface interface { Get(name string) (*extensions.Ingress, error) List(opts api.ListOptions) (*extensions.IngressList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Ingress, err error) IngressExpansion } @@ -148,3 +149,17 @@ func (c *ingresses) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched ingress. +func (c *ingresses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.Ingress, err error) { + result = &extensions.Ingress{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("ingresses"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/job.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/job.go index 4ae3f6cac557..f0411862bd4e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/job.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/job.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/podsecuritypolicy.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/podsecuritypolicy.go index 06a7908f4675..e59ba014bb0f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/podsecuritypolicy.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/podsecuritypolicy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type PodSecurityPolicyInterface interface { Get(name string) (*extensions.PodSecurityPolicy, error) List(opts api.ListOptions) (*extensions.PodSecurityPolicyList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.PodSecurityPolicy, err error) PodSecurityPolicyExpansion } @@ -125,3 +126,16 @@ func (c *podSecurityPolicies) Watch(opts api.ListOptions) (watch.Interface, erro VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched podSecurityPolicy. +func (c *podSecurityPolicies) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.PodSecurityPolicy, err error) { + result = &extensions.PodSecurityPolicy{} + err = c.client.Patch(pt). + Resource("podsecuritypolicies"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/replicaset.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/replicaset.go index 6257fd8981ea..fc6987b5ba0d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/replicaset.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/replicaset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ type ReplicaSetInterface interface { Get(name string) (*extensions.ReplicaSet, error) List(opts api.ListOptions) (*extensions.ReplicaSetList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ReplicaSet, err error) ReplicaSetExpansion } @@ -148,3 +149,17 @@ func (c *replicaSets) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched replicaSet. +func (c *replicaSets) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ReplicaSet, err error) { + result = &extensions.ReplicaSet{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("replicasets"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale.go index 7e54bc347437..12455ca888a5 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale_expansion.go index 61a77f260d5d..8dbba79e3fe8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/scale_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/storageclass.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/storageclass.go new file mode 100644 index 000000000000..0a145b0fde86 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/storageclass.go @@ -0,0 +1,141 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + api "k8s.io/kubernetes/pkg/api" + extensions "k8s.io/kubernetes/pkg/apis/extensions" + watch "k8s.io/kubernetes/pkg/watch" +) + +// StorageClassesGetter has a method to return a StorageClassInterface. +// A group's client should implement this interface. +type StorageClassesGetter interface { + StorageClasses() StorageClassInterface +} + +// StorageClassInterface has methods to work with StorageClass resources. +type StorageClassInterface interface { + Create(*extensions.StorageClass) (*extensions.StorageClass, error) + Update(*extensions.StorageClass) (*extensions.StorageClass, error) + Delete(name string, options *api.DeleteOptions) error + DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error + Get(name string) (*extensions.StorageClass, error) + List(opts api.ListOptions) (*extensions.StorageClassList, error) + Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.StorageClass, err error) + StorageClassExpansion +} + +// storageClasses implements StorageClassInterface +type storageClasses struct { + client *ExtensionsClient +} + +// newStorageClasses returns a StorageClasses +func newStorageClasses(c *ExtensionsClient) *storageClasses { + return &storageClasses{ + client: c, + } +} + +// Create takes the representation of a storageClass and creates it. Returns the server's representation of the storageClass, and an error, if there is any. +func (c *storageClasses) Create(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Post(). + Resource("storageclasses"). + Body(storageClass). + Do(). + Into(result) + return +} + +// Update takes the representation of a storageClass and updates it. Returns the server's representation of the storageClass, and an error, if there is any. +func (c *storageClasses) Update(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Put(). + Resource("storageclasses"). + Name(storageClass.Name). + Body(storageClass). + Do(). + Into(result) + return +} + +// Delete takes name of the storageClass and deletes it. Returns an error if one occurs. +func (c *storageClasses) Delete(name string, options *api.DeleteOptions) error { + return c.client.Delete(). + Resource("storageclasses"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *storageClasses) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { + return c.client.Delete(). + Resource("storageclasses"). + VersionedParams(&listOptions, api.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Get takes name of the storageClass, and returns the corresponding storageClass object, and an error if there is any. +func (c *storageClasses) Get(name string) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Get(). + Resource("storageclasses"). + Name(name). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of StorageClasses that match those selectors. +func (c *storageClasses) List(opts api.ListOptions) (result *extensions.StorageClassList, err error) { + result = &extensions.StorageClassList{} + err = c.client.Get(). + Resource("storageclasses"). + VersionedParams(&opts, api.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested storageClasses. +func (c *storageClasses) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.client.Get(). + Prefix("watch"). + Resource("storageclasses"). + VersionedParams(&opts, api.ParameterCodec). + Watch() +} + +// Patch applies the patch and returns the patched storageClass. +func (c *storageClasses) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Patch(pt). + Resource("storageclasses"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/thirdpartyresource.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/thirdpartyresource.go index a64ffb62c426..914ae240353c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/thirdpartyresource.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/extensions/unversioned/thirdpartyresource.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ThirdPartyResourceInterface interface { Get(name string) (*extensions.ThirdPartyResource, error) List(opts api.ListOptions) (*extensions.ThirdPartyResourceList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ThirdPartyResource, err error) ThirdPartyResourceExpansion } @@ -125,3 +126,16 @@ func (c *thirdPartyResources) Watch(opts api.ListOptions) (watch.Interface, erro VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched thirdPartyResource. +func (c *thirdPartyResources) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *extensions.ThirdPartyResource, err error) { + result = &extensions.ThirdPartyResource{} + err = c.client.Patch(pt). + Resource("thirdpartyresources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrole.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrole.go index 5d0b3912a53f..2ad8d75c5e6f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrole.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrole.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ClusterRoleInterface interface { Get(name string) (*rbac.ClusterRole, error) List(opts api.ListOptions) (*rbac.ClusterRoleList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRole, err error) ClusterRoleExpansion } @@ -125,3 +126,16 @@ func (c *clusterRoles) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched clusterRole. +func (c *clusterRoles) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRole, err error) { + result = &rbac.ClusterRole{} + err = c.client.Patch(pt). + Resource("clusterroles"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrolebinding.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrolebinding.go index f2102592afcd..1f88d7edbc8d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrolebinding.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/clusterrolebinding.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ClusterRoleBindingInterface interface { Get(name string) (*rbac.ClusterRoleBinding, error) List(opts api.ListOptions) (*rbac.ClusterRoleBindingList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRoleBinding, err error) ClusterRoleBindingExpansion } @@ -125,3 +126,16 @@ func (c *clusterRoleBindings) Watch(opts api.ListOptions) (watch.Interface, erro VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched clusterRoleBinding. +func (c *clusterRoleBindings) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRoleBinding, err error) { + result = &rbac.ClusterRoleBinding{} + err = c.client.Patch(pt). + Resource("clusterrolebindings"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/doc.go index 47517b6422dd..1e6a8ff827b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/doc.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/doc.go index eb358c26c80f..083f78f3a401 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrole.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrole.go index c86ec5f705cc..ad06353d009a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrole.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrole.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -97,3 +97,13 @@ func (c *FakeClusterRoles) Watch(opts api.ListOptions) (watch.Interface, error) return c.Fake. InvokesWatch(core.NewRootWatchAction(clusterrolesResource, opts)) } + +// Patch applies the patch and returns the patched clusterRole. +func (c *FakeClusterRoles) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRole, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(clusterrolesResource, name, data, subresources...), &rbac.ClusterRole{}) + if obj == nil { + return nil, err + } + return obj.(*rbac.ClusterRole), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrolebinding.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrolebinding.go index bf16661b1721..502774d44d45 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrolebinding.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_clusterrolebinding.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -97,3 +97,13 @@ func (c *FakeClusterRoleBindings) Watch(opts api.ListOptions) (watch.Interface, return c.Fake. InvokesWatch(core.NewRootWatchAction(clusterrolebindingsResource, opts)) } + +// Patch applies the patch and returns the patched clusterRoleBinding. +func (c *FakeClusterRoleBindings) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.ClusterRoleBinding, err error) { + obj, err := c.Fake. + Invokes(core.NewRootPatchSubresourceAction(clusterrolebindingsResource, name, data, subresources...), &rbac.ClusterRoleBinding{}) + if obj == nil { + return nil, err + } + return obj.(*rbac.ClusterRoleBinding), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rbac_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rbac_client.go index 5c4951fe1829..9e3a130db353 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rbac_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rbac_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_role.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_role.go index eacccc39ac1f..b054f408bded 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_role.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_role.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -104,3 +104,14 @@ func (c *FakeRoles) Watch(opts api.ListOptions) (watch.Interface, error) { InvokesWatch(core.NewWatchAction(rolesResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched role. +func (c *FakeRoles) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.Role, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(rolesResource, c.ns, name, data, subresources...), &rbac.Role{}) + + if obj == nil { + return nil, err + } + return obj.(*rbac.Role), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rolebinding.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rolebinding.go index ff7576617511..94870bdcd2e8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rolebinding.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/fake/fake_rolebinding.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -104,3 +104,14 @@ func (c *FakeRoleBindings) Watch(opts api.ListOptions) (watch.Interface, error) InvokesWatch(core.NewWatchAction(rolebindingsResource, c.ns, opts)) } + +// Patch applies the patch and returns the patched roleBinding. +func (c *FakeRoleBindings) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.RoleBinding, err error) { + obj, err := c.Fake. + Invokes(core.NewPatchSubresourceAction(rolebindingsResource, c.ns, name, data, subresources...), &rbac.RoleBinding{}) + + if obj == nil { + return nil, err + } + return obj.(*rbac.RoleBinding), err +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/generated_expansion.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/generated_expansion.go index a3b9c689d359..cbb0192a1640 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/generated_expansion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rbac_client.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rbac_client.go index 4d67337cde2c..fa2f336fe77e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rbac_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rbac_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/role.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/role.go index 68e7ebe93b8c..76dafee01e23 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/role.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/role.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type RoleInterface interface { Get(name string) (*rbac.Role, error) List(opts api.ListOptions) (*rbac.RoleList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.Role, err error) RoleExpansion } @@ -134,3 +135,17 @@ func (c *roles) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched role. +func (c *roles) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.Role, err error) { + result = &rbac.Role{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("roles"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rolebinding.go b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rolebinding.go index c73318c9794c..e62fe2105cdb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rolebinding.go +++ b/vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/unversioned/rolebinding.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type RoleBindingInterface interface { Get(name string) (*rbac.RoleBinding, error) List(opts api.ListOptions) (*rbac.RoleBindingList, error) Watch(opts api.ListOptions) (watch.Interface, error) + Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.RoleBinding, err error) RoleBindingExpansion } @@ -134,3 +135,17 @@ func (c *roleBindings) Watch(opts api.ListOptions) (watch.Interface, error) { VersionedParams(&opts, api.ParameterCodec). Watch() } + +// Patch applies the patch and returns the patched roleBinding. +func (c *roleBindings) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *rbac.RoleBinding, err error) { + result = &rbac.RoleBinding{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("rolebindings"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/leaderelection/leaderelection.go b/vendor/k8s.io/kubernetes/pkg/client/leaderelection/leaderelection.go index 2bd4df3edb3a..ac8d8967a6bf 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/leaderelection/leaderelection.go +++ b/vendor/k8s.io/kubernetes/pkg/client/leaderelection/leaderelection.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/metrics/metrics.go b/vendor/k8s.io/kubernetes/pkg/client/metrics/metrics.go index efa66fc8bcf7..53029b53e9fe 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/metrics/metrics.go +++ b/vendor/k8s.io/kubernetes/pkg/client/metrics/metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/record/doc.go b/vendor/k8s.io/kubernetes/pkg/client/record/doc.go index d955154326fb..0dc790696fb8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/record/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/record/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/record/event.go b/vendor/k8s.io/kubernetes/pkg/client/record/event.go index 47cbe3eca69f..9378f784b10d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/record/event.go +++ b/vendor/k8s.io/kubernetes/pkg/client/record/event.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/watch" @@ -113,7 +113,7 @@ func (eventBroadcaster *eventBroadcasterImpl) StartRecordingToSink(sink EventSin // The default math/rand package functions aren't thread safe, so create a // new Rand object for each StartRecording call. randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - eventCorrelator := NewEventCorrelator(util.RealClock{}) + eventCorrelator := NewEventCorrelator(clock.RealClock{}) return eventBroadcaster.StartEventWatcher( func(event *api.Event) { recordToSink(sink, event, eventCorrelator, randGen, eventBroadcaster.sleepDuration) @@ -242,13 +242,13 @@ func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler fun // NewRecorder returns an EventRecorder that records events with the given event source. func (eventBroadcaster *eventBroadcasterImpl) NewRecorder(source api.EventSource) EventRecorder { - return &recorderImpl{source, eventBroadcaster.Broadcaster, util.RealClock{}} + return &recorderImpl{source, eventBroadcaster.Broadcaster, clock.RealClock{}} } type recorderImpl struct { source api.EventSource *watch.Broadcaster - clock util.Clock + clock clock.Clock } func (recorder *recorderImpl) generateEvent(object runtime.Object, timestamp unversioned.Time, eventtype, reason, message string) { diff --git a/vendor/k8s.io/kubernetes/pkg/client/record/events_cache.go b/vendor/k8s.io/kubernetes/pkg/client/record/events_cache.go index fa76db795813..8ff65776cb11 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/record/events_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/client/record/events_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/strategicpatch" ) @@ -116,12 +116,12 @@ type EventAggregator struct { maxIntervalInSeconds int // clock is used to allow for testing over a time interval - clock util.Clock + clock clock.Clock } // NewEventAggregator returns a new instance of an EventAggregator func NewEventAggregator(lruCacheSize int, keyFunc EventAggregatorKeyFunc, messageFunc EventAggregatorMessageFunc, - maxEvents int, maxIntervalInSeconds int, clock util.Clock) *EventAggregator { + maxEvents int, maxIntervalInSeconds int, clock clock.Clock) *EventAggregator { return &EventAggregator{ cache: lru.New(lruCacheSize), keyFunc: keyFunc, @@ -207,11 +207,11 @@ type eventLog struct { type eventLogger struct { sync.RWMutex cache *lru.Cache - clock util.Clock + clock clock.Clock } // newEventLogger observes events and counts their frequencies -func newEventLogger(lruCacheEntries int, clock util.Clock) *eventLogger { +func newEventLogger(lruCacheEntries int, clock clock.Clock) *eventLogger { return &eventLogger{cache: lru.New(lruCacheEntries), clock: clock} } @@ -326,7 +326,7 @@ type EventCorrelateResult struct { // the same reason. // * Events are incrementally counted if the exact same event is encountered multiple // times. -func NewEventCorrelator(clock util.Clock) *EventCorrelator { +func NewEventCorrelator(clock clock.Clock) *EventCorrelator { cacheSize := maxLruCacheEntries return &EventCorrelator{ filterFunc: DefaultEventFilterFunc, diff --git a/vendor/k8s.io/kubernetes/pkg/client/record/fake.go b/vendor/k8s.io/kubernetes/pkg/client/record/fake.go index 35204ef2df6d..e063a4fc6438 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/record/fake.go +++ b/vendor/k8s.io/kubernetes/pkg/client/record/fake.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/client.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/client.go index 230edd45c743..24ad1914e946 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/client.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -222,7 +222,3 @@ func (c *RESTClient) Delete() *Request { func (c *RESTClient) APIVersion() unversioned.GroupVersion { return *c.contentConfig.GroupVersion } - -func (c *RESTClient) Codec() runtime.Codec { - return c.contentConfig.Codec -} diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/config.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/config.go index 0741e3c2d8f4..aa9cc5202680 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/config.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/config.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,11 @@ import ( "k8s.io/kubernetes/pkg/version" ) +const ( + DefaultQPS float32 = 5.0 + DefaultBurst int = 10 +) + // Config holds the common attributes that can be passed to a Kubernetes client on // initialization. type Config struct { @@ -93,10 +98,12 @@ type Config struct { // on top of the returned RoundTripper. WrapTransport func(rt http.RoundTripper) http.RoundTripper - // QPS indicates the maximum QPS to the master from this client. If zero, QPS is unlimited. + // QPS indicates the maximum QPS to the master from this client. + // If it's zero, the created RESTClient will use DefaultQPS: 5 QPS float32 - // Maximum burst for throttle + // Maximum burst for throttle. + // If it's zero, the created RESTClient will use DefaultBurst: 10. Burst int // Rate limiter for limiting connections to the master from this client. If present overwrites QPS/Burst @@ -124,6 +131,9 @@ type TLSClientConfig struct { } type ContentConfig struct { + // AcceptContentTypes specifies the types the client will accept and is optional. + // If not set, ContentType will be used to define the Accept header + AcceptContentTypes string // ContentType specifies the wire format used to communicate with the server. // This value will be set as the Accept header on requests made to the server, and // as the default content type on any object sent to the server. If not set, @@ -136,15 +146,6 @@ type ContentConfig struct { // NegotiatedSerializer is used for obtaining encoders and decoders for multiple // supported media types. NegotiatedSerializer runtime.NegotiatedSerializer - - // Codec specifies the encoding and decoding behavior for runtime.Objects passed - // to a RESTClient or Client. Required when initializing a RESTClient, optional - // when initializing a Client. - // - // DEPRECATED: Please use NegotiatedSerializer instead. - // Codec is currently used only in some tests and will be removed soon. - // All production setups should use NegotiatedSerializer. - Codec runtime.Codec } // RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config @@ -158,6 +159,14 @@ func RESTClientFor(config *Config) (*RESTClient, error) { if config.NegotiatedSerializer == nil { return nil, fmt.Errorf("NegotiatedSerializer is required when initializing a RESTClient") } + qps := config.QPS + if config.QPS == 0.0 { + qps = DefaultQPS + } + burst := config.Burst + if config.Burst == 0 { + burst = DefaultBurst + } baseURL, versionedAPIPath, err := defaultServerUrlFor(config) if err != nil { @@ -174,7 +183,7 @@ func RESTClientFor(config *Config) (*RESTClient, error) { httpClient = &http.Client{Transport: transport} } - return NewRESTClient(baseURL, versionedAPIPath, config.ContentConfig, config.QPS, config.Burst, config.RateLimiter, httpClient) + return NewRESTClient(baseURL, versionedAPIPath, config.ContentConfig, qps, burst, config.RateLimiter, httpClient) } // UnversionedRESTClientFor is the same as RESTClientFor, except that it allows @@ -214,12 +223,6 @@ func SetKubernetesDefaults(config *Config) error { if len(config.UserAgent) == 0 { config.UserAgent = DefaultKubernetesUserAgent() } - if config.QPS == 0.0 { - config.QPS = 5.0 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } @@ -240,7 +243,7 @@ func DefaultKubernetesUserAgent() string { // InClusterConfig returns a config object which uses the service account // kubernetes gives to pods. It's intended for clients that expect to be -// running inside a pod running on kuberenetes. It will return an error if +// running inside a pod running on kubernetes. It will return an error if // called from a process not running in a kubernetes environment. func InClusterConfig() (*Config, error) { host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/plugin.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/plugin.go index 4752e375bc71..06ac3cce1639 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/plugin.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/plugin.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/request.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/request.go index 9fd3f0ddb091..dd1bbb35a535 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/request.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/request.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package restclient import ( "bytes" + "encoding/hex" "fmt" "io" "io/ioutil" @@ -143,7 +144,10 @@ func NewRequest(client HTTPClient, verb string, baseURL *url.URL, versionedAPIPa backoffMgr: backoff, throttle: throttle, } - if len(content.ContentType) > 0 { + switch { + case len(content.AcceptContentTypes) > 0: + r.SetHeader("Accept", content.AcceptContentTypes) + case len(content.ContentType) > 0: r.SetHeader("Accept", content.ContentType+", */*") } return r @@ -538,10 +542,10 @@ func (r *Request) Body(obj interface{}) *Request { r.err = err return r } - glog.V(8).Infof("Request Body: %s", string(data)) + glog.V(8).Infof("Request Body: %#v", string(data)) r.body = bytes.NewReader(data) case []byte: - glog.V(8).Infof("Request Body: %s", string(t)) + glog.V(8).Infof("Request Body: %#v", string(t)) r.body = bytes.NewReader(t) case io.Reader: r.body = t @@ -555,7 +559,7 @@ func (r *Request) Body(obj interface{}) *Request { r.err = err return r } - glog.V(8).Infof("Request Body: %s", string(data)) + glog.V(8).Infof("Request Body: %#v", string(data)) r.body = bytes.NewReader(data) r.SetHeader("Content-Type", r.content.ContentType) default: @@ -573,7 +577,7 @@ func (r *Request) URL() *url.URL { if len(r.resource) != 0 { p = path.Join(p, strings.ToLower(r.resource)) } - // Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compat if nothing was changed + // Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compatibility if nothing was changed if len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 { p = path.Join(p, r.resourceName, r.subresource, r.subpath) } @@ -888,16 +892,49 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu body = data } } - glog.V(8).Infof("Response Body: %s", string(body)) + + if glog.V(8) { + switch { + case bytes.IndexFunc(body, func(r rune) bool { return r < 0x0a }) != -1: + glog.Infof("Response Body:\n%s", hex.Dump(body)) + default: + glog.Infof("Response Body: %s", string(body)) + } + } + + // verify the content type is accurate + contentType := resp.Header.Get("Content-Type") + decoder := r.serializers.Decoder + if len(contentType) > 0 && (decoder == nil || (len(r.content.ContentType) > 0 && contentType != r.content.ContentType)) { + mediaType, params, err := mime.ParseMediaType(contentType) + if err != nil { + return Result{err: errors.NewInternalError(err)} + } + decoder, err = r.serializers.RenegotiatedDecoder(mediaType, params) + if err != nil { + // if we fail to negotiate a decoder, treat this as an unstructured error + switch { + case resp.StatusCode == http.StatusSwitchingProtocols: + // no-op, we've been upgraded + case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent: + return Result{err: r.transformUnstructuredResponseError(resp, req, body)} + } + return Result{ + body: body, + contentType: contentType, + statusCode: resp.StatusCode, + } + } + } // Did the server give us a status response? isStatusResponse := false + status := &unversioned.Status{} // Because release-1.1 server returns Status with empty APIVersion at paths // to the Extensions resources, we need to use DecodeInto here to provide // default groupVersion, otherwise a status response won't be correctly // decoded. - status := &unversioned.Status{} - err := runtime.DecodeInto(r.serializers.Decoder, body, status) + err := runtime.DecodeInto(decoder, body, status) if err == nil && len(status.Status) > 0 { isStatusResponse = true } @@ -919,25 +956,6 @@ func (r *Request) transformResponse(resp *http.Response, req *http.Request) Resu return Result{err: errors.FromObject(status)} } - contentType := resp.Header.Get("Content-Type") - var decoder runtime.Decoder - if contentType == r.content.ContentType { - decoder = r.serializers.Decoder - } else { - mediaType, params, err := mime.ParseMediaType(contentType) - if err != nil { - return Result{err: errors.NewInternalError(err)} - } - decoder, err = r.serializers.RenegotiatedDecoder(mediaType, params) - if err != nil { - return Result{ - body: body, - contentType: contentType, - statusCode: resp.StatusCode, - } - } - } - return Result{ body: body, contentType: contentType, @@ -970,7 +988,7 @@ func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *h body = data } } - glog.V(8).Infof("Response Body: %s", string(body)) + glog.V(8).Infof("Response Body: %#v", string(body)) message := "unknown" if isTextResponse(resp) { diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/transport.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/transport.go index 0bfa2ea2720a..c385914e2900 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/transport.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/transport.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/url_utils.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/url_utils.go index 9a83d787472b..81f16d63eaf4 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/url_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/url_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ func DefaultServerURL(host, apiPath string, groupVersion unversioned.GroupVersio if err != nil { return nil, "", err } - if hostURL.Scheme == "" { + if hostURL.Scheme == "" || hostURL.Host == "" { scheme := "http://" if defaultTLS { scheme = "https://" diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go index 6c672f08af6a..24a89ed975cc 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/urlbackoff.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/restclient/versions.go b/vendor/k8s.io/kubernetes/pkg/client/restclient/versions.go index e12c05c10f70..33764344744b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/restclient/versions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/restclient/versions.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/testing/core/actions.go b/vendor/k8s.io/kubernetes/pkg/client/testing/core/actions.go index 70f5b14fd398..837dbd762ddd 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/testing/core/actions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/testing/core/actions.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ limitations under the License. package core import ( + "path" "strings" "k8s.io/kubernetes/pkg/api" @@ -118,30 +119,46 @@ func NewUpdateAction(resource unversioned.GroupVersionResource, namespace string return action } -func NewRootPatchAction(resource unversioned.GroupVersionResource, object runtime.Object) PatchActionImpl { +func NewRootPatchAction(resource unversioned.GroupVersionResource, name string, patch []byte) PatchActionImpl { action := PatchActionImpl{} action.Verb = "patch" action.Resource = resource - action.Object = object + action.Name = name + action.Patch = patch return action } -func NewPatchAction(resource unversioned.GroupVersionResource, namespace string, object runtime.Object) PatchActionImpl { +func NewPatchAction(resource unversioned.GroupVersionResource, namespace string, name string, patch []byte) PatchActionImpl { action := PatchActionImpl{} action.Verb = "patch" action.Resource = resource action.Namespace = namespace - action.Object = object + action.Name = name + action.Patch = patch return action } -func NewPatchSubresourceAction(resource unversioned.GroupVersionResource, subresource string) PatchActionImpl { +func NewRootPatchSubresourceAction(resource unversioned.GroupVersionResource, name string, patch []byte, subresources ...string) PatchActionImpl { action := PatchActionImpl{} action.Verb = "patch" action.Resource = resource - action.Subresource = subresource + action.Subresource = path.Join(subresources...) + action.Name = name + action.Patch = patch + + return action +} + +func NewPatchSubresourceAction(resource unversioned.GroupVersionResource, namespace, name string, patch []byte, subresources ...string) PatchActionImpl { + action := PatchActionImpl{} + action.Verb = "patch" + action.Resource = resource + action.Subresource = path.Join(subresources...) + action.Namespace = namespace + action.Name = name + action.Patch = patch return action } @@ -401,11 +418,16 @@ func (a UpdateActionImpl) GetObject() runtime.Object { type PatchActionImpl struct { ActionImpl - Object runtime.Object + Name string + Patch []byte } -func (a PatchActionImpl) GetObject() runtime.Object { - return a.Object +func (a PatchActionImpl) GetName() string { + return a.Name +} + +func (a PatchActionImpl) GetPatch() []byte { + return a.Patch } type DeleteActionImpl struct { diff --git a/vendor/k8s.io/kubernetes/pkg/client/testing/core/fake.go b/vendor/k8s.io/kubernetes/pkg/client/testing/core/fake.go index 751780b1d6a8..c04ea1f40ec7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/testing/core/fake.go +++ b/vendor/k8s.io/kubernetes/pkg/client/testing/core/fake.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/testing/core/fixture.go b/vendor/k8s.io/kubernetes/pkg/client/testing/core/fixture.go index bd4e560064e0..9902e49860e4 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/testing/core/fixture.go +++ b/vendor/k8s.io/kubernetes/pkg/client/testing/core/fixture.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,28 +18,39 @@ package core import ( "fmt" - "io/ioutil" - "reflect" - "strings" + "sync" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util/yaml" "k8s.io/kubernetes/pkg/watch" ) -// ObjectRetriever abstracts the implementation for retrieving or setting generic -// objects. It is intended to be used to fake calls to a server by returning -// objects based on their kind and name. -type ObjectRetriever interface { - // Kind should return a resource or a list of resources (depending on the provided kind and - // name). It should return an error if the caller should communicate an error to the server. - Kind(gvk unversioned.GroupVersionKind, name string) (runtime.Object, error) - // Add adds a runtime object for test purposes into this object. - Add(runtime.Object) error +// ObjectTracker keeps track of objects. It is intended to be used to +// fake calls to a server by returning objects based on their kind, +// namespace and name. +type ObjectTracker interface { + // Add adds an object to the tracker. If object being added + // is a list, its items are added separately. + Add(obj runtime.Object) error + + // Get retrieves the object by its kind, namespace and name. + Get(gvk unversioned.GroupVersionKind, ns, name string) (runtime.Object, error) + + // Update updates an existing object in the tracker. + Update(obj runtime.Object) error + + // List retrieves all objects of a given kind in the given + // namespace. Only non-List kinds are accepted. + List(gvk unversioned.GroupVersionKind, ns string) (runtime.Object, error) + + // Delete deletes an existing object from the tracker. If object + // didn't exist in the tracker prior to deletion, Delete returns + // no error. + Delete(gvk unversioned.GroupVersionKind, ns, name string) error } // ObjectScheme abstracts the implementation of common operations on objects. @@ -49,55 +60,78 @@ type ObjectScheme interface { runtime.ObjectTyper } -// ObjectReaction returns a ReactionFunc that takes a generic action string of the form -// - or -- and attempts to return a runtime -// Object or error that matches the requested action. For instance, list-replicationControllers -// should attempt to return a list of replication controllers. This method delegates to the -// ObjectRetriever interface to satisfy retrieval of lists or retrieval of single items. -// TODO: add support for sub resources -func ObjectReaction(o ObjectRetriever, mapper meta.RESTMapper) ReactionFunc { +// ObjectReaction returns a ReactionFunc that applies core.Action to +// the given tracker. +func ObjectReaction(tracker ObjectTracker, mapper meta.RESTMapper) ReactionFunc { return func(action Action) (bool, runtime.Object, error) { - resource := action.GetResource() - kind, err := mapper.KindFor(resource) + ns := action.GetNamespace() + gvr := action.GetResource() + + gvk, err := mapper.KindFor(gvr) + if err != nil { + return false, nil, fmt.Errorf("error getting kind for resource %q: %s", gvr, err) + } + // This is a temporary fix. Because there is no internal resource, so // the caller has no way to express that it expects to get an internal // kind back. A more proper fix will be directly specify the Kind when // build the action. - kind.Version = resource.Version - if err != nil { - return false, nil, fmt.Errorf("unrecognized action %s: %v", action.GetResource(), err) + gvk.Version = gvr.Version + if len(gvk.Version) == 0 { + gvk.Version = runtime.APIVersionInternal } - // TODO: have mapper return a Kind for a subresource? - switch castAction := action.(type) { - case ListAction: - kind.Kind += "List" - resource, err := o.Kind(kind, "") - return true, resource, err + // Here and below we need to switch on implementation types, + // not on interfaces, as some interfaces are identical + // (e.g. UpdateAction and CreateAction), so if we use them, + // updates and creates end up matching the same case branch. + switch action := action.(type) { - case GetAction: - resource, err := o.Kind(kind, castAction.GetName()) - return true, resource, err + case ListActionImpl: + obj, err := tracker.List(gvk, ns) + return true, obj, err - case DeleteAction: - resource, err := o.Kind(kind, castAction.GetName()) - return true, resource, err + case GetActionImpl: + obj, err := tracker.Get(gvk, ns, action.GetName()) + return true, obj, err + + case CreateActionImpl: + objMeta, err := meta.Accessor(action.GetObject()) + if err != nil { + return true, nil, err + } + if action.GetSubresource() == "" { + err = tracker.Add(action.GetObject()) + } else { + // TODO: Currently we're handling subresource creation as an update + // on the enclosing resource. This works for some subresources but + // might not be generic enough. + err = tracker.Update(action.GetObject()) + } + if err != nil { + return true, nil, err + } + obj, err := tracker.Get(gvk, ns, objMeta.GetName()) + return true, obj, err - case CreateAction: - accessor, err := meta.Accessor(castAction.GetObject()) + case UpdateActionImpl: + objMeta, err := meta.Accessor(action.GetObject()) if err != nil { return true, nil, err } - resource, err := o.Kind(kind, accessor.GetName()) - return true, resource, err + err = tracker.Update(action.GetObject()) + if err != nil { + return true, nil, err + } + obj, err := tracker.Get(gvk, ns, objMeta.GetName()) + return true, obj, err - case UpdateAction: - accessor, err := meta.Accessor(castAction.GetObject()) + case DeleteActionImpl: + err := tracker.Delete(gvk, ns, action.GetName()) if err != nil { return true, nil, err } - resource, err := o.Kind(kind, accessor.GetName()) - return true, resource, err + return true, nil, nil default: return false, nil, fmt.Errorf("no reaction implemented for %s", action) @@ -105,140 +139,276 @@ func ObjectReaction(o ObjectRetriever, mapper meta.RESTMapper) ReactionFunc { } } -// AddObjectsFromPath loads the JSON or YAML file containing Kubernetes API resources -// and adds them to the provided ObjectRetriever. -func AddObjectsFromPath(path string, o ObjectRetriever, decoder runtime.Decoder) error { - data, err := ioutil.ReadFile(path) - if err != nil { - return err - } - data, err = yaml.ToJSON(data) - if err != nil { - return err - } - obj, err := runtime.Decode(decoder, data) - if err != nil { - return err - } - if err := o.Add(obj); err != nil { - return err - } - return nil -} - -type objects struct { - types map[string][]runtime.Object - last map[string]int +type tracker struct { scheme ObjectScheme decoder runtime.Decoder + lock sync.RWMutex + objects map[unversioned.GroupVersionKind][]runtime.Object } -var _ ObjectRetriever = &objects{} - -// NewObjects implements the ObjectRetriever interface by introspecting the -// objects provided to Add() and returning them when the Kind method is invoked. -// If an api.List object is provided to Add(), each child item is added. If an -// object is added that is itself a list (PodList, ServiceList) then that is added -// to the "PodList" kind. If no PodList is added, the retriever will take any loaded -// Pods and return them in a list. If an api.Status is added, and the Details.Kind field -// is set, that status will be returned instead (as an error if Status != Success, or -// as a runtime.Object if Status == Success). If multiple PodLists are provided, they -// will be returned in order by the Kind call, and the last PodList will be reused for -// subsequent calls. -func NewObjects(scheme ObjectScheme, decoder runtime.Decoder) ObjectRetriever { - return objects{ - types: make(map[string][]runtime.Object), - last: make(map[string]int), +var _ ObjectTracker = &tracker{} + +// NewObjectTracker returns an ObjectTracker that can be used to keep track +// of objects for the fake clientset. Mostly useful for unit tests. +func NewObjectTracker(scheme ObjectScheme, decoder runtime.Decoder) ObjectTracker { + return &tracker{ scheme: scheme, decoder: decoder, + objects: make(map[unversioned.GroupVersionKind][]runtime.Object), } } -func (o objects) Kind(kind unversioned.GroupVersionKind, name string) (runtime.Object, error) { - if len(kind.Version) == 0 { - kind.Version = runtime.APIVersionInternal +func (t *tracker) List(gvk unversioned.GroupVersionKind, ns string) (runtime.Object, error) { + // Heuristic for list kind: original kind + List suffix. Might + // not always be true but this tracker has a pretty limited + // understanding of the actual API model. + listGVK := gvk + listGVK.Kind = listGVK.Kind + "List" + + list, err := t.scheme.New(listGVK) + if err != nil { + return nil, err + } + + if !meta.IsListType(list) { + return nil, fmt.Errorf("%q is not a list type", listGVK.Kind) } - empty, err := o.scheme.New(kind) - nilValue := reflect.Zero(reflect.TypeOf(empty)).Interface().(runtime.Object) - arr, ok := o.types[kind.Kind] + t.lock.RLock() + defer t.lock.RUnlock() + + objs, ok := t.objects[gvk] if !ok { - if strings.HasSuffix(kind.Kind, "List") { - itemKind := kind.Kind[:len(kind.Kind)-4] - arr, ok := o.types[itemKind] - if !ok { - return empty, nil - } - out, err := o.scheme.New(kind) - if err != nil { - return nilValue, err - } - if err := meta.SetList(out, arr); err != nil { - return nilValue, err - } - if out, err = o.scheme.Copy(out); err != nil { - return nilValue, err - } - return out, nil - } - return nilValue, errors.NewNotFound(unversioned.GroupResource{Group: kind.Group, Resource: kind.Kind}, name) + return list, nil } - index := o.last[kind.Kind] - if index >= len(arr) { - index = len(arr) - 1 + matchingObjs, err := filterByNamespaceAndName(objs, ns, "") + if err != nil { + return nil, err } - if index < 0 { - return nilValue, errors.NewNotFound(unversioned.GroupResource{Group: kind.Group, Resource: kind.Kind}, name) + if err := meta.SetList(list, matchingObjs); err != nil { + return nil, err + } + if list, err = t.scheme.Copy(list); err != nil { + return nil, err + } + return list, nil +} + +func (t *tracker) Get(gvk unversioned.GroupVersionKind, ns, name string) (runtime.Object, error) { + if err := checkNamespace(gvk, ns); err != nil { + return nil, err } - out, err := o.scheme.Copy(arr[index]) + + errNotFound := errors.NewNotFound(unversioned.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, name) + + t.lock.RLock() + defer t.lock.RUnlock() + + objs, ok := t.objects[gvk] + if !ok { + return nil, errNotFound + } + + matchingObjs, err := filterByNamespaceAndName(objs, ns, name) + if err != nil { + return nil, err + } + if len(matchingObjs) == 0 { + return nil, errNotFound + } + if len(matchingObjs) > 1 { + return nil, fmt.Errorf("more than one object matched gvk %s, ns: %q name: %q", gvk, ns, name) + } + + // Only one object should match in the tracker if it works + // correctly, as Add/Update methods enforce kind/namespace/name + // uniqueness. + obj, err := t.scheme.Copy(matchingObjs[0]) if err != nil { - return nilValue, err + return nil, err } - o.last[kind.Kind] = index + 1 - if status, ok := out.(*unversioned.Status); ok { + if status, ok := obj.(*unversioned.Status); ok { if status.Details != nil { - status.Details.Kind = kind.Kind + status.Details.Kind = gvk.Kind } if status.Status != unversioned.StatusSuccess { - return nilValue, &errors.StatusError{ErrStatus: *status} + return nil, &errors.StatusError{ErrStatus: *status} } } - return out, nil + return obj, nil +} + +func (t *tracker) Add(obj runtime.Object) error { + return t.add(obj, false) +} + +func (t *tracker) Update(obj runtime.Object) error { + return t.add(obj, true) } -func (o objects) Add(obj runtime.Object) error { - gvks, _, err := o.scheme.ObjectKinds(obj) +func (t *tracker) add(obj runtime.Object, replaceExisting bool) error { + if meta.IsListType(obj) { + return t.addList(obj, replaceExisting) + } + + gvks, _, err := t.scheme.ObjectKinds(obj) if err != nil { return err } - kind := gvks[0].Kind + if len(gvks) == 0 { + return fmt.Errorf("no registered kinds for %v", obj) + } + + t.lock.Lock() + defer t.lock.Unlock() - switch { - case meta.IsListType(obj): - if kind != "List" { - o.types[kind] = append(o.types[kind], obj) + for _, gvk := range gvks { + gr := unversioned.GroupResource{Group: gvk.Group, Resource: gvk.Kind} + + // To avoid the object from being accidentally modified by caller + // after it's been added to the tracker, we always store the deep + // copy. + obj, err = t.scheme.Copy(obj) + if err != nil { + return err + } + + if status, ok := obj.(*unversioned.Status); ok && status.Details != nil { + gvk.Kind = status.Details.Kind } - list, err := meta.ExtractList(obj) + newMeta, err := meta.Accessor(obj) if err != nil { return err } - if errs := runtime.DecodeList(list, o.decoder); len(errs) > 0 { - return errs[0] + + if err := checkNamespace(gvk, newMeta.GetNamespace()); err != nil { + return err } - for _, obj := range list { - if err := o.Add(obj); err != nil { + + for i, existingObj := range t.objects[gvk] { + oldMeta, err := meta.Accessor(existingObj) + if err != nil { return err } + if oldMeta.GetNamespace() == newMeta.GetNamespace() && oldMeta.GetName() == newMeta.GetName() { + if replaceExisting { + t.objects[gvk][i] = obj + return nil + } + return errors.NewAlreadyExists(gr, newMeta.GetName()) + } } - default: - if status, ok := obj.(*unversioned.Status); ok && status.Details != nil { - kind = status.Details.Kind + + if replaceExisting { + // Tried to update but no matching object was found. + return errors.NewNotFound(gr, newMeta.GetName()) + } + + t.objects[gvk] = append(t.objects[gvk], obj) + } + + return nil +} + +func (t *tracker) addList(obj runtime.Object, replaceExisting bool) error { + list, err := meta.ExtractList(obj) + if err != nil { + return err + } + errs := runtime.DecodeList(list, t.decoder) + if len(errs) > 0 { + return errs[0] + } + for _, obj := range list { + err := t.add(obj, replaceExisting) + if err != nil { + return err + } + } + return nil +} + +func (t *tracker) Delete(gvk unversioned.GroupVersionKind, ns, name string) error { + if err := checkNamespace(gvk, ns); err != nil { + return err + } + + t.lock.Lock() + defer t.lock.Unlock() + + found := false + + for i, existingObj := range t.objects[gvk] { + objMeta, err := meta.Accessor(existingObj) + if err != nil { + return err + } + if objMeta.GetNamespace() == ns && objMeta.GetName() == name { + t.objects[gvk] = append(t.objects[gvk][:i], t.objects[gvk][i+1:]...) + found = true + } + } + + if found { + return nil + } + + return errors.NewNotFound(unversioned.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, name) +} + +// filterByNamespaceAndName returns all objects in the collection that +// match provided namespace and name. Empty namespace matches +// non-namespaced objects. +func filterByNamespaceAndName(objs []runtime.Object, ns, name string) ([]runtime.Object, error) { + var res []runtime.Object + + for _, obj := range objs { + acc, err := meta.Accessor(obj) + if err != nil { + return nil, err + } + if ns != "" && acc.GetNamespace() != ns { + continue + } + if name != "" && acc.GetName() != name { + continue + } + res = append(res, obj) + } + + return res, nil +} + +// checkNamespace makes sure that the scope of gvk matches ns. It +// returns an error if namespace is empty but gvk is a namespaced +// kind, or if ns is non-empty and gvk is a namespaced kind. +func checkNamespace(gvk unversioned.GroupVersionKind, ns string) error { + group, err := registered.Group(gvk.Group) + if err != nil { + return err + } + mapping, err := group.RESTMapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err != nil { + return err + } + switch mapping.Scope.Name() { + case meta.RESTScopeNameRoot: + if ns != "" { + return fmt.Errorf("namespace specified for a non-namespaced kind %s", gvk) + } + case meta.RESTScopeNameNamespace: + if ns == "" { + // Skipping this check for Events, since + // controllers emit events that have no namespace, + // even though Event is a namespaced resource. + if gvk.Kind != "Event" { + return fmt.Errorf("no namespace specified for a namespaced kind %s", gvk) + } } - o.types[kind] = append(o.types[kind], obj) } return nil diff --git a/vendor/k8s.io/kubernetes/pkg/client/transport/cache.go b/vendor/k8s.io/kubernetes/pkg/client/transport/cache.go index 8c07f5391a3e..eedfd3d78b3e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/transport/cache.go +++ b/vendor/k8s.io/kubernetes/pkg/client/transport/cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/transport/config.go b/vendor/k8s.io/kubernetes/pkg/client/transport/config.go index 63a63fbb4795..6e5c68a30b23 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/transport/config.go +++ b/vendor/k8s.io/kubernetes/pkg/client/transport/config.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/transport/round_trippers.go b/vendor/k8s.io/kubernetes/pkg/client/transport/round_trippers.go index 55284ebc65f7..aadf0cbf9a23 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/transport/round_trippers.go +++ b/vendor/k8s.io/kubernetes/pkg/client/transport/round_trippers.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/transport/transport.go b/vendor/k8s.io/kubernetes/pkg/client/transport/transport.go index 2d20e1b878a6..9c5b9ef3c32c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/transport/transport.go +++ b/vendor/k8s.io/kubernetes/pkg/client/transport/transport.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go index 283dd5a63e8b..1bd18b9548c8 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/discovery_client.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -81,6 +81,8 @@ type SwaggerSchemaInterface interface { // versions and resources. type DiscoveryClient struct { *restclient.RESTClient + + LegacyPrefix string } // Convert unversioned.APIVersions to unversioned.APIGroup. APIVersions is used by legacy v1, so @@ -105,7 +107,7 @@ func apiVersionsToAPIGroup(apiVersions *unversioned.APIVersions) (apiGroup unver func (d *DiscoveryClient) ServerGroups() (apiGroupList *unversioned.APIGroupList, err error) { // Get the groupVersions exposed at /api v := &unversioned.APIVersions{} - err = d.Get().AbsPath("/api").Do().Into(v) + err = d.Get().AbsPath(d.LegacyPrefix).Do().Into(v) apiGroup := unversioned.APIGroup{} if err == nil { apiGroup = apiVersionsToAPIGroup(v) @@ -135,8 +137,9 @@ func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (r url := url.URL{} if len(groupVersion) == 0 { return nil, fmt.Errorf("groupVersion shouldn't be empty") - } else if groupVersion == "v1" { - url.Path = "/api/" + groupVersion + } + if len(d.LegacyPrefix) > 0 && groupVersion == "v1" { + url.Path = d.LegacyPrefix + "/" + groupVersion } else { url.Path = "/apis/" + groupVersion } @@ -245,8 +248,8 @@ func (d *DiscoveryClient) SwaggerSchema(version unversioned.GroupVersion) (*swag return nil, fmt.Errorf("API version: %v is not supported by the server. Use one of: %v", version, groupVersions) } var path string - if version == v1.SchemeGroupVersion { - path = "/swaggerapi/api/" + version.Version + if len(d.LegacyPrefix) > 0 && version == v1.SchemeGroupVersion { + path = "/swaggerapi" + d.LegacyPrefix + "/" + version.Version } else { path = "/swaggerapi/apis/" + version.Group + "/" + version.Version } @@ -285,7 +288,7 @@ func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) return nil, err } client, err := restclient.UnversionedRESTClientFor(&config) - return &DiscoveryClient{client}, err + return &DiscoveryClient{RESTClient: client, LegacyPrefix: "/api"}, err } // NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. If @@ -301,7 +304,7 @@ func NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient { // New creates a new DiscoveryClient for the given RESTClient. func NewDiscoveryClient(c *restclient.RESTClient) *DiscoveryClient { - return &DiscoveryClient{c} + return &DiscoveryClient{RESTClient: c, LegacyPrefix: "/api"} } func stringDoesntExistIn(str string, slice []string) bool { diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/fake/discovery.go b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/fake/discovery.go index 1c230acf02aa..25b48c076a50 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/fake/discovery.go +++ b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/fake/discovery.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client.go b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client.go index 26369bd58234..5b8e1481ebcb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -58,6 +58,7 @@ func NewClient(conf *restclient.Config) (*Client, error) { // TODO: it's questionable that this should be using anything other than unstructured schema and JSON conf.ContentType = runtime.ContentTypeJSON + conf.AcceptContentTypes = runtime.ContentTypeJSON streamingInfo, _ := api.Codecs.StreamingSerializerForMediaType("application/json;stream=watch", nil) conf.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec}, streamingInfo) @@ -69,13 +70,6 @@ func NewClient(conf *restclient.Config) (*Client, error) { conf.UserAgent = restclient.DefaultKubernetesUserAgent() } - if conf.QPS == 0.0 { - conf.QPS = 5.0 - } - if conf.Burst == 0 { - conf.Burst = 10 - } - cl, err := restclient.RESTClientFor(conf) if err != nil { return nil, err diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client_pool.go b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client_pool.go index f7c6505fd773..5723ed708f6d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client_pool.go +++ b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/client_pool.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/dynamic_util.go b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/dynamic_util.go index 094f838115b1..4ffe313e61e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/dynamic_util.go +++ b/vendor/k8s.io/kubernetes/pkg/client/typed/dynamic/dynamic_util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ func NewDiscoveryRESTMapper(resources []*unversioned.APIResourceList, versionFun return rm, nil } -// ObjectTyper provides an ObjectTyper implmentation for +// ObjectTyper provides an ObjectTyper implementation for // runtime.Unstructured object based on discovery information. type ObjectTyper struct { registered map[unversioned.GroupVersionKind]bool diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/apps.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/apps.go index 1905c29c2467..f2498cbb5661 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/apps.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/apps.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -71,13 +71,6 @@ func setAppsDefaults(config *restclient.Config) error { config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go index 64b3ef6becdf..128597f93a69 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/auth/clientauth.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go index 9e543c9d3aeb..188a5ea78da0 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/autoscaling.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -72,13 +72,6 @@ func setAutoscalingDefaults(config *restclient.Config) error { config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/batch.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/batch.go index 40fc49dc121f..c31652f41d82 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/batch.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/batch.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -102,13 +102,6 @@ func setBatchDefaults(config *restclient.Config, gv *unversioned.GroupVersion) e config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificates.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificates.go new file mode 100644 index 000000000000..29b15c45ef30 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificates.go @@ -0,0 +1,86 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apimachinery/registered" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/client/restclient" +) + +// Interface holds the methods for clients of Kubernetes to allow mock testing. +type CertificatesInterface interface { + CertificateSigningRequests() CertificateSigningRequestInterface +} + +type CertificatesClient struct { + *restclient.RESTClient +} + +func (c *CertificatesClient) CertificateSigningRequests() CertificateSigningRequestInterface { + return newCertificateSigningRequests(c) +} + +// NewCertificates creates a new CertificatesClient for the given config. +func NewCertificates(c *restclient.Config) (*CertificatesClient, error) { + config := *c + if err := setCertificatesDefaults(&config); err != nil { + return nil, err + } + client, err := restclient.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &CertificatesClient{client}, nil +} + +// NewCertificatesOrDie creates a new CertificatesClient for the given config and +// panics if there is an error in the config. +func NewCertificatesOrDie(c *restclient.Config) *CertificatesClient { + client, err := NewCertificates(c) + if err != nil { + panic(err) + } + return client +} + +func setCertificatesDefaults(config *restclient.Config) error { + // if certificates group is not registered, return an error + g, err := registered.Group(certificates.GroupName) + if err != nil { + return err + } + config.APIPath = defaultAPIPath + if config.UserAgent == "" { + config.UserAgent = restclient.DefaultKubernetesUserAgent() + } + // TODO: Unconditionally set the config.Version, until we fix the config. + //if config.Version == "" { + copyGroupVersion := g.GroupVersion + config.GroupVersion = ©GroupVersion + //} + + config.NegotiatedSerializer = api.Codecs + if config.QPS == 0 { + config.QPS = 5 + } + if config.Burst == 0 { + config.Burst = 10 + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificatesigningrequests.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificatesigningrequests.go new file mode 100644 index 000000000000..f3ce09fc387b --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/certificatesigningrequests.go @@ -0,0 +1,104 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/watch" +) + +// CertificateSigningRequestInterface has methods to work with CertificateSigningRequest resources. +type CertificateSigningRequestInterface interface { + List(opts api.ListOptions) (*certificates.CertificateSigningRequestList, error) + Get(name string) (*certificates.CertificateSigningRequest, error) + Delete(name string, options *api.DeleteOptions) error + Create(certificateSigningRequest *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + Update(certificateSigningRequest *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + UpdateStatus(certificateSigningRequest *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + UpdateApproval(certificateSigningRequest *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) + Watch(opts api.ListOptions) (watch.Interface, error) +} + +// certificateSigningRequests implements CertificateSigningRequestsNamespacer interface +type certificateSigningRequests struct { + client *CertificatesClient +} + +// newCertificateSigningRequests returns a certificateSigningRequests +func newCertificateSigningRequests(c *CertificatesClient) *certificateSigningRequests { + return &certificateSigningRequests{ + client: c, + } +} + +// List takes label and field selectors, and returns the list of certificateSigningRequests that match those selectors. +func (c *certificateSigningRequests) List(opts api.ListOptions) (result *certificates.CertificateSigningRequestList, err error) { + result = &certificates.CertificateSigningRequestList{} + err = c.client.Get().Resource("certificatesigningrequests").VersionedParams(&opts, api.ParameterCodec).Do().Into(result) + return +} + +// Get takes the name of the certificateSigningRequest, and returns the corresponding CertificateSigningRequest object, and an error if it occurs +func (c *certificateSigningRequests) Get(name string) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Get().Resource("certificatesigningrequests").Name(name).Do().Into(result) + return +} + +// Delete takes the name of the certificateSigningRequest and deletes it. Returns an error if one occurs. +func (c *certificateSigningRequests) Delete(name string, options *api.DeleteOptions) error { + return c.client.Delete().Resource("certificatesigningrequests").Name(name).Body(options).Do().Error() +} + +// Create takes the representation of a certificateSigningRequest and creates it. Returns the server's representation of the certificateSigningRequest, and an error, if it occurs. +func (c *certificateSigningRequests) Create(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Post().Resource("certificatesigningrequests").Body(certificateSigningRequest).Do().Into(result) + return +} + +// Update takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if it occurs. +func (c *certificateSigningRequests) Update(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Put().Resource("certificatesigningrequests").Name(certificateSigningRequest.Name).Body(certificateSigningRequest).Do().Into(result) + return +} + +// UpdateStatus takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if it occurs. +func (c *certificateSigningRequests) UpdateStatus(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Put().Resource("certificatesigningrequests").Name(certificateSigningRequest.Name).SubResource("status").Body(certificateSigningRequest).Do().Into(result) + return +} + +// UpdateApproval takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if it occurs. +func (c *certificateSigningRequests) UpdateApproval(certificateSigningRequest *certificates.CertificateSigningRequest) (result *certificates.CertificateSigningRequest, err error) { + result = &certificates.CertificateSigningRequest{} + err = c.client.Put().Resource("certificatesigningrequests").Name(certificateSigningRequest.Name).SubResource("approval").Body(certificateSigningRequest).Do().Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested certificateSigningRequests. +func (c *certificateSigningRequests) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.client.Get(). + Prefix("watch"). + Namespace(api.NamespaceAll). + Resource("certificatesigningrequests"). + VersionedParams(&opts, api.ParameterCodec). + Watch() +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/client.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/client.go index df68040042f4..d8047cd4a1c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/client.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/client.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -44,11 +44,13 @@ type Interface interface { PersistentVolumeClaimsNamespacer ComponentStatusesInterface ConfigMapsNamespacer + Apps() AppsInterface Autoscaling() AutoscalingInterface Batch() BatchInterface Extensions() ExtensionsInterface Rbac() RbacInterface Discovery() discovery.DiscoveryInterface + Certificates() CertificatesInterface } func (c *Client) ReplicationControllers(namespace string) ReplicationControllerInterface { @@ -124,6 +126,7 @@ type Client struct { *PolicyClient *RbacClient *discovery.DiscoveryClient + *CertificatesClient } // IsTimeout tests if this is a timeout error in the underlying transport. @@ -171,3 +174,7 @@ func (c *Client) Rbac() RbacInterface { func (c *Client) Discovery() discovery.DiscoveryInterface { return c.DiscoveryClient } + +func (c *Client) Certificates() CertificatesInterface { + return c.CertificatesClient +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers.go index 87330c5009f1..43e26487cbe7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest/latest.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest/latest.go index 48cedb82ea50..0b9a4270c0ee 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest/latest.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest/latest.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/register.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/register.go index f26a6cd1b11b..5426e7fef409 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/register.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go index 56b44e8f42ab..95b5289f4601 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/conversion.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/conversion.go index e03fc60b164b..e22e5f81ec70 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/register.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/register.go index e5c9e88ef99a..dcdb533c0d39 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/register.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go index 46b5dbaa72d3..77bce80a3bb0 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/v1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/auth_loaders.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/auth_loaders.go index 8b10ce2bcba1..0abc425c0c76 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/auth_loaders.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/auth_loaders.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go index c83f315a3187..47b14e215acf 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/client_config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/config.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/config.go index ec5948609f19..9df69a74128a 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/config.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/doc.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/doc.go index 7e8f9b4e3adb..30ef6f36daf9 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader.go index 8988355de65b..10094062279c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -230,14 +230,17 @@ func (rules *ClientConfigLoadingRules) Migrate() error { if _, err := os.Stat(destination); err == nil { // if the destination already exists, do nothing continue + } else if os.IsPermission(err) { + // if we can't access the file, skip it + continue } else if !os.IsNotExist(err) { // if we had an error other than non-existence, fail return err } if sourceInfo, err := os.Stat(source); err != nil { - if os.IsNotExist(err) { - // if the source file doesn't exist, there's no work to do. + if os.IsNotExist(err) || os.IsPermission(err) { + // if the source file doesn't exist or we can't access it, there's no work to do. continue } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go index 52c1493d056e..0180469127f7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/merged_client_builder.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go index f6dda97f1cbd..40a35e65d6cc 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/overrides.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -124,12 +124,12 @@ const ( // RecommendedAuthOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing func RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags { return AuthOverrideFlags{ - ClientCertificate: FlagInfo{prefix + FlagCertFile, "", "", "Path to a client certificate file for TLS."}, - ClientKey: FlagInfo{prefix + FlagKeyFile, "", "", "Path to a client key file for TLS."}, - Token: FlagInfo{prefix + FlagBearerToken, "", "", "Bearer token for authentication to the API server."}, - Impersonate: FlagInfo{prefix + FlagImpersonate, "", "", "Username to impersonate for the operation."}, - Username: FlagInfo{prefix + FlagUsername, "", "", "Username for basic authentication to the API server."}, - Password: FlagInfo{prefix + FlagPassword, "", "", "Password for basic authentication to the API server."}, + ClientCertificate: FlagInfo{prefix + FlagCertFile, "", "", "Path to a client certificate file for TLS"}, + ClientKey: FlagInfo{prefix + FlagKeyFile, "", "", "Path to a client key file for TLS"}, + Token: FlagInfo{prefix + FlagBearerToken, "", "", "Bearer token for authentication to the API server"}, + Impersonate: FlagInfo{prefix + FlagImpersonate, "", "", "Username to impersonate for the operation"}, + Username: FlagInfo{prefix + FlagUsername, "", "", "Username for basic authentication to the API server"}, + Password: FlagInfo{prefix + FlagPassword, "", "", "Password for basic authentication to the API server"}, } } @@ -138,8 +138,8 @@ func RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags { return ClusterOverrideFlags{ APIServer: FlagInfo{prefix + FlagAPIServer, "", "", "The address and port of the Kubernetes API server"}, APIVersion: FlagInfo{prefix + FlagAPIVersion, "", "", "DEPRECATED: The API version to use when talking to the server"}, - CertificateAuthority: FlagInfo{prefix + FlagCAFile, "", "", "Path to a cert. file for the certificate authority."}, - InsecureSkipTLSVerify: FlagInfo{prefix + FlagInsecure, "", "false", "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure."}, + CertificateAuthority: FlagInfo{prefix + FlagCAFile, "", "", "Path to a cert. file for the certificate authority"}, + InsecureSkipTLSVerify: FlagInfo{prefix + FlagInsecure, "", "false", "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure"}, } } @@ -158,7 +158,7 @@ func RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags { return ContextOverrideFlags{ ClusterName: FlagInfo{prefix + FlagClusterName, "", "", "The name of the kubeconfig cluster to use"}, AuthInfoName: FlagInfo{prefix + FlagAuthInfoName, "", "", "The name of the kubeconfig user to use"}, - Namespace: FlagInfo{prefix + FlagNamespace, "", "", "If present, the namespace scope for this CLI request."}, + Namespace: FlagInfo{prefix + FlagNamespace, "", "", "If present, the namespace scope for this CLI request"}, } } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation.go index 1690f515e936..63f8adec629e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clientcmd/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterrolebindings.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterrolebindings.go index 2a9d79846f35..fa9cad97d3e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterrolebindings.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterrolebindings.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterroles.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterroles.go index 0d2d375d619a..165271ab504e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterroles.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/clusterroles.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/componentstatuses.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/componentstatuses.go index 0717cdec1242..aca996b2b000 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/componentstatuses.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/componentstatuses.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/conditions.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/conditions.go index f68f98fe121e..5c284292bffe 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/conditions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/conditions.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/configmap.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/configmap.go index 60fffa755796..c2f20354f4a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/configmap.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/configmap.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/containerinfo.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/containerinfo.go index 306386852ff6..2f9aae8ab384 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/containerinfo.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/containerinfo.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets.go index fa12591a6588..7ec9182f8aec 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/daemon_sets.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/deployment.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/deployment.go index cafd4cfd1d39..a5e8afe947fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/deployment.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/deployment.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/doc.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/doc.go index 252d80975816..dac3925b4afb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/endpoints.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/endpoints.go index c58c88a28d13..6e20a347eb58 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/endpoints.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/endpoints.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/events.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/events.go index b882ccdc47e6..3421bd8117eb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/events.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/events.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/extensions.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/extensions.go index 3c9114d9a88c..c83846f92416 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/extensions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/extensions.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ type ExtensionsInterface interface { ThirdPartyResourceNamespacer ReplicaSetsNamespacer PodSecurityPoliciesInterface + StorageClassesInterface } // ExtensionsClient is used to interact with experimental Kubernetes features. @@ -82,6 +83,10 @@ func (c *ExtensionsClient) ReplicaSets(namespace string) ReplicaSetInterface { return newReplicaSets(c, namespace) } +func (c *ExtensionsClient) StorageClasses() StorageClassInterface { + return newStorageClasses(c) +} + // NewExtensions creates a new ExtensionsClient for the given config. This client // provides access to experimental Kubernetes features. // Features of Extensions group are not supported and may be changed or removed in @@ -126,13 +131,6 @@ func setExtensionsDefaults(config *restclient.Config) error { config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/flags.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/flags.go index 9fc540cfbda9..7d32a259df33 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/flags.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/flags.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/helper.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/helper.go index 020bb01c26d8..84757692df7d 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/helper.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/helper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import ( "k8s.io/kubernetes/pkg/apis/apps" "k8s.io/kubernetes/pkg/apis/autoscaling" "k8s.io/kubernetes/pkg/apis/batch" + "k8s.io/kubernetes/pkg/apis/certificates" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/apis/policy" "k8s.io/kubernetes/pkg/apis/rbac" @@ -95,6 +96,14 @@ func New(c *restclient.Config) (*Client, error) { return nil, err } } + var certsClient *CertificatesClient + if registered.IsRegistered(certificates.GroupName) { + certsConfig := *c + certsClient, err = NewCertificates(&certsConfig) + if err != nil { + return nil, err + } + } var appsClient *AppsClient if registered.IsRegistered(apps.GroupName) { @@ -114,7 +123,7 @@ func New(c *restclient.Config) (*Client, error) { } } - return &Client{RESTClient: client, AutoscalingClient: autoscalingClient, BatchClient: batchClient, ExtensionsClient: extensionsClient, DiscoveryClient: discoveryClient, AppsClient: appsClient, PolicyClient: policyClient, RbacClient: rbacClient}, nil + return &Client{RESTClient: client, AutoscalingClient: autoscalingClient, BatchClient: batchClient, CertificatesClient: certsClient, ExtensionsClient: extensionsClient, DiscoveryClient: discoveryClient, AppsClient: appsClient, PolicyClient: policyClient, RbacClient: rbacClient}, nil } // MatchesServerVersion queries the server to compares the build version @@ -134,7 +143,7 @@ func MatchesServerVersion(client *Client, c *restclient.Config) error { return fmt.Errorf("couldn't read version from server: %v\n", err) } // GitVersion includes GitCommit and GitTreeState, but best to be safe? - if cVer.GitVersion != sVer.GitVersion || cVer.GitCommit != sVer.GitCommit || cVer.GitTreeState != cVer.GitTreeState { + if cVer.GitVersion != sVer.GitVersion || cVer.GitCommit != sVer.GitCommit || cVer.GitTreeState != sVer.GitTreeState { return fmt.Errorf("server version (%#v) differs from client version (%#v)!\n", sVer, cVer) } @@ -193,6 +202,11 @@ func NegotiateVersion(client *Client, c *restclient.Config, requestedGV *unversi return nil, fmt.Errorf("client does not support API version %q; client supported API versions: %v", preferredGV, clientVersions) } + // If the server supports no versions, then we should just use the preferredGV + // This can happen because discovery fails due to 403 Forbidden errors + if len(serverVersions) == 0 { + return preferredGV, nil + } if serverVersions.Has(preferredGV.String()) { return preferredGV, nil } @@ -254,9 +268,6 @@ func SetKubernetesDefaults(config *restclient.Config) error { if config.NegotiatedSerializer == nil { config.NegotiatedSerializer = api.Codecs } - if config.Codec == nil { - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) - } return restclient.SetKubernetesDefaults(config) } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler.go index 8cdba3a265cf..76c6a9cf9d78 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/horizontalpodautoscaler.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go index bbe61472dcae..8508573c0a61 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/import_known_versions.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import ( _ "k8s.io/kubernetes/pkg/apis/authorization/install" _ "k8s.io/kubernetes/pkg/apis/autoscaling/install" _ "k8s.io/kubernetes/pkg/apis/batch/install" + _ "k8s.io/kubernetes/pkg/apis/certificates/install" _ "k8s.io/kubernetes/pkg/apis/componentconfig/install" _ "k8s.io/kubernetes/pkg/apis/extensions/install" _ "k8s.io/kubernetes/pkg/apis/policy/install" diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/ingress.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/ingress.go index 4865b20862f9..59c6a6d9f8ea 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/ingress.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/ingress.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/jobs.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/jobs.go index 94b819079a92..14cfa3a30b83 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/jobs.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/jobs.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges.go index 8bc2253da914..914a049f4467 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/limit_ranges.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/namespaces.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/namespaces.go index 122bcba50853..b4a38361ca67 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/namespaces.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/namespaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/network_policys.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/network_policys.go index 0dc9d97be893..3e3f61045d71 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/network_policys.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/network_policys.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/nodes.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/nodes.go index 452a03f1691f..15a7db2ad188 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/nodes.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/nodes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ type NodeInterface interface { Create(node *api.Node) (*api.Node, error) List(opts api.ListOptions) (*api.NodeList, error) Delete(name string) error + DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error Update(*api.Node) (*api.Node, error) UpdateStatus(*api.Node) (*api.Node, error) Watch(opts api.ListOptions) (watch.Interface, error) @@ -76,6 +77,16 @@ func (c *nodes) Delete(name string) error { return c.r.Delete().Resource(c.resourceName()).Name(name).Do().Error() } +// DeleteCollection deletes a collection of nodes. +func (c *nodes) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { + return c.r.Delete(). + Resource(c.resourceName()). + VersionedParams(&listOptions, api.ParameterCodec). + Body(options). + Do(). + Error() +} + // Update updates an existing node. func (c *nodes) Update(node *api.Node) (*api.Node, error) { result := &api.Node{} diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim.go index bf5447d7589b..4ea3a95a761b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumeclaim.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumes.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumes.go index 2de17bb7183a..5fce1f0a452b 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumes.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/persistentvolumes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pet_sets.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pet_sets.go index 71b1ea021763..954efcd09223 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pet_sets.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pet_sets.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_disruption_budgets.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_disruption_budgets.go index 14f373f37601..0239623a7bcb 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_disruption_budgets.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_disruption_budgets.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_templates.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_templates.go index ed5b733c6781..7627d735f55c 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_templates.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pod_templates.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pods.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pods.go index 426d3ee8e960..ea16fb87d694 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/pods.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/pods.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy.go index 356d913dbea7..f03e643f26dd 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/podsecuritypolicy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/policy.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/policy.go index 8b06ce275ac4..9a47d7917351 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/policy.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/policy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -71,13 +71,6 @@ func setPolicyDefaults(config *restclient.Config) error { config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/rbac.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/rbac.go index 76ec392c3e47..09b2b4073e0f 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/rbac.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/rbac.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -91,13 +91,6 @@ func setRbacDefaults(config *restclient.Config) error { config.GroupVersion = ©GroupVersion //} - config.Codec = api.Codecs.LegacyCodec(*config.GroupVersion) config.NegotiatedSerializer = api.Codecs - if config.QPS == 0 { - config.QPS = 5 - } - if config.Burst == 0 { - config.Burst = 10 - } return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/replica_sets.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/replica_sets.go index be9284084f71..191a006b6043 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/replica_sets.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/replica_sets.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers.go index f237a76acf3f..e4b9e2d992f7 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/replication_controllers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas.go index acfd8ddb32ce..9944cef9bb8e 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/resource_quotas.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/rolebindings.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/rolebindings.go index a43815c55268..b79838010d10 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/rolebindings.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/rolebindings.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/roles.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/roles.go index 29aee1baee76..b265e787b503 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/roles.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/roles.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/scale.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/scale.go index 705f6048b59c..a55b0777dbc6 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/scale.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/scale.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/scheduledjobs.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/scheduledjobs.go index d2b83fce2009..de07a7e5de75 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/scheduledjobs.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/scheduledjobs.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/secrets.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/secrets.go index 33d77ad249d3..bba3fd936954 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/secrets.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/secrets.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/service_accounts.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/service_accounts.go index d78a25c473a1..68d1b2112a25 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/service_accounts.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/service_accounts.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/services.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/services.go index 8b40a5d0484b..aada5c164a62 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/services.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/services.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/storageclasses.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/storageclasses.go new file mode 100644 index 000000000000..7c5c0b4e72dd --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/storageclasses.go @@ -0,0 +1,87 @@ +/* +Copyright 2016 The Kubernetes 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 unversioned + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/watch" +) + +type StorageClassesInterface interface { + StorageClasses() StorageClassInterface +} + +// StorageClassInterface has methods to work with StorageClass resources. +type StorageClassInterface interface { + List(opts api.ListOptions) (*extensions.StorageClassList, error) + Get(name string) (*extensions.StorageClass, error) + Create(storageClass *extensions.StorageClass) (*extensions.StorageClass, error) + Update(storageClass *extensions.StorageClass) (*extensions.StorageClass, error) + Delete(name string) error + Watch(opts api.ListOptions) (watch.Interface, error) +} + +// storageClasses implements StorageClassInterface +type storageClasses struct { + client *ExtensionsClient +} + +func newStorageClasses(c *ExtensionsClient) *storageClasses { + return &storageClasses{c} +} + +func (c *storageClasses) List(opts api.ListOptions) (result *extensions.StorageClassList, err error) { + result = &extensions.StorageClassList{} + err = c.client.Get(). + Resource("storageclasses"). + VersionedParams(&opts, api.ParameterCodec). + Do(). + Into(result) + + return result, err +} + +func (c *storageClasses) Get(name string) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Get().Resource("storageClasses").Name(name).Do().Into(result) + return +} + +func (c *storageClasses) Create(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Post().Resource("storageClasses").Body(storageClass).Do().Into(result) + return +} + +func (c *storageClasses) Update(storageClass *extensions.StorageClass) (result *extensions.StorageClass, err error) { + result = &extensions.StorageClass{} + err = c.client.Put().Resource("storageClasses").Name(storageClass.Name).Body(storageClass).Do().Into(result) + return +} + +func (c *storageClasses) Delete(name string) error { + return c.client.Delete().Resource("storageClasses").Name(name).Do().Error() +} + +func (c *storageClasses) Watch(opts api.ListOptions) (watch.Interface, error) { + return c.client.Get(). + Prefix("watch"). + Resource("storageClasses"). + VersionedParams(&opts, api.ParameterCodec). + Watch() +} diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources.go index 0908db06eb72..68adddbe7c19 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/thirdpartyresources.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/client/unversioned/util.go b/vendor/k8s.io/kubernetes/pkg/client/unversioned/util.go index 37ada3c3d67c..9657ff2a9f20 100644 --- a/vendor/k8s.io/kubernetes/pkg/client/unversioned/util.go +++ b/vendor/k8s.io/kubernetes/pkg/client/unversioned/util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/cloud.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/cloud.go index 0190ed50ac75..cb5b68189178 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/cloud.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/cloud.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -81,13 +81,16 @@ type LoadBalancer interface { // GetLoadBalancer returns whether the specified load balancer exists, and // if so, what its status is. // Implementations must treat the *api.Service parameter as read-only and not modify it. - GetLoadBalancer(service *api.Service) (status *api.LoadBalancerStatus, exists bool, err error) + // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager + GetLoadBalancer(clusterName string, service *api.Service) (status *api.LoadBalancerStatus, exists bool, err error) // EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer // Implementations must treat the *api.Service parameter as read-only and not modify it. - EnsureLoadBalancer(service *api.Service, hosts []string) (*api.LoadBalancerStatus, error) + // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager + EnsureLoadBalancer(clusterName string, service *api.Service, hosts []string) (*api.LoadBalancerStatus, error) // UpdateLoadBalancer updates hosts under the specified load balancer. // Implementations must treat the *api.Service parameter as read-only and not modify it. - UpdateLoadBalancer(service *api.Service, hosts []string) error + // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager + UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error // EnsureLoadBalancerDeleted deletes the specified load balancer if it // exists, returning nil if the load balancer specified either didn't exist or // was successfully deleted. @@ -95,7 +98,8 @@ type LoadBalancer interface { // have multiple underlying components, meaning a Get could say that the LB // doesn't exist even if some part of it is still laying around. // Implementations must treat the *api.Service parameter as read-only and not modify it. - EnsureLoadBalancerDeleted(service *api.Service) error + // Parameter 'clusterName' is the name of the cluster as presented to kube-controller-manager + EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error } // Instances is an abstract, pluggable interface for sets of instances. @@ -106,12 +110,11 @@ type Instances interface { // make this clearer. NodeAddresses(name string) ([]api.NodeAddress, error) // ExternalID returns the cloud provider ID of the specified instance (deprecated). + // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) ExternalID(name string) (string, error) // InstanceID returns the cloud provider ID of the specified instance. - // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) InstanceID(name string) (string, error) // InstanceType returns the type of the specified instance. - // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) InstanceType(name string) (string, error) // List lists instances that match 'filter' which is a regular expression which must match the entire instance name (fqdn) List(filter string) ([]string, error) diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/doc.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/doc.go index eaa91e6cf253..7192394c3964 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/plugins.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/plugins.go index ad39e34051ce..670400f628fe 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go index a2f9836f302d..e83ddd475930 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -300,6 +300,17 @@ type CloudConfig struct { //has setup a rule that allows inbound traffic on kubelet ports from the //local VPC subnet (so load balancers can access it). E.g. 10.82.0.0/16 30000-32000. DisableSecurityGroupIngress bool + + //During the instantiation of an new AWS cloud provider, the detected region + //is validated against a known set of regions. + // + //In a non-standard, AWS like environment (e.g. Eucalyptus), this check may + //be undesirable. Setting this to true will disable the check and provide + //a warning that the check was skipped. Please note that this is an + //experimental feature and work-in-progress for the moment. If you find + //yourself in an non-AWS cloud and open an issue, please indicate that in the + //issue body. + DisableStrictZoneCheck bool } } @@ -664,9 +675,13 @@ func newAWSCloud(config io.Reader, awsServices Services) (*Cloud, error) { return nil, err } - valid := isRegionValid(regionName) - if !valid { - return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone) + if !cfg.Global.DisableStrictZoneCheck { + valid := isRegionValid(regionName) + if !valid { + return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone) + } + } else { + glog.Warningf("Strict AWS zone checking is disabled. Proceeding with zone: %s", zone) } ec2, err := awsServices.Compute(regionName) @@ -1174,8 +1189,8 @@ func newAWSDisk(aws *Cloud, name string) (*awsDisk, error) { // The original idea of the URL-style name was to put the AZ into the // host, so we could find the AZ immediately from the name without // querying the API. But it turns out we don't actually need it for - // Ubernetes-Lite, as we put the AZ into the labels on the PV instead. - // However, if in future we want to support Ubernetes-Lite + // multi-AZ clusters, as we put the AZ into the labels on the PV instead. + // However, if in future we want to support multi-AZ cluster // volume-awareness without using PersistentVolumes, we likely will // want the AZ in the host. @@ -1422,7 +1437,7 @@ func (c *Cloud) DetachDisk(diskName string, instanceName string) (string, error) } if !alreadyAttached { - glog.Warning("DetachDisk called on non-attached disk: ", diskName) + glog.Warningf("DetachDisk called on non-attached disk: %s", diskName) // TODO: Continue? Tolerate non-attached error in DetachVolume? } @@ -2282,10 +2297,10 @@ func buildListener(port api.ServicePort, annotations map[string]string, sslPorts } // EnsureLoadBalancer implements LoadBalancer.EnsureLoadBalancer -func (c *Cloud) EnsureLoadBalancer(apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { +func (c *Cloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { annotations := apiService.Annotations - glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", - apiService.Namespace, apiService.Name, c.region, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, annotations) + glog.V(2).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v, %v)", + clusterName, apiService.Namespace, apiService.Name, c.region, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, annotations) if apiService.Spec.SessionAffinity != api.ServiceAffinityNone { // ELB supports sticky sessions, but only when configured for HTTP/HTTPS @@ -2457,7 +2472,7 @@ func (c *Cloud) EnsureLoadBalancer(apiService *api.Service, hosts []string) (*ap } // GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer -func (c *Cloud) GetLoadBalancer(service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (c *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) lb, err := c.describeLoadBalancer(loadBalancerName) if err != nil { @@ -2673,7 +2688,7 @@ func (c *Cloud) updateInstanceSecurityGroupsForLoadBalancer(lb *elb.LoadBalancer } // EnsureLoadBalancerDeleted implements LoadBalancer.EnsureLoadBalancerDeleted. -func (c *Cloud) EnsureLoadBalancerDeleted(service *api.Service) error { +func (c *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) lb, err := c.describeLoadBalancer(loadBalancerName) if err != nil { @@ -2769,7 +2784,7 @@ func (c *Cloud) EnsureLoadBalancerDeleted(service *api.Service) error { } // UpdateLoadBalancer implements LoadBalancer.UpdateLoadBalancer -func (c *Cloud) UpdateLoadBalancer(service *api.Service, hosts []string) error { +func (c *Cloud) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { hostSet := sets.NewString(hosts...) instances, err := c.getInstancesByNodeNamesCached(hostSet) if err != nil { diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go index 5edbb3da992c..af3ff541a0a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_instancegroups.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go index 85b2f2d50c5b..0e20acdda244 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_loadbalancer.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ func (c *Cloud) ensureLoadBalancer(namespacedName types.NamespacedName, loadBala {Key: aws.String(TagNameKubernetesService), Value: aws.String(namespacedName.String())}, } - glog.Infof("Creating load balancer for %v with name: ", namespacedName, loadBalancerName) + glog.Infof("Creating load balancer for %v with name: %s", namespacedName, loadBalancerName) _, err := c.elb.CreateLoadBalancer(createRequest) if err != nil { return nil, err diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go index 63a9e2e5ae25..981405993486 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_routes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go index 0067ded7f08b..361b93e7fafa 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/aws_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go index 177c7074a8f4..f1c88fd1e426 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/log_handler.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/retry_handler.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/retry_handler.go index 6e6657bf0b42..49a50ef5c501 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/retry_handler.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/retry_handler.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/sets_ippermissions.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/sets_ippermissions.go index 2e1343ff8d96..8a268c4b0e27 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/sets_ippermissions.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/aws/sets_ippermissions.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/OWNERS b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/OWNERS new file mode 100644 index 000000000000..120b921b3cf9 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/OWNERS @@ -0,0 +1,3 @@ +assignees: + - colemickens + - brendandburns diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure.go new file mode 100644 index 000000000000..8fefc76a6528 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure.go @@ -0,0 +1,173 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "io" + "io/ioutil" + + "k8s.io/kubernetes/pkg/cloudprovider" + + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/ghodss/yaml" +) + +// CloudProviderName is the value used for the --cloud-provider flag +const CloudProviderName = "azure" + +// Config holds the configuration parsed from the --cloud-config flag +type Config struct { + Cloud string `json:"cloud" yaml:"cloud"` + TenantID string `json:"tenantId" yaml:"tenantId"` + SubscriptionID string `json:"subscriptionId" yaml:"subscriptionId"` + ResourceGroup string `json:"resourceGroup" yaml:"resourceGroup"` + Location string `json:"location" yaml:"location"` + VnetName string `json:"vnetName" yaml:"vnetName"` + SubnetName string `json:"subnetName" yaml:"subnetName"` + SecurityGroupName string `json:"securityGroupName" yaml:"securityGroupName"` + RouteTableName string `json:"routeTableName" yaml:"routeTableName"` + + AADClientID string `json:"aadClientId" yaml:"aadClientId"` + AADClientSecret string `json:"aadClientSecret" yaml:"aadClientSecret"` + AADTenantID string `json:"aadTenantId" yaml:"aadTenantId"` +} + +// Cloud holds the config and clients +type Cloud struct { + Config + Environment azure.Environment + RoutesClient network.RoutesClient + SubnetsClient network.SubnetsClient + InterfacesClient network.InterfacesClient + RouteTablesClient network.RouteTablesClient + LoadBalancerClient network.LoadBalancersClient + PublicIPAddressesClient network.PublicIPAddressesClient + SecurityGroupsClient network.SecurityGroupsClient + VirtualMachinesClient compute.VirtualMachinesClient +} + +func init() { + cloudprovider.RegisterCloudProvider(CloudProviderName, NewCloud) +} + +// NewCloud returns a Cloud with initialized clients +func NewCloud(configReader io.Reader) (cloudprovider.Interface, error) { + var az Cloud + + configContents, err := ioutil.ReadAll(configReader) + if err != nil { + return nil, err + } + err = yaml.Unmarshal(configContents, &az) + if err != nil { + return nil, err + } + + if az.Cloud == "" { + az.Environment = azure.PublicCloud + } else { + az.Environment, err = azure.EnvironmentFromName(az.Cloud) + if err != nil { + return nil, err + } + } + + oauthConfig, err := az.Environment.OAuthConfigForTenant(az.TenantID) + if err != nil { + return nil, err + } + + servicePrincipalToken, err := azure.NewServicePrincipalToken( + *oauthConfig, + az.AADClientID, + az.AADClientSecret, + az.Environment.ServiceManagementEndpoint) + if err != nil { + return nil, err + } + + az.SubnetsClient = network.NewSubnetsClient(az.SubscriptionID) + az.SubnetsClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.SubnetsClient.Authorizer = servicePrincipalToken + + az.RouteTablesClient = network.NewRouteTablesClient(az.SubscriptionID) + az.RouteTablesClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.RouteTablesClient.Authorizer = servicePrincipalToken + + az.RoutesClient = network.NewRoutesClient(az.SubscriptionID) + az.RoutesClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.RoutesClient.Authorizer = servicePrincipalToken + + az.InterfacesClient = network.NewInterfacesClient(az.SubscriptionID) + az.InterfacesClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.InterfacesClient.Authorizer = servicePrincipalToken + + az.LoadBalancerClient = network.NewLoadBalancersClient(az.SubscriptionID) + az.LoadBalancerClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.LoadBalancerClient.Authorizer = servicePrincipalToken + + az.VirtualMachinesClient = compute.NewVirtualMachinesClient(az.SubscriptionID) + az.VirtualMachinesClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.VirtualMachinesClient.Authorizer = servicePrincipalToken + + az.PublicIPAddressesClient = network.NewPublicIPAddressesClient(az.SubscriptionID) + az.PublicIPAddressesClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.PublicIPAddressesClient.Authorizer = servicePrincipalToken + + az.SecurityGroupsClient = network.NewSecurityGroupsClient(az.SubscriptionID) + az.SecurityGroupsClient.BaseURI = az.Environment.ResourceManagerEndpoint + az.SecurityGroupsClient.Authorizer = servicePrincipalToken + + return &az, nil +} + +// LoadBalancer returns a balancer interface. Also returns true if the interface is supported, false otherwise. +func (az *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) { + return az, true +} + +// Instances returns an instances interface. Also returns true if the interface is supported, false otherwise. +func (az *Cloud) Instances() (cloudprovider.Instances, bool) { + return az, true +} + +// Zones returns a zones interface. Also returns true if the interface is supported, false otherwise. +func (az *Cloud) Zones() (cloudprovider.Zones, bool) { + return az, true +} + +// Clusters returns a clusters interface. Also returns true if the interface is supported, false otherwise. +func (az *Cloud) Clusters() (cloudprovider.Clusters, bool) { + return nil, false +} + +// Routes returns a routes interface along with whether the interface is supported. +func (az *Cloud) Routes() (cloudprovider.Routes, bool) { + return az, true +} + +// ScrubDNS provides an opportunity for cloud-provider-specific code to process DNS settings for pods. +func (az *Cloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) { + return nameservers, searches +} + +// ProviderName returns the cloud provider ID. +func (az *Cloud) ProviderName() string { + return CloudProviderName +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_instances.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_instances.go new file mode 100644 index 000000000000..b80adb00c345 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_instances.go @@ -0,0 +1,146 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "fmt" + "regexp" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/cloudprovider" + + "github.com/Azure/azure-sdk-for-go/arm/compute" +) + +// NodeAddresses returns the addresses of the specified instance. +func (az *Cloud) NodeAddresses(name string) ([]api.NodeAddress, error) { + ip, err := az.getIPForMachine(name) + if err != nil { + return nil, err + } + + return []api.NodeAddress{ + {Type: api.NodeInternalIP, Address: ip}, + {Type: api.NodeHostName, Address: name}, + }, nil +} + +// ExternalID returns the cloud provider ID of the specified instance (deprecated). +func (az *Cloud) ExternalID(name string) (string, error) { + return az.InstanceID(name) +} + +// InstanceID returns the cloud provider ID of the specified instance. +// Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) +func (az *Cloud) InstanceID(name string) (string, error) { + machine, exists, err := az.getVirtualMachine(name) + if err != nil { + return "", err + } else if !exists { + return "", cloudprovider.InstanceNotFound + } + return *machine.ID, nil +} + +// InstanceType returns the type of the specified instance. +// Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) +// (Implementer Note): This is used by kubelet. Kubelet will label the node. Real log from kubelet: +// Adding node label from cloud provider: beta.kubernetes.io/instance-type=[value] +func (az *Cloud) InstanceType(name string) (string, error) { + machine, exists, err := az.getVirtualMachine(name) + if err != nil { + return "", err + } else if !exists { + return "", cloudprovider.InstanceNotFound + } + return string(machine.Properties.HardwareProfile.VMSize), nil +} + +// List lists instances that match 'filter' which is a regular expression which must match the entire instance name (fqdn) +func (az *Cloud) List(filter string) ([]string, error) { + allNodes, err := az.listAllNodesInResourceGroup() + if err != nil { + return nil, err + } + + filteredNodes, err := filterNodes(allNodes, filter) + if err != nil { + return nil, err + } + + nodeNames := make([]string, len(filteredNodes)) + for i, v := range filteredNodes { + nodeNames[i] = *v.Name + } + + return nodeNames, nil +} + +// AddSSHKeyToAllInstances adds an SSH public key as a legal identity for all instances +// expected format for the key is standard ssh-keygen format: +func (az *Cloud) AddSSHKeyToAllInstances(user string, keyData []byte) error { + return fmt.Errorf("not supported") +} + +// CurrentNodeName returns the name of the node we are currently running on +// On most clouds (e.g. GCE) this is the hostname, so we provide the hostname +func (az *Cloud) CurrentNodeName(hostname string) (string, error) { + return hostname, nil +} + +func (az *Cloud) listAllNodesInResourceGroup() ([]compute.VirtualMachine, error) { + allNodes := []compute.VirtualMachine{} + + result, err := az.VirtualMachinesClient.List(az.ResourceGroup) + if err != nil { + return nil, err + } + + morePages := (result.Value != nil && len(*result.Value) > 1) + + for morePages { + allNodes = append(allNodes, *result.Value...) + + result, err = az.VirtualMachinesClient.ListAllNextResults(result) + if err != nil { + return nil, err + } + + morePages = (result.Value != nil && len(*result.Value) > 1) + } + + return allNodes, nil + +} + +func filterNodes(nodes []compute.VirtualMachine, filter string) ([]compute.VirtualMachine, error) { + filteredNodes := []compute.VirtualMachine{} + + re, err := regexp.Compile(filter) + if err != nil { + return nil, err + } + + for _, node := range nodes { + // search tags + if re.MatchString(*node.Name) { + filteredNodes = append(filteredNodes, node) + } + } + + return filteredNodes, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_loadbalancer.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_loadbalancer.go new file mode 100644 index 000000000000..3d04c5f003c9 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_loadbalancer.go @@ -0,0 +1,611 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "fmt" + "strconv" + "strings" + + "k8s.io/kubernetes/pkg/api" + utilerrors "k8s.io/kubernetes/pkg/util/errors" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/Azure/go-autorest/autorest/to" + "github.com/golang/glog" +) + +// GetLoadBalancer returns whether the specified load balancer exists, and +// if so, what its status is. +func (az *Cloud) GetLoadBalancer(clusterName string, service *api.Service) (status *api.LoadBalancerStatus, exists bool, err error) { + lbName := getLoadBalancerName(clusterName) + pipName := getPublicIPName(clusterName, service) + serviceName := getServiceName(service) + + _, existsLb, err := az.getAzureLoadBalancer(lbName) + if err != nil { + return nil, false, err + } + if !existsLb { + glog.V(5).Infof("get(%s): lb(%s) - doesn't exist", serviceName, pipName) + return nil, false, nil + } + + pip, existsPip, err := az.getPublicIPAddress(pipName) + if err != nil { + return nil, false, err + } + if !existsPip { + glog.V(5).Infof("get(%s): pip(%s) - doesn't exist", serviceName, pipName) + return nil, false, nil + } + + return &api.LoadBalancerStatus{ + Ingress: []api.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, + }, true, nil +} + +// EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer +func (az *Cloud) EnsureLoadBalancer(clusterName string, service *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { + lbName := getLoadBalancerName(clusterName) + pipName := getPublicIPName(clusterName, service) + serviceName := getServiceName(service) + glog.V(2).Infof("ensure(%s): START clusterName=%q lbName=%q", serviceName, clusterName, lbName) + + pip, err := az.ensurePublicIPExists(serviceName, pipName) + if err != nil { + return nil, err + } + + sg, err := az.SecurityGroupsClient.Get(az.ResourceGroup, az.SecurityGroupName, "") + if err != nil { + return nil, err + } + sg, sgNeedsUpdate, err := az.reconcileSecurityGroup(sg, clusterName, service) + if err != nil { + return nil, err + } + if sgNeedsUpdate { + glog.V(3).Infof("ensure(%s): sg(%s) - updating", serviceName, *sg.Name) + _, err := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *sg.Name, sg, nil) + if err != nil { + return nil, err + } + } + + lb, existsLb, err := az.getAzureLoadBalancer(lbName) + if err != nil { + return nil, err + } + if !existsLb { + lb = network.LoadBalancer{ + Name: &lbName, + Location: &az.Location, + Properties: &network.LoadBalancerPropertiesFormat{}, + } + } + + lb, lbNeedsUpdate, err := az.reconcileLoadBalancer(lb, pip, clusterName, service, hosts) + if err != nil { + return nil, err + } + if !existsLb || lbNeedsUpdate { + glog.V(3).Infof("ensure(%s): lb(%s) - updating", serviceName, lbName) + _, err = az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) + if err != nil { + return nil, err + } + } + + // Add the machines to the backend pool if they're not already + lbBackendName := getBackendPoolName(clusterName) + lbBackendPoolID := az.getBackendPoolID(lbName, lbBackendName) + hostUpdates := make([]func() error, len(hosts)) + for i, host := range hosts { + localHost := host + f := func() error { + err := az.ensureHostInPool(serviceName, localHost, lbBackendPoolID) + if err != nil { + return fmt.Errorf("ensure(%s): lb(%s) - failed to ensure host in pool: %q", serviceName, lbName, err) + } + return nil + } + hostUpdates[i] = f + } + + errs := utilerrors.AggregateGoroutines(hostUpdates...) + if errs != nil { + return nil, utilerrors.Flatten(errs) + } + + glog.V(2).Infof("ensure(%s): FINISH - %s", service.Name, *pip.Properties.IPAddress) + return &api.LoadBalancerStatus{ + Ingress: []api.LoadBalancerIngress{{IP: *pip.Properties.IPAddress}}, + }, nil +} + +// UpdateLoadBalancer updates hosts under the specified load balancer. +func (az *Cloud) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { + _, err := az.EnsureLoadBalancer(clusterName, service, hosts) + return err +} + +// EnsureLoadBalancerDeleted deletes the specified load balancer if it +// exists, returning nil if the load balancer specified either didn't exist or +// was successfully deleted. +// This construction is useful because many cloud providers' load balancers +// have multiple underlying components, meaning a Get could say that the LB +// doesn't exist even if some part of it is still laying around. +func (az *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { + lbName := getLoadBalancerName(clusterName) + pipName := getPublicIPName(clusterName, service) + serviceName := getServiceName(service) + + glog.V(2).Infof("delete(%s): START clusterName=%q lbName=%q", serviceName, clusterName, lbName) + + // reconcile logic is capable of fully reconcile, so we can use this to delete + service.Spec.Ports = []api.ServicePort{} + + lb, existsLb, err := az.getAzureLoadBalancer(lbName) + if err != nil { + return err + } + if existsLb { + lb, lbNeedsUpdate, reconcileErr := az.reconcileLoadBalancer(lb, nil, clusterName, service, []string{}) + if reconcileErr != nil { + return reconcileErr + } + if lbNeedsUpdate { + if len(*lb.Properties.FrontendIPConfigurations) > 0 { + glog.V(3).Infof("delete(%s): lb(%s) - updating", serviceName, lbName) + _, err = az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) + if err != nil { + return err + } + } else { + glog.V(3).Infof("delete(%s): lb(%s) - deleting; no remaining frontendipconfigs", serviceName, lbName) + + _, err = az.LoadBalancerClient.Delete(az.ResourceGroup, lbName, nil) + if err != nil { + return err + } + } + } + } + + sg, existsSg, err := az.getSecurityGroup() + if err != nil { + return err + } + if existsSg { + reconciledSg, sgNeedsUpdate, reconcileErr := az.reconcileSecurityGroup(sg, clusterName, service) + if reconcileErr != nil { + return reconcileErr + } + if sgNeedsUpdate { + glog.V(3).Infof("delete(%s): sg(%s) - updating", serviceName, az.SecurityGroupName) + _, err := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *reconciledSg.Name, reconciledSg, nil) + if err != nil { + return err + } + } + } + + err = az.ensurePublicIPDeleted(serviceName, pipName) + if err != nil { + return err + } + + glog.V(2).Infof("delete(%s): FINISH", serviceName) + return nil +} + +func (az *Cloud) ensurePublicIPExists(serviceName, pipName string) (*network.PublicIPAddress, error) { + pip, existsPip, err := az.getPublicIPAddress(pipName) + if err != nil { + return nil, err + } + if existsPip { + return &pip, nil + } + + pip.Name = to.StringPtr(pipName) + pip.Location = to.StringPtr(az.Location) + pip.Properties = &network.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: network.Static, + } + pip.Tags = &map[string]*string{"service": &serviceName} + + glog.V(3).Infof("ensure(%s): pip(%s) - creating", serviceName, *pip.Name) + _, err = az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil) + if err != nil { + return nil, err + } + + pip, err = az.PublicIPAddressesClient.Get(az.ResourceGroup, *pip.Name, "") + if err != nil { + return nil, err + } + + return &pip, nil + +} + +func (az *Cloud) ensurePublicIPDeleted(serviceName, pipName string) error { + _, deleteErr := az.PublicIPAddressesClient.Delete(az.ResourceGroup, pipName, nil) + _, realErr := checkResourceExistsFromError(deleteErr) + if realErr != nil { + return nil + } + return nil +} + +// This ensures load balancer exists and the frontend ip config is setup. +// This also reconciles the Service's Ports with the LoadBalancer config. +// This entails adding rules/probes for expected Ports and removing stale rules/ports. +func (az *Cloud) reconcileLoadBalancer(lb network.LoadBalancer, pip *network.PublicIPAddress, clusterName string, service *api.Service, hosts []string) (network.LoadBalancer, bool, error) { + lbName := getLoadBalancerName(clusterName) + serviceName := getServiceName(service) + lbFrontendIPConfigName := getFrontendIPConfigName(service) + lbFrontendIPConfigID := az.getFrontendIPConfigID(lbName, lbFrontendIPConfigName) + lbBackendPoolName := getBackendPoolName(clusterName) + lbBackendPoolID := az.getBackendPoolID(lbName, lbBackendPoolName) + + wantLb := len(service.Spec.Ports) > 0 + dirtyLb := false + + // Ensure LoadBalancer's Backend Pool Configuration + if wantLb { + if lb.Properties.BackendAddressPools == nil || + len(*lb.Properties.BackendAddressPools) == 0 { + lb.Properties.BackendAddressPools = &[]network.BackendAddressPool{ + { + Name: to.StringPtr(lbBackendPoolName), + }, + } + glog.V(10).Infof("reconcile(%s)(%t): lb backendpool - adding", serviceName, wantLb) + dirtyLb = true + } else if len(*lb.Properties.BackendAddressPools) != 1 || + !strings.EqualFold(*(*lb.Properties.BackendAddressPools)[0].Name, lbBackendPoolName) { + return lb, false, fmt.Errorf("loadbalancer is misconfigured with a different backend pool") + } + } + + // Ensure LoadBalancer's Frontend IP Configurations + dirtyConfigs := false + newConfigs := []network.FrontendIPConfiguration{} + if lb.Properties.FrontendIPConfigurations != nil { + newConfigs = *lb.Properties.FrontendIPConfigurations + } + if !wantLb { + for i := len(newConfigs) - 1; i >= 0; i-- { + config := newConfigs[i] + if strings.EqualFold(*config.Name, lbFrontendIPConfigName) { + glog.V(3).Infof("reconcile(%s)(%t): lb frontendconfig(%s) - dropping", serviceName, wantLb, lbFrontendIPConfigName) + newConfigs = append(newConfigs[:i], newConfigs[i+1:]...) + dirtyConfigs = true + } + } + } else { + foundConfig := false + for _, config := range newConfigs { + if strings.EqualFold(*config.Name, lbFrontendIPConfigName) { + foundConfig = true + break + } + } + if !foundConfig { + newConfigs = append(newConfigs, + network.FrontendIPConfiguration{ + Name: to.StringPtr(lbFrontendIPConfigName), + Properties: &network.FrontendIPConfigurationPropertiesFormat{ + PublicIPAddress: &network.PublicIPAddress{ + ID: pip.ID, + }, + }, + }) + glog.V(10).Infof("reconcile(%s)(%t): lb frontendconfig(%s) - adding", serviceName, wantLb, lbFrontendIPConfigName) + dirtyConfigs = true + } + } + if dirtyConfigs { + dirtyLb = true + lb.Properties.FrontendIPConfigurations = &newConfigs + } + + // update probes/rules + expectedProbes := make([]network.Probe, len(service.Spec.Ports)) + expectedRules := make([]network.LoadBalancingRule, len(service.Spec.Ports)) + for i, port := range service.Spec.Ports { + lbRuleName := getRuleName(service, port) + + transportProto, _, probeProto, err := getProtocolsFromKubernetesProtocol(port.Protocol) + if err != nil { + return lb, false, err + } + + expectedProbes[i] = network.Probe{ + Name: &lbRuleName, + Properties: &network.ProbePropertiesFormat{ + Protocol: probeProto, + Port: to.Int32Ptr(port.NodePort), + IntervalInSeconds: to.Int32Ptr(5), + NumberOfProbes: to.Int32Ptr(2), + }, + } + + expectedRules[i] = network.LoadBalancingRule{ + Name: &lbRuleName, + Properties: &network.LoadBalancingRulePropertiesFormat{ + Protocol: transportProto, + FrontendIPConfiguration: &network.SubResource{ + ID: to.StringPtr(lbFrontendIPConfigID), + }, + BackendAddressPool: &network.SubResource{ + ID: to.StringPtr(lbBackendPoolID), + }, + Probe: &network.SubResource{ + ID: to.StringPtr(az.getLoadBalancerProbeID(lbName, lbRuleName)), + }, + FrontendPort: to.Int32Ptr(port.Port), + BackendPort: to.Int32Ptr(port.NodePort), + }, + } + } + + // remove unwated probes + dirtyProbes := false + var updatedProbes []network.Probe + if lb.Properties.Probes != nil { + updatedProbes = *lb.Properties.Probes + } + for i := len(updatedProbes) - 1; i >= 0; i-- { + existingProbe := updatedProbes[i] + if serviceOwnsRule(service, *existingProbe.Name) { + glog.V(10).Infof("reconcile(%s)(%t): lb probe(%s) - considering evicting", serviceName, wantLb, *existingProbe.Name) + keepProbe := false + if findProbe(expectedProbes, existingProbe) { + glog.V(10).Infof("reconcile(%s)(%t): lb probe(%s) - keeping", serviceName, wantLb, *existingProbe.Name) + keepProbe = true + } + if !keepProbe { + updatedProbes = append(updatedProbes[:i], updatedProbes[i+1:]...) + glog.V(10).Infof("reconcile(%s)(%t): lb probe(%s) - dropping", serviceName, wantLb, *existingProbe.Name) + dirtyProbes = true + } + } + } + // add missing, wanted probes + for _, expectedProbe := range expectedProbes { + foundProbe := false + if findProbe(updatedProbes, expectedProbe) { + glog.V(10).Infof("reconcile(%s)(%t): lb probe(%s) - already exists", serviceName, wantLb, *expectedProbe.Name) + foundProbe = true + } + if !foundProbe { + glog.V(10).Infof("reconcile(%s)(%t): lb probe(%s) - adding", serviceName, wantLb, *expectedProbe.Name) + updatedProbes = append(updatedProbes, expectedProbe) + dirtyProbes = true + } + } + if dirtyProbes { + dirtyLb = true + lb.Properties.Probes = &updatedProbes + } + + // update rules + dirtyRules := false + var updatedRules []network.LoadBalancingRule + if lb.Properties.LoadBalancingRules != nil { + updatedRules = *lb.Properties.LoadBalancingRules + } + // update rules: remove unwanted + for i := len(updatedRules) - 1; i >= 0; i-- { + existingRule := updatedRules[i] + if serviceOwnsRule(service, *existingRule.Name) { + keepRule := false + glog.V(10).Infof("reconcile(%s)(%t): lb rule(%s) - considering evicting", serviceName, wantLb, *existingRule.Name) + if findRule(expectedRules, existingRule) { + glog.V(10).Infof("reconcile(%s)(%t): lb rule(%s) - keeping", serviceName, wantLb, *existingRule.Name) + keepRule = true + } + if !keepRule { + glog.V(3).Infof("reconcile(%s)(%t): lb rule(%s) - dropping", serviceName, wantLb, *existingRule.Name) + updatedRules = append(updatedRules[:i], updatedRules[i+1:]...) + dirtyRules = true + } + } + } + // update rules: add needed + for _, expectedRule := range expectedRules { + foundRule := false + if findRule(updatedRules, expectedRule) { + glog.V(10).Infof("reconcile(%s)(%t): lb rule(%s) - already exists", serviceName, wantLb, *expectedRule.Name) + foundRule = true + } + if !foundRule { + glog.V(10).Infof("reconcile(%s)(%t): lb rule(%s) adding", serviceName, wantLb, *expectedRule.Name) + updatedRules = append(updatedRules, expectedRule) + dirtyRules = true + } + } + if dirtyRules { + dirtyLb = true + lb.Properties.LoadBalancingRules = &updatedRules + } + + return lb, dirtyLb, nil +} + +// This reconciles the Network Security Group similar to how the LB is reconciled. +// This entails adding required, missing SecurityRules and removing stale rules. +func (az *Cloud) reconcileSecurityGroup(sg network.SecurityGroup, clusterName string, service *api.Service) (network.SecurityGroup, bool, error) { + serviceName := getServiceName(service) + wantLb := len(service.Spec.Ports) > 0 + expectedSecurityRules := make([]network.SecurityRule, len(service.Spec.Ports)) + for i, port := range service.Spec.Ports { + securityRuleName := getRuleName(service, port) + _, securityProto, _, err := getProtocolsFromKubernetesProtocol(port.Protocol) + if err != nil { + return sg, false, err + } + + expectedSecurityRules[i] = network.SecurityRule{ + Name: to.StringPtr(securityRuleName), + Properties: &network.SecurityRulePropertiesFormat{ + Protocol: securityProto, + SourcePortRange: to.StringPtr("*"), + DestinationPortRange: to.StringPtr(strconv.Itoa(int(port.NodePort))), + SourceAddressPrefix: to.StringPtr("Internet"), + DestinationAddressPrefix: to.StringPtr("*"), + Access: network.Allow, + Direction: network.Inbound, + }, + } + } + + // update security rules + dirtySg := false + var updatedRules []network.SecurityRule + if sg.Properties.SecurityRules != nil { + updatedRules = *sg.Properties.SecurityRules + } + // update security rules: remove unwanted + for i := len(updatedRules) - 1; i >= 0; i-- { + existingRule := updatedRules[i] + if serviceOwnsRule(service, *existingRule.Name) { + glog.V(10).Infof("reconcile(%s)(%t): sg rule(%s) - considering evicting", serviceName, wantLb, *existingRule.Name) + keepRule := false + if findSecurityRule(expectedSecurityRules, existingRule) { + glog.V(10).Infof("reconcile(%s)(%t): sg rule(%s) - keeping", serviceName, wantLb, *existingRule.Name) + keepRule = true + } + if !keepRule { + glog.V(10).Infof("reconcile(%s)(%t): sg rule(%s) - dropping", serviceName, wantLb, *existingRule.Name) + updatedRules = append(updatedRules[:i], updatedRules[i+1:]...) + dirtySg = true + } + } + } + // update security rules: add needed + for _, expectedRule := range expectedSecurityRules { + foundRule := false + if findSecurityRule(updatedRules, expectedRule) { + glog.V(10).Infof("reconcile(%s)(%t): sg rule(%s) - already exists", serviceName, wantLb, *expectedRule.Name) + foundRule = true + } + if !foundRule { + glog.V(10).Infof("reconcile(%s)(%t): sg rule(%s) - adding", serviceName, wantLb, *expectedRule.Name) + + nextAvailablePriority, err := getNextAvailablePriority(updatedRules) + if err != nil { + return sg, false, err + } + + expectedRule.Properties.Priority = to.Int32Ptr(nextAvailablePriority) + updatedRules = append(updatedRules, expectedRule) + dirtySg = true + } + } + if dirtySg { + sg.Properties.SecurityRules = &updatedRules + } + return sg, dirtySg, nil +} + +func findProbe(probes []network.Probe, probe network.Probe) bool { + for _, existingProbe := range probes { + if strings.EqualFold(*existingProbe.Name, *probe.Name) { + return true + } + } + return false +} + +func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule) bool { + for _, existingRule := range rules { + if strings.EqualFold(*existingRule.Name, *rule.Name) { + return true + } + } + return false +} + +func findSecurityRule(rules []network.SecurityRule, rule network.SecurityRule) bool { + for _, existingRule := range rules { + if strings.EqualFold(*existingRule.Name, *rule.Name) { + return true + } + } + return false +} + +// This ensures the given VM's Primary NIC's Primary IP Configuration is +// participating in the specified LoadBalancer Backend Pool. +func (az *Cloud) ensureHostInPool(serviceName, machineName string, backendPoolID string) error { + machine, err := az.VirtualMachinesClient.Get(az.ResourceGroup, machineName, "") + if err != nil { + return err + } + + primaryNicID, err := getPrimaryInterfaceID(machine) + if err != nil { + return err + } + nicName, err := getLastSegment(primaryNicID) + if err != nil { + return err + } + + nic, err := az.InterfacesClient.Get(az.ResourceGroup, nicName, "") + if err != nil { + return err + } + + var primaryIPConfig *network.InterfaceIPConfiguration + primaryIPConfig, err = getPrimaryIPConfig(nic) + if err != nil { + return err + } + + foundPool := false + newBackendPools := []network.BackendAddressPool{} + if primaryIPConfig.Properties.LoadBalancerBackendAddressPools != nil { + newBackendPools = *primaryIPConfig.Properties.LoadBalancerBackendAddressPools + } + for _, existingPool := range newBackendPools { + if strings.EqualFold(backendPoolID, *existingPool.ID) { + foundPool = true + break + } + } + if !foundPool { + newBackendPools = append(newBackendPools, + network.BackendAddressPool{ + ID: to.StringPtr(backendPoolID), + }) + + primaryIPConfig.Properties.LoadBalancerBackendAddressPools = &newBackendPools + + glog.V(3).Infof("nicupdate(%s): nic(%s) - updating", serviceName, nicName) + _, err := az.InterfacesClient.CreateOrUpdate(az.ResourceGroup, *nic.Name, nic, nil) + if err != nil { + return err + } + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_routes.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_routes.go new file mode 100644 index 000000000000..00f12a4375f3 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_routes.go @@ -0,0 +1,161 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/cloudprovider" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/Azure/go-autorest/autorest/to" + "github.com/golang/glog" +) + +// ListRoutes lists all managed routes that belong to the specified clusterName +func (az *Cloud) ListRoutes(clusterName string) (routes []*cloudprovider.Route, err error) { + glog.V(10).Infof("list: START clusterName=%q", clusterName) + routeTable, existsRouteTable, err := az.getRouteTable() + if err != nil { + return nil, err + } + if !existsRouteTable { + return []*cloudprovider.Route{}, nil + } + + var kubeRoutes []*cloudprovider.Route + if routeTable.Properties.Routes != nil { + kubeRoutes = make([]*cloudprovider.Route, len(*routeTable.Properties.Routes)) + for i, route := range *routeTable.Properties.Routes { + instance := getInstanceName(*route.Name) + cidr := *route.Properties.AddressPrefix + glog.V(10).Infof("list: * instance=%q, cidr=%q", instance, cidr) + + kubeRoutes[i] = &cloudprovider.Route{ + Name: *route.Name, + TargetInstance: instance, + DestinationCIDR: cidr, + } + } + } + + glog.V(10).Info("list: FINISH") + return kubeRoutes, nil +} + +// CreateRoute creates the described managed route +// route.Name will be ignored, although the cloud-provider may use nameHint +// to create a more user-meaningful name. +func (az *Cloud) CreateRoute(clusterName string, nameHint string, kubeRoute *cloudprovider.Route) error { + glog.V(2).Infof("create: creating route. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetInstance, kubeRoute.DestinationCIDR) + + routeTable, existsRouteTable, err := az.getRouteTable() + if err != nil { + return err + } + if !existsRouteTable { + routeTable = network.RouteTable{ + Name: to.StringPtr(az.RouteTableName), + Location: to.StringPtr(az.Location), + Properties: &network.RouteTablePropertiesFormat{}, + } + + glog.V(3).Infof("create: creating routetable. routeTableName=%q", az.RouteTableName) + _, err = az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil) + if err != nil { + return err + } + + routeTable, err = az.RouteTablesClient.Get(az.ResourceGroup, az.RouteTableName, "") + if err != nil { + return err + } + } + + // ensure the subnet is properly configured + subnet, err := az.SubnetsClient.Get(az.ResourceGroup, az.VnetName, az.SubnetName, "") + if err != nil { + // 404 is fatal here + return err + } + if subnet.Properties.RouteTable != nil { + if *subnet.Properties.RouteTable.ID != *routeTable.ID { + return fmt.Errorf("The subnet has a route table, but it was unrecognized. Refusing to modify it. active_routetable=%q expected_routetable=%q", *subnet.Properties.RouteTable.ID, *routeTable.ID) + } + } else { + subnet.Properties.RouteTable = &network.RouteTable{ + ID: routeTable.ID, + } + glog.V(3).Info("create: updating subnet") + _, err := az.SubnetsClient.CreateOrUpdate(az.ResourceGroup, az.VnetName, az.SubnetName, subnet, nil) + if err != nil { + return err + } + } + + targetIP, err := az.getIPForMachine(kubeRoute.TargetInstance) + if err != nil { + return err + } + + routeName := getRouteName(kubeRoute.TargetInstance) + route := network.Route{ + Name: to.StringPtr(routeName), + Properties: &network.RoutePropertiesFormat{ + AddressPrefix: to.StringPtr(kubeRoute.DestinationCIDR), + NextHopType: network.RouteNextHopTypeVirtualAppliance, + NextHopIPAddress: to.StringPtr(targetIP), + }, + } + + glog.V(3).Infof("create: creating route: instance=%q cidr=%q", kubeRoute.TargetInstance, kubeRoute.DestinationCIDR) + _, err = az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil) + if err != nil { + return err + } + + glog.V(2).Infof("create: route created. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetInstance, kubeRoute.DestinationCIDR) + return nil +} + +// DeleteRoute deletes the specified managed route +// Route should be as returned by ListRoutes +func (az *Cloud) DeleteRoute(clusterName string, kubeRoute *cloudprovider.Route) error { + glog.V(2).Infof("delete: deleting route. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetInstance, kubeRoute.DestinationCIDR) + + routeName := getRouteName(kubeRoute.TargetInstance) + _, err := az.RoutesClient.Delete(az.ResourceGroup, az.RouteTableName, routeName, nil) + if err != nil { + return err + } + + glog.V(2).Infof("delete: route deleted. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetInstance, kubeRoute.DestinationCIDR) + return nil +} + +// This must be kept in sync with getInstanceName. +// These two functions enable stashing the instance name in the route +// and then retrieving it later when listing. This is needed because +// Azure does not let you put tags/descriptions on the Route itself. +func getRouteName(instanceName string) string { + return fmt.Sprintf("%s", instanceName) +} + +// Used with getRouteName. See comment on getRouteName. +func getInstanceName(routeName string) string { + return fmt.Sprintf("%s", routeName) +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_util.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_util.go new file mode 100644 index 000000000000..4fe5aa4ebd61 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_util.go @@ -0,0 +1,236 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "fmt" + "strings" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/cloudprovider" + + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/Azure/azure-sdk-for-go/arm/network" +) + +const ( + loadBalancerMinimumPriority = 500 + loadBalancerMaximumPriority = 4096 + + machineResourceIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s" + frontendIPConfigIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers/%s/frontendIPConfigurations/%s" + backendPoolIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers/%s/backendAddressPools/%s" + loadBalancerRuleIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers/%s/loadBalancingRules/%s" + loadBalancerProbeIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers/%s/probes/%s" + securityRuleIDTemplate = "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s" +) + +// returns the full identifier of a machine +func (az *Cloud) getMachineID(machineName string) string { + return fmt.Sprintf( + machineResourceIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + machineName) +} + +// returns the full identifier of a loadbalancer frontendipconfiguration. +func (az *Cloud) getFrontendIPConfigID(lbName, backendPoolName string) string { + return fmt.Sprintf( + frontendIPConfigIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + lbName, + backendPoolName) +} + +// returns the full identifier of a loadbalancer backendpool. +func (az *Cloud) getBackendPoolID(lbName, backendPoolName string) string { + return fmt.Sprintf( + backendPoolIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + lbName, + backendPoolName) +} + +// returns the full identifier of a loadbalancer rule. +func (az *Cloud) getLoadBalancerRuleID(lbName, lbRuleName string) string { + return fmt.Sprintf( + loadBalancerRuleIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + lbName, + lbRuleName) +} + +// returns the full identifier of a loadbalancer probe. +func (az *Cloud) getLoadBalancerProbeID(lbName, lbRuleName string) string { + return fmt.Sprintf( + loadBalancerProbeIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + lbName, + lbRuleName) +} + +// returns the full identifier of a network security group security rule. +func (az *Cloud) getSecurityRuleID(securityRuleName string) string { + return fmt.Sprintf( + securityRuleIDTemplate, + az.SubscriptionID, + az.ResourceGroup, + az.SecurityGroupName, + securityRuleName) +} + +// returns the deepest child's identifier from a full identifier string. +func getLastSegment(ID string) (string, error) { + parts := strings.Split(ID, "/") + name := parts[len(parts)-1] + if len(name) == 0 { + return "", fmt.Errorf("resource name was missing from identifier") + } + + return name, nil +} + +// returns the equivalent LoadBalancerRule, SecurityRule and LoadBalancerProbe +// protocol types for the given Kubernetes protocol type. +func getProtocolsFromKubernetesProtocol(protocol api.Protocol) (network.TransportProtocol, network.SecurityRuleProtocol, network.ProbeProtocol, error) { + switch protocol { + case api.ProtocolTCP: + return network.TransportProtocolTCP, network.TCP, network.ProbeProtocolTCP, nil + default: + return "", "", "", fmt.Errorf("Only TCP is supported for Azure LoadBalancers") + } +} + +// This returns the full identifier of the primary NIC for the given VM. +func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) { + if len(*machine.Properties.NetworkProfile.NetworkInterfaces) == 1 { + return *(*machine.Properties.NetworkProfile.NetworkInterfaces)[0].ID, nil + } + + for _, ref := range *machine.Properties.NetworkProfile.NetworkInterfaces { + if *ref.Properties.Primary { + return *ref.ID, nil + } + } + + return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", *machine.Name) +} + +func getPrimaryIPConfig(nic network.Interface) (*network.InterfaceIPConfiguration, error) { + if len(*nic.Properties.IPConfigurations) == 1 { + return &((*nic.Properties.IPConfigurations)[0]), nil + } + + // we're here because we either have multiple ipconfigs and can't determine the primary: + // https://github.com/Azure/azure-rest-api-specs/issues/305 + // or somehow we had zero ipconfigs + return nil, fmt.Errorf("failed to determine the determine primary ipconfig. nicname=%q", *nic.Name) +} + +func getLoadBalancerName(clusterName string) string { + return clusterName +} + +func getBackendPoolName(clusterName string) string { + return clusterName +} + +func getRuleName(service *api.Service, port api.ServicePort) string { + return fmt.Sprintf("%s-%s-%d-%d", getRulePrefix(service), port.Protocol, port.Port, port.NodePort) +} + +// This returns a human-readable version of the Service used to tag some resources. +// This is only used for human-readable convenience, and not to filter. +func getServiceName(service *api.Service) string { + return fmt.Sprintf("%s/%s", service.Namespace, service.Name) +} + +// This returns a prefix for loadbalancer/security rules. +func getRulePrefix(service *api.Service) string { + return cloudprovider.GetLoadBalancerName(service) +} + +func serviceOwnsRule(service *api.Service, rule string) bool { + prefix := getRulePrefix(service) + return strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix)) +} + +func getFrontendIPConfigName(service *api.Service) string { + return cloudprovider.GetLoadBalancerName(service) +} + +func getPublicIPName(clusterName string, service *api.Service) string { + return fmt.Sprintf("%s-%s", clusterName, cloudprovider.GetLoadBalancerName(service)) +} + +// This returns the next available rule priority level for a given set of security rules. +func getNextAvailablePriority(rules []network.SecurityRule) (int32, error) { + var smallest int32 = loadBalancerMinimumPriority + var spread int32 = 1 + +outer: + for smallest < loadBalancerMaximumPriority { + for _, rule := range rules { + if *rule.Properties.Priority == smallest { + smallest += spread + continue outer + } + } + // no one else had it + return smallest, nil + } + + return -1, fmt.Errorf("SecurityGroup priorities are exhausted") +} + +func (az *Cloud) getIPForMachine(machineName string) (string, error) { + machine, exists, err := az.getVirtualMachine(machineName) + if !exists { + return "", cloudprovider.InstanceNotFound + } + if err != nil { + return "", err + } + + nicID, err := getPrimaryInterfaceID(machine) + if err != nil { + return "", err + } + + nicName, err := getLastSegment(nicID) + if err != nil { + return "", err + } + + nic, err := az.InterfacesClient.Get(az.ResourceGroup, nicName, "") + if err != nil { + return "", err + } + + ipConfig, err := getPrimaryIPConfig(nic) + if err != nil { + return "", err + } + + targetIP := *ipConfig.Properties.PrivateIPAddress + return targetIP, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_wrap.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_wrap.go new file mode 100644 index 000000000000..782c751c2466 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_wrap.go @@ -0,0 +1,124 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/Azure/go-autorest/autorest" +) + +// checkExistsFromError inspects an error and returns a true if err is nil, +// false if error is an autorest.Error with StatusCode=404 and will return the +// error back if error is another status code or another type of error. +func checkResourceExistsFromError(err error) (bool, error) { + if err == nil { + return true, nil + } + v, ok := err.(autorest.DetailedError) + if ok && v.StatusCode == http.StatusNotFound { + return false, nil + } + return false, v +} + +func (az *Cloud) getVirtualMachine(machineName string) (vm compute.VirtualMachine, exists bool, err error) { + var realErr error + + vm, err = az.VirtualMachinesClient.Get(az.ResourceGroup, machineName, "") + + exists, realErr = checkResourceExistsFromError(err) + if realErr != nil { + return vm, false, realErr + } + + if !exists { + return vm, false, nil + } + + return vm, exists, err +} + +func (az *Cloud) getRouteTable() (routeTable network.RouteTable, exists bool, err error) { + var realErr error + + routeTable, err = az.RouteTablesClient.Get(az.ResourceGroup, az.RouteTableName, "") + + exists, realErr = checkResourceExistsFromError(err) + if realErr != nil { + return routeTable, false, realErr + } + + if !exists { + return routeTable, false, nil + } + + return routeTable, exists, err +} + +func (az *Cloud) getSecurityGroup() (sg network.SecurityGroup, exists bool, err error) { + var realErr error + + sg, err = az.SecurityGroupsClient.Get(az.ResourceGroup, az.SecurityGroupName, "") + + exists, realErr = checkResourceExistsFromError(err) + if realErr != nil { + return sg, false, realErr + } + + if !exists { + return sg, false, nil + } + + return sg, exists, err +} + +func (az *Cloud) getAzureLoadBalancer(name string) (lb network.LoadBalancer, exists bool, err error) { + var realErr error + + lb, err = az.LoadBalancerClient.Get(az.ResourceGroup, name, "") + + exists, realErr = checkResourceExistsFromError(err) + if realErr != nil { + return lb, false, realErr + } + + if !exists { + return lb, false, nil + } + + return lb, exists, err +} + +func (az *Cloud) getPublicIPAddress(name string) (pip network.PublicIPAddress, exists bool, err error) { + var realErr error + + pip, err = az.PublicIPAddressesClient.Get(az.ResourceGroup, name, "") + + exists, realErr = checkResourceExistsFromError(err) + if realErr != nil { + return pip, false, realErr + } + + if !exists { + return pip, false, nil + } + + return pip, exists, err +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_zones.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_zones.go new file mode 100644 index 000000000000..ab2dd9e3b27f --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/azure/azure_zones.go @@ -0,0 +1,78 @@ +/* +Copyright 2016 The Kubernetes 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 azure + +import ( + "encoding/json" + "io" + "io/ioutil" + "net/http" + "sync" + + "k8s.io/kubernetes/pkg/cloudprovider" +) + +const instanceInfoURL = "http://169.254.169.254/metadata/v1/InstanceInfo" + +var faultMutex = &sync.Mutex{} +var faultDomain *string + +type instanceInfo struct { + ID string `json:"ID"` + UpdateDomain string `json:"UD"` + FaultDomain string `json:"FD"` +} + +// GetZone returns the Zone containing the current failure zone and locality region that the program is running in +func (az *Cloud) GetZone() (cloudprovider.Zone, error) { + faultMutex.Lock() + if faultDomain == nil { + var err error + faultDomain, err = fetchFaultDomain() + if err != nil { + return cloudprovider.Zone{}, err + } + } + zone := cloudprovider.Zone{ + FailureDomain: *faultDomain, + Region: az.Location, + } + faultMutex.Unlock() + return zone, nil +} + +func fetchFaultDomain() (*string, error) { + resp, err := http.Get(instanceInfoURL) + if err != nil { + return nil, err + } + defer resp.Body.Close() + return readFaultDomain(resp.Body) +} + +func readFaultDomain(reader io.Reader) (*string, error) { + var instanceInfo instanceInfo + body, err := ioutil.ReadAll(reader) + if err != nil { + return nil, err + } + err = json.Unmarshal(body, &instanceInfo) + if err != nil { + return nil, err + } + return &instanceInfo.FaultDomain, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/doc.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/doc.go index 93acc5a3142a..25c79b9ec0b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go index 015929b67807..a7d71a3f7caf 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/gce.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ type GCECloud struct { projectID string region string localZone string // The zone in which we are running - managedZones []string // List of zones we are spanning (for Ubernetes-Lite, primarily when running on master) + managedZones []string // List of zones we are spanning (for multi-AZ clusters, primarily when running on master) networkURL string nodeTags []string // List of tags to use on firewall rules for load balancers nodeInstancePrefix string // If non-"", an advisory prefix for all nodes in the cluster @@ -494,7 +494,7 @@ func (gce *GCECloud) waitForZoneOp(op *compute.Operation, zone string) error { } // GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer -func (gce *GCECloud) GetLoadBalancer(service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (gce *GCECloud) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) fwd, err := gce.service.ForwardingRules.Get(gce.projectID, gce.region, loadBalancerName).Do() if err == nil { @@ -521,7 +521,7 @@ func isHTTPErrorCode(err error, code int) bool { // Due to an interesting series of design decisions, this handles both creating // new load balancers and updating existing load balancers, recognizing when // each is needed. -func (gce *GCECloud) EnsureLoadBalancer(apiService *api.Service, hostNames []string) (*api.LoadBalancerStatus, error) { +func (gce *GCECloud) EnsureLoadBalancer(clusterName string, apiService *api.Service, hostNames []string) (*api.LoadBalancerStatus, error) { if len(hostNames) == 0 { return nil, fmt.Errorf("Cannot EnsureLoadBalancer() with no hosts") } @@ -670,15 +670,17 @@ func (gce *GCECloud) EnsureLoadBalancer(apiService *api.Service, hostNames []str // Unlike forwarding rules and target pools, firewalls can be updated // without needing to be deleted and recreated. if firewallExists { + glog.Infof("EnsureLoadBalancer(%v(%v)): updating firewall", loadBalancerName, serviceName) if err := gce.updateFirewall(loadBalancerName, gce.region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } - glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): updated firewall", loadBalancerName, serviceName) + glog.Infof("EnsureLoadBalancer(%v(%v)): updated firewall", loadBalancerName, serviceName) } else { + glog.Infof("EnsureLoadBalancer(%v(%v)): creating firewall", loadBalancerName, serviceName) if err := gce.createFirewall(loadBalancerName, gce.region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } - glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): created firewall", loadBalancerName, serviceName) + glog.Infof("EnsureLoadBalancer(%v(%v)): created firewall", loadBalancerName, serviceName) } } @@ -737,9 +739,11 @@ func (gce *GCECloud) EnsureLoadBalancer(apiService *api.Service, hostNames []str if err := gce.updateTargetPool(loadBalancerName, created, hosts); err != nil { return nil, fmt.Errorf("failed to update target pool %s: %v", loadBalancerName, err) } + glog.Infof("EnsureLoadBalancer(%v(%v)): updated target pool (with %d hosts)", loadBalancerName, serviceName, len(hosts)-maxTargetPoolCreateInstances) } } if tpNeedsUpdate || fwdRuleNeedsUpdate { + glog.Infof("EnsureLoadBalancer(%v(%v)): creating forwarding rule, IP %s", loadBalancerName, serviceName, ipAddress) if err := gce.createForwardingRule(loadBalancerName, serviceName.String(), gce.region, ipAddress, ports); err != nil { return nil, fmt.Errorf("failed to create forwarding rule %s: %v", loadBalancerName, err) } @@ -748,7 +752,7 @@ func (gce *GCECloud) EnsureLoadBalancer(apiService *api.Service, hostNames []str // of a user-requested IP, the "is user-owned" flag will be set, // preventing it from actually being released. isSafeToReleaseIP = true - glog.V(4).Infof("EnsureLoadBalancer(%v(%v)): created forwarding rule, IP %s", loadBalancerName, serviceName, ipAddress) + glog.Infof("EnsureLoadBalancer(%v(%v)): created forwarding rule, IP %s", loadBalancerName, serviceName, ipAddress) } status := &api.LoadBalancerStatus{} @@ -1189,7 +1193,7 @@ func (gce *GCECloud) ensureStaticIP(name, serviceName, region, existingIP string } // UpdateLoadBalancer is an implementation of LoadBalancer.UpdateLoadBalancer. -func (gce *GCECloud) UpdateLoadBalancer(service *api.Service, hostNames []string) error { +func (gce *GCECloud) UpdateLoadBalancer(clusterName string, service *api.Service, hostNames []string) error { hosts, err := gce.getInstancesByNames(hostNames) if err != nil { return err @@ -1260,9 +1264,9 @@ func (gce *GCECloud) updateTargetPool(loadBalancerName string, existing sets.Str } // EnsureLoadBalancerDeleted is an implementation of LoadBalancer.EnsureLoadBalancerDeleted. -func (gce *GCECloud) EnsureLoadBalancerDeleted(service *api.Service) error { +func (gce *GCECloud) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) - glog.V(2).Infof("EnsureLoadBalancerDeleted(%v, %v, %v, %v)", service.Namespace, service.Name, loadBalancerName, + glog.V(2).Infof("EnsureLoadBalancerDeleted(%v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, loadBalancerName, gce.region) errs := utilerrors.AggregateGoroutines( diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/token_source.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/token_source.go index 20028c02c6b9..a30cae577c2e 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/token_source.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/gce/token_source.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go index 1b488bc62dc4..84b506fc7a27 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/client.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go index 9edbc8f5f563..29d3bfdc4f56 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/config.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go index 20285843b65b..1ca1dcf36599 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/mesos.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go index 2baf7b47f500..4f0735308968 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/mesos/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go index fa801bb9cb7c..be941b52cf7a 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import ( const ProviderName = "openstack" -// metadataUrl is URL to OpenStack metadata server. It's hadrcoded IPv4 +// metadataUrl is URL to OpenStack metadata server. It's hardcoded IPv4 // link-local address as documented in "OpenStack Cloud Administrator Guide", // chapter Compute - Networking with nova-network. // http://docs.openstack.org/admin-guide-cloud/compute-networking-nova.html#metadata-service diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go index 90f345a8aecb..615210b705c1 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -260,7 +260,7 @@ func waitLoadbalancerDeleted(client *gophercloud.ServiceClient, loadbalancerID s } } -func (lbaas *LbaasV2) GetLoadBalancer(service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err == ErrNotFound { @@ -281,8 +281,8 @@ func (lbaas *LbaasV2) GetLoadBalancer(service *api.Service) (*api.LoadBalancerSt // a list of regions (from config) and query/create loadbalancers in // each region. -func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { - glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, apiService.Annotations) +func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { + glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, apiService.Annotations) ports := apiService.Spec.Ports if len(ports) > 1 { @@ -318,7 +318,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string } glog.V(2).Infof("Checking if openstack load balancer already exists: %s", cloudprovider.GetLoadBalancerName(apiService)) - _, exists, err := lbaas.GetLoadBalancer(apiService) + _, exists, err := lbaas.GetLoadBalancer(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error checking if openstack load balancer already exists: %v", err) } @@ -326,7 +326,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string // TODO: Implement a more efficient update strategy for common changes than delete & create // In particular, if we implement hosts update, we can get rid of UpdateHosts if exists { - err := lbaas.EnsureLoadBalancerDeleted(apiService) + err := lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error deleting existing openstack load balancer: %v", err) } @@ -352,7 +352,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string loadbalancer, err := loadbalancers.Create(lbaas.network, createOpts).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } @@ -366,7 +366,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string }).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } @@ -381,7 +381,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string }).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } @@ -400,7 +400,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string }).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } } @@ -417,7 +417,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string }).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } } @@ -430,7 +430,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string portID, err := getPortIDByIP(lbaas.network, loadbalancer.VipAddress) if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } @@ -441,7 +441,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string floatIP, err := floatingips.Create(lbaas.network, floatIPOpts).Extract() if err != nil { // cleanup what was created so far - _ = lbaas.EnsureLoadBalancerDeleted(apiService) + _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } @@ -451,9 +451,9 @@ func (lbaas *LbaasV2) EnsureLoadBalancer(apiService *api.Service, hosts []string return status, nil } -func (lbaas *LbaasV2) UpdateLoadBalancer(service *api.Service, hosts []string) error { +func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) - glog.V(4).Infof("UpdateLoadBalancer(%v, %v)", loadBalancerName, hosts) + glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, hosts) ports := service.Spec.Ports if len(ports) > 1 { @@ -538,9 +538,9 @@ func (lbaas *LbaasV2) UpdateLoadBalancer(service *api.Service, hosts []string) e return nil } -func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(service *api.Service) error { +func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) - glog.V(4).Infof("EnsureLoadBalancerDeleted(%v)", loadBalancerName) + glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err != nil && err != ErrNotFound { @@ -690,7 +690,7 @@ func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(service *api.Service) error { return nil } -func (lb *LbaasV1) GetLoadBalancer(service *api.Service) (*api.LoadBalancerStatus, bool, error) { +func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *api.Service) (*api.LoadBalancerStatus, bool, error) { loadBalancerName := cloudprovider.GetLoadBalancerName(service) vip, err := getVipByName(lb.network, loadBalancerName) if err == ErrNotFound { @@ -711,8 +711,8 @@ func (lb *LbaasV1) GetLoadBalancer(service *api.Service) (*api.LoadBalancerStatu // a list of regions (from config) and query/create loadbalancers in // each region. -func (lb *LbaasV1) EnsureLoadBalancer(apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { - glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, apiService.Annotations) +func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *api.Service, hosts []string) (*api.LoadBalancerStatus, error) { + glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, hosts, apiService.Annotations) ports := apiService.Spec.Ports if len(ports) > 1 { @@ -748,7 +748,7 @@ func (lb *LbaasV1) EnsureLoadBalancer(apiService *api.Service, hosts []string) ( } glog.V(2).Infof("Checking if openstack load balancer already exists: %s", cloudprovider.GetLoadBalancerName(apiService)) - _, exists, err := lb.GetLoadBalancer(apiService) + _, exists, err := lb.GetLoadBalancer(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error checking if openstack load balancer already exists: %v", err) } @@ -756,7 +756,7 @@ func (lb *LbaasV1) EnsureLoadBalancer(apiService *api.Service, hosts []string) ( // TODO: Implement a more efficient update strategy for common changes than delete & create // In particular, if we implement hosts update, we can get rid of UpdateHosts if exists { - err := lb.EnsureLoadBalancerDeleted(apiService) + err := lb.EnsureLoadBalancerDeleted(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error deleting existing openstack load balancer: %v", err) } @@ -860,9 +860,9 @@ func (lb *LbaasV1) EnsureLoadBalancer(apiService *api.Service, hosts []string) ( } -func (lb *LbaasV1) UpdateLoadBalancer(service *api.Service, hosts []string) error { +func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *api.Service, hosts []string) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) - glog.V(4).Infof("UpdateLoadBalancer(%v, %v)", loadBalancerName, hosts) + glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, hosts) vip, err := getVipByName(lb.network, loadBalancerName) if err != nil { @@ -922,9 +922,9 @@ func (lb *LbaasV1) UpdateLoadBalancer(service *api.Service, hosts []string) erro return nil } -func (lb *LbaasV1) EnsureLoadBalancerDeleted(service *api.Service) error { +func (lb *LbaasV1) EnsureLoadBalancerDeleted(clusterName string, service *api.Service) error { loadBalancerName := cloudprovider.GetLoadBalancerName(service) - glog.V(4).Infof("EnsureLoadBalancerDeleted(%v)", loadBalancerName) + glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) vip, err := getVipByName(lb.network, loadBalancerName) if err != nil && err != ErrNotFound { diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go index d2ba03c10bab..3fb29893f5c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt/ovirt.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go index 765beb636bf6..633b3e21eeda 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/providers.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package cloudprovider import ( // Cloud providers _ "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" + _ "k8s.io/kubernetes/pkg/cloudprovider/providers/azure" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/gce" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/mesos" _ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack" diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go index 3f6f6a5d4b36..d03609662450 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/rackspace/rackspace.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vsphere.go b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vsphere.go index d90354a23d2a..788ff7870500 100644 --- a/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vsphere.go +++ b/vendor/k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere/vsphere.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,12 +17,11 @@ limitations under the License. package vsphere import ( - "bytes" "errors" "fmt" "io" + "net" "net/url" - "os/exec" "path" "strings" @@ -106,14 +105,12 @@ func init() { } func readInstanceID(cfg *VSphereConfig) (string, error) { - cmd := exec.Command("bash", "-c", `dmidecode -t 1 | grep UUID | tr -d ' ' | cut -f 2 -d ':'`) - var out bytes.Buffer - cmd.Stdout = &out - err := cmd.Run() + addrs, err := net.InterfaceAddrs() if err != nil { return "", err } - if out.Len() == 0 { + + if len(addrs) == 0 { return "", fmt.Errorf("unable to retrieve Instance ID") } @@ -140,7 +137,22 @@ func readInstanceID(cfg *VSphereConfig) (string, error) { s := object.NewSearchIndex(c.Client) - svm, err := s.FindByUuid(ctx, dc, strings.ToLower(strings.TrimSpace(out.String())), true, nil) + var svm object.Reference + for _, v := range addrs { + ip, _, err := net.ParseCIDR(v.String()) + if err != nil { + return "", fmt.Errorf("unable to parse cidr from ip") + } + + svm, err = s.FindByIp(ctx, dc, ip.String(), true) + if err == nil && svm != nil { + break + } + } + if svm == nil { + return "", fmt.Errorf("unable to retrieve vm reference from vSphere") + } + var vm mo.VirtualMachine err = s.Properties(ctx, svm.Reference(), []string{"name"}, &vm) if err != nil { @@ -299,7 +311,7 @@ func (i *Instances) List(filter string) ([]string, error) { return nil, err } - glog.V(3).Infof("Found %s instances matching %s: %s", + glog.V(3).Infof("Found %d instances matching %s: %s", len(vmList), filter, vmList) return vmList, nil @@ -422,9 +434,9 @@ func (i *Instances) InstanceID(name string) (string, error) { } if mvm.Summary.Config.Template == false { - glog.Warning("VM %s, is not in %s state", name, ActivePowerState) + glog.Warningf("VM %s, is not in %s state", name, ActivePowerState) } else { - glog.Warning("VM %s, is a template", name) + glog.Warningf("VM %s, is a template", name) } return "", cloudprovider.InstanceNotFound diff --git a/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller.go b/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller.go new file mode 100644 index 000000000000..029e9d52be6e --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller.go @@ -0,0 +1,200 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "time" + + "github.com/cloudflare/cfssl/config" + "github.com/cloudflare/cfssl/signer" + "github.com/cloudflare/cfssl/signer/local" + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/client/cache" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" + "k8s.io/kubernetes/pkg/client/record" + "k8s.io/kubernetes/pkg/controller" + "k8s.io/kubernetes/pkg/controller/framework" + "k8s.io/kubernetes/pkg/runtime" + utilruntime "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/wait" + "k8s.io/kubernetes/pkg/util/workqueue" + "k8s.io/kubernetes/pkg/watch" +) + +type CertificateController struct { + kubeClient clientset.Interface + + // CSR framework and store + csrController *framework.Controller + csrStore cache.StoreToCertificateRequestLister + + // To allow injection of updateCertificateRequestStatus for testing. + updateHandler func(csr *certificates.CertificateSigningRequest) error + syncHandler func(csrKey string) error + + signer *local.Signer + + queue *workqueue.Type +} + +func NewCertificateController(kubeClient clientset.Interface, syncPeriod time.Duration, caCertFile, caKeyFile string) (*CertificateController, error) { + // Send events to the apiserver + eventBroadcaster := record.NewBroadcaster() + eventBroadcaster.StartLogging(glog.Infof) + eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + + // Configure cfssl signer + // TODO: support non-default policy and remote/pkcs11 signing + policy := &config.Signing{ + Default: config.DefaultConfig(), + } + ca, err := local.NewSignerFromFile(caCertFile, caKeyFile, policy) + if err != nil { + return nil, err + } + + cc := &CertificateController{ + kubeClient: kubeClient, + queue: workqueue.New(), + signer: ca, + } + + // Manage the addition/update of certificate requests + cc.csrStore.Store, cc.csrController = framework.NewInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return cc.kubeClient.Certificates().CertificateSigningRequests().List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return cc.kubeClient.Certificates().CertificateSigningRequests().Watch(options) + }, + }, + &certificates.CertificateSigningRequest{}, + syncPeriod, + framework.ResourceEventHandlerFuncs{ + AddFunc: func(obj interface{}) { + csr := obj.(*certificates.CertificateSigningRequest) + glog.V(4).Infof("Adding certificate request %s", csr.Name) + cc.enqueueCertificateRequest(obj) + }, + UpdateFunc: func(old, new interface{}) { + oldCSR := old.(*certificates.CertificateSigningRequest) + glog.V(4).Infof("Updating certificate request %s", oldCSR.Name) + cc.enqueueCertificateRequest(new) + }, + DeleteFunc: func(obj interface{}) { + csr := obj.(*certificates.CertificateSigningRequest) + glog.V(4).Infof("Deleting certificate request %s", csr.Name) + cc.enqueueCertificateRequest(obj) + }, + }, + ) + cc.syncHandler = cc.maybeSignCertificate + return cc, nil +} + +// Run the main goroutine responsible for watching and syncing jobs. +func (cc *CertificateController) Run(workers int, stopCh <-chan struct{}) { + defer utilruntime.HandleCrash() + go cc.csrController.Run(stopCh) + glog.Infof("Starting certificate controller manager") + for i := 0; i < workers; i++ { + go wait.Until(cc.worker, time.Second, stopCh) + } + <-stopCh + glog.Infof("Shutting down certificate controller") + cc.queue.ShutDown() +} + +// worker runs a thread that dequeues CSRs, handles them, and marks them done. +func (cc *CertificateController) worker() { + for { + func() { + key, quit := cc.queue.Get() + if quit { + return + } + defer cc.queue.Done(key) + err := cc.syncHandler(key.(string)) + if err != nil { + glog.Errorf("Error syncing CSR: %v", err) + } + }() + } +} + +func (cc *CertificateController) enqueueCertificateRequest(obj interface{}) { + key, err := controller.KeyFunc(obj) + if err != nil { + glog.Errorf("Couldn't get key for object %+v: %v", obj, err) + return + } + cc.queue.Add(key) +} + +func (cc *CertificateController) updateCertificateRequestStatus(csr *certificates.CertificateSigningRequest) error { + _, updateErr := cc.kubeClient.Certificates().CertificateSigningRequests().UpdateStatus(csr) + if updateErr == nil { + // success! + return nil + } + + // retry on failure + cc.enqueueCertificateRequest(csr) + return updateErr +} + +// maybeSignCertificate will inspect the certificate request and, if it has +// been approved and meets policy expectations, generate an X509 cert using the +// cluster CA assets. If successful it will update the CSR approve subresource +// with the signed certificate. +func (cc *CertificateController) maybeSignCertificate(key string) error { + startTime := time.Now() + defer func() { + glog.V(4).Infof("Finished syncing certificate request %q (%v)", key, time.Now().Sub(startTime)) + }() + obj, exists, err := cc.csrStore.Store.GetByKey(key) + if err != nil { + cc.queue.Add(key) + return err + } + if !exists { + glog.V(3).Infof("csr has been deleted: %v", key) + return nil + } + csr := obj.(*certificates.CertificateSigningRequest) + + // At this point, the controller needs to: + // 1. Check the approval conditions + // 2. Generate a signed certificate + // 3. Update the Status subresource + + if csr.Status.Certificate == nil && IsCertificateRequestApproved(csr) { + pemBytes := csr.Spec.Request + req := signer.SignRequest{Request: string(pemBytes)} + certBytes, err := cc.signer.Sign(req) + if err != nil { + return err + } + csr.Status.Certificate = certBytes + } + + return cc.updateCertificateRequestStatus(csr) +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller_utils.go new file mode 100644 index 000000000000..f2e687c7809c --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/certificates/controller_utils.go @@ -0,0 +1,36 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import "k8s.io/kubernetes/pkg/apis/certificates" + +// IsCertificateRequestApproved returns true if a certificate request has the +// "Approved" condition and no "Denied" conditions; false otherwise. +func IsCertificateRequestApproved(csr *certificates.CertificateSigningRequest) bool { + status := csr.Status + var approved, denied bool + // TODO: incorporate timestamps + for _, c := range status.Conditions { + if c.Type == certificates.CertificateApproved { + approved = true + } + if c.Type == certificates.CertificateDenied { + denied = true + } + } + return approved && !denied +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/certificates/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/certificates/doc.go new file mode 100644 index 000000000000..70094277a393 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/certificates/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 certificates contains logic for watching and synchronizing +// CertificateSigningRequests. +package certificates diff --git a/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager.go b/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager.go new file mode 100644 index 000000000000..6c530e47f379 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager.go @@ -0,0 +1,144 @@ +/* +Copyright 2016 The Kubernetes 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 controller + +import ( + "fmt" + "strings" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/labels" +) + +type PodControllerRefManager struct { + podControl PodControlInterface + controllerObject api.ObjectMeta + controllerSelector labels.Selector + controllerKind unversioned.GroupVersionKind +} + +// NewPodControllerRefManager returns a PodControllerRefManager that exposes +// methods to manage the controllerRef of pods. +func NewPodControllerRefManager( + podControl PodControlInterface, + controllerObject api.ObjectMeta, + controllerSelector labels.Selector, + controllerKind unversioned.GroupVersionKind, +) *PodControllerRefManager { + return &PodControllerRefManager{podControl, controllerObject, controllerSelector, controllerKind} +} + +// Classify first filters out inactive pods, then it classify the remaining pods +// into three categories: 1. matchesAndControlled are the pods whose labels +// match the selector of the RC, and have a controllerRef pointing to the +// controller 2. matchesNeedsController are the pods whose labels match the RC, +// but don't have a controllerRef. (Pods with matching labels but with a +// controllerRef pointing to other object are ignored) 3. controlledDoesNotMatch +// are the pods that have a controllerRef pointing to the controller, but their +// labels no longer match the selector. +func (m *PodControllerRefManager) Classify(pods []api.Pod) ( + matchesAndControlled []*api.Pod, + matchesNeedsController []*api.Pod, + controlledDoesNotMatch []*api.Pod) { + for i := range pods { + pod := pods[i] + if !IsPodActive(pod) { + glog.V(4).Infof("Ignoring inactive pod %v/%v in state %v, deletion time %v", + pod.Namespace, pod.Name, pod.Status.Phase, pod.DeletionTimestamp) + continue + } + controllerRef := getControllerOf(pod.ObjectMeta) + if controllerRef != nil { + if controllerRef.UID == m.controllerObject.UID { + // already controlled + if m.controllerSelector.Matches(labels.Set(pod.Labels)) { + matchesAndControlled = append(matchesAndControlled, &pod) + } else { + controlledDoesNotMatch = append(controlledDoesNotMatch, &pod) + } + } else { + // ignoring the pod controlled by other controller + glog.V(4).Infof("Ignoring pod %v/%v, it's owned by [%s/%s, name: %s, uid: %s]", + pod.Namespace, pod.Name, controllerRef.APIVersion, controllerRef.Kind, controllerRef.Name, controllerRef.UID) + continue + } + } else { + if !m.controllerSelector.Matches(labels.Set(pod.Labels)) { + continue + } + matchesNeedsController = append(matchesNeedsController, &pod) + } + } + return matchesAndControlled, matchesNeedsController, controlledDoesNotMatch +} + +// getControllerOf returns the controllerRef if controllee has a controller, +// otherwise returns nil. +func getControllerOf(controllee api.ObjectMeta) *api.OwnerReference { + for _, owner := range controllee.OwnerReferences { + // controlled by other controller + if owner.Controller != nil && *owner.Controller == true { + return &owner + } + } + return nil +} + +// AdoptPod sends a patch to take control of the pod. It returns the error if +// the patching fails. +func (m *PodControllerRefManager) AdoptPod(pod *api.Pod) error { + // we should not adopt any pods if the controller is about to be deleted + if m.controllerObject.DeletionTimestamp != nil { + return fmt.Errorf("cancel the adopt attempt for pod %s because the controlller is being deleted", + strings.Join([]string{pod.Namespace, pod.Name, string(pod.UID)}, "_")) + } + addControllerPatch := fmt.Sprintf( + `{"metadata":{"ownerReferences":[{"apiVersion":"%s","kind":"%s","name":"%s","uid":"%s","controller":true}],"uid":"%s"}}`, + m.controllerKind.GroupVersion(), m.controllerKind.Kind, + m.controllerObject.Name, m.controllerObject.UID, pod.UID) + return m.podControl.PatchPod(pod.Namespace, pod.Name, []byte(addControllerPatch)) +} + +// ReleasePod sends a patch to free the pod from the control of the controller. +// It returns the error if the patching fails. 404 and 422 errors are ignored. +func (m *PodControllerRefManager) ReleasePod(pod *api.Pod) error { + glog.V(2).Infof("patching pod %s_%s to remove its controllerRef to %s/%s:%s", + pod.Namespace, pod.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.controllerObject.Name) + deleteOwnerRefPatch := fmt.Sprintf(`{"metadata":{"ownerReferences":[{"$patch":"delete","uid":"%s"}],"uid":"%s"}}`, m.controllerObject.UID, pod.UID) + err := m.podControl.PatchPod(pod.Namespace, pod.Name, []byte(deleteOwnerRefPatch)) + if err != nil { + if errors.IsNotFound(err) { + // If the pod no longer exists, ignore it. + return nil + } + if errors.IsInvalid(err) { + // Invalid error will be returned in two cases: 1. the pod + // has no owner reference, 2. the uid of the pod doesn't + // match, which means the pod is deleted and then recreated. + // In both cases, the error can be ignored. + + // TODO: If the pod has owner references, but none of them + // has the owner.UID, server will silently ignore the patch. + // Investigate why. + return nil + } + } + return err +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/controller_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/controller_utils.go index a7aba40bece5..8c2eb5edf9d5 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/controller_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/controller_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -34,14 +34,12 @@ import ( "k8s.io/kubernetes/pkg/controller/framework" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/integer" "k8s.io/kubernetes/pkg/util/sets" ) const ( - CreatedByAnnotation = "kubernetes.io/created-by" - // If a watch drops a delete event for a pod, it'll take this long // before a dormant controller waiting for those packets is woken up anyway. It is // specifically targeted at the case where some problem prevents an update @@ -169,12 +167,12 @@ func (r *ControllerExpectations) SatisfiedExpectations(controllerKey string) boo // TODO: Make this possible to disable in tests. // TODO: Support injection of clock. func (exp *ControlleeExpectations) isExpired() bool { - return util.RealClock{}.Since(exp.timestamp) > ExpectationsTimeout + return clock.RealClock{}.Since(exp.timestamp) > ExpectationsTimeout } // SetExpectations registers new expectations for the given controller. Forgets existing expectations. func (r *ControllerExpectations) SetExpectations(controllerKey string, add, del int) error { - exp := &ControlleeExpectations{add: int64(add), del: int64(del), key: controllerKey, timestamp: util.RealClock{}.Now()} + exp := &ControlleeExpectations{add: int64(add), del: int64(del), key: controllerKey, timestamp: clock.RealClock{}.Now()} glog.V(4).Infof("Setting expectations %#v", exp) return r.Add(exp) } @@ -205,7 +203,7 @@ func (r *ControllerExpectations) RaiseExpectations(controllerKey string, add, de } } -// CreationObserved atomically decrements the `add` expecation count of the given controller. +// CreationObserved atomically decrements the `add` expectation count of the given controller. func (r *ControllerExpectations) CreationObserved(controllerKey string) { r.LowerExpectations(controllerKey, 1, 0) } @@ -351,8 +349,12 @@ type PodControlInterface interface { CreatePods(namespace string, template *api.PodTemplateSpec, object runtime.Object) error // CreatePodsOnNode creates a new pod accorting to the spec on the specified node. CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error + // CreatePodsWithControllerRef creates new pods according to the spec, and sets object as the pod's controller. + CreatePodsWithControllerRef(namespace string, template *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error // DeletePod deletes the pod identified by podID. DeletePod(namespace string, podID string, object runtime.Object) error + // PatchPod patches the pod. + PatchPod(namespace, name string, data []byte) error } // RealPodControl is the default implementation of PodControlInterface. @@ -392,7 +394,7 @@ func getPodsAnnotationSet(template *api.PodTemplateSpec, object runtime.Object) if err != nil { return desiredAnnotations, fmt.Errorf("unable to serialize controller reference: %v", err) } - desiredAnnotations[CreatedByAnnotation] = string(createdByRefJson) + desiredAnnotations[api.CreatedByAnnotation] = string(createdByRefJson) return desiredAnnotations, nil } @@ -406,14 +408,35 @@ func getPodsPrefix(controllerName string) string { } func (r RealPodControl) CreatePods(namespace string, template *api.PodTemplateSpec, object runtime.Object) error { - return r.createPods("", namespace, template, object) + return r.createPods("", namespace, template, object, nil) +} + +func (r RealPodControl) CreatePodsWithControllerRef(namespace string, template *api.PodTemplateSpec, controllerObject runtime.Object, controllerRef *api.OwnerReference) error { + if controllerRef == nil { + return fmt.Errorf("controllerRef is nil") + } + if len(controllerRef.APIVersion) == 0 { + return fmt.Errorf("controllerRef has empty APIVersion") + } + if len(controllerRef.Kind) == 0 { + return fmt.Errorf("controllerRef has empty Kind") + } + if controllerRef.Controller == nil || *controllerRef.Controller != true { + return fmt.Errorf("controllerRef.Controller is not set") + } + return r.createPods("", namespace, template, controllerObject, controllerRef) } func (r RealPodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { - return r.createPods(nodeName, namespace, template, object) + return r.createPods(nodeName, namespace, template, object, nil) +} + +func (r RealPodControl) PatchPod(namespace, name string, data []byte) error { + _, err := r.KubeClient.Core().Pods(namespace).Patch(name, api.StrategicMergePatchType, data) + return err } -func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Object) (*api.Pod, error) { +func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Object, controllerRef *api.OwnerReference) (*api.Pod, error) { desiredLabels := getPodsLabelSet(template) desiredAnnotations, err := getPodsAnnotationSet(template, parentObject) if err != nil { @@ -432,14 +455,17 @@ func GetPodFromTemplate(template *api.PodTemplateSpec, parentObject runtime.Obje GenerateName: prefix, }, } + if controllerRef != nil { + pod.OwnerReferences = append(pod.OwnerReferences, *controllerRef) + } if err := api.Scheme.Convert(&template.Spec, &pod.Spec); err != nil { return nil, fmt.Errorf("unable to convert pod template: %v", err) } return pod, nil } -func (r RealPodControl) createPods(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { - pod, err := GetPodFromTemplate(template, object) +func (r RealPodControl) createPods(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error { + pod, err := GetPodFromTemplate(template, object, controllerRef) if err != nil { return err } @@ -481,40 +507,63 @@ func (r RealPodControl) DeletePod(namespace string, podID string, object runtime type FakePodControl struct { sync.Mutex - Templates []api.PodTemplateSpec - DeletePodName []string - Err error + Templates []api.PodTemplateSpec + ControllerRefs []api.OwnerReference + DeletePodName []string + Patches [][]byte + Err error } var _ PodControlInterface = &FakePodControl{} +func (f *FakePodControl) PatchPod(namespace, name string, data []byte) error { + f.Lock() + defer f.Unlock() + f.Patches = append(f.Patches, data) + if f.Err != nil { + return f.Err + } + return nil +} + func (f *FakePodControl) CreatePods(namespace string, spec *api.PodTemplateSpec, object runtime.Object) error { f.Lock() defer f.Unlock() + f.Templates = append(f.Templates, *spec) if f.Err != nil { return f.Err } + return nil +} + +func (f *FakePodControl) CreatePodsWithControllerRef(namespace string, spec *api.PodTemplateSpec, object runtime.Object, controllerRef *api.OwnerReference) error { + f.Lock() + defer f.Unlock() f.Templates = append(f.Templates, *spec) + f.ControllerRefs = append(f.ControllerRefs, *controllerRef) + if f.Err != nil { + return f.Err + } return nil } func (f *FakePodControl) CreatePodsOnNode(nodeName, namespace string, template *api.PodTemplateSpec, object runtime.Object) error { f.Lock() defer f.Unlock() + f.Templates = append(f.Templates, *template) if f.Err != nil { return f.Err } - f.Templates = append(f.Templates, *template) return nil } func (f *FakePodControl) DeletePod(namespace string, podID string, object runtime.Object) error { f.Lock() defer f.Unlock() + f.DeletePodName = append(f.DeletePodName, podID) if f.Err != nil { return f.Err } - f.DeletePodName = append(f.DeletePodName, podID) return nil } @@ -523,6 +572,45 @@ func (f *FakePodControl) Clear() { defer f.Unlock() f.DeletePodName = []string{} f.Templates = []api.PodTemplateSpec{} + f.ControllerRefs = []api.OwnerReference{} + f.Patches = [][]byte{} +} + +// ByLogging allows custom sorting of pods so the best one can be picked for getting its logs. +type ByLogging []*api.Pod + +func (s ByLogging) Len() int { return len(s) } +func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +func (s ByLogging) Less(i, j int) bool { + // 1. assigned < unassigned + if s[i].Spec.NodeName != s[j].Spec.NodeName && (len(s[i].Spec.NodeName) == 0 || len(s[j].Spec.NodeName) == 0) { + return len(s[i].Spec.NodeName) > 0 + } + // 2. PodRunning < PodUnknown < PodPending + m := map[api.PodPhase]int{api.PodRunning: 0, api.PodUnknown: 1, api.PodPending: 2} + if m[s[i].Status.Phase] != m[s[j].Status.Phase] { + return m[s[i].Status.Phase] < m[s[j].Status.Phase] + } + // 3. ready < not ready + if api.IsPodReady(s[i]) != api.IsPodReady(s[j]) { + return api.IsPodReady(s[i]) + } + // TODO: take availability into account when we push minReadySeconds information from deployment into pods, + // see https://github.com/kubernetes/kubernetes/issues/22065 + // 4. Been ready for more time < less time < empty time + if api.IsPodReady(s[i]) && api.IsPodReady(s[j]) && !podReadyTime(s[i]).Equal(podReadyTime(s[j])) { + return afterOrZero(podReadyTime(s[j]), podReadyTime(s[i])) + } + // 5. Pods with containers with higher restart counts < lower restart counts + if maxContainerRestarts(s[i]) != maxContainerRestarts(s[j]) { + return maxContainerRestarts(s[i]) > maxContainerRestarts(s[j]) + } + // 6. older pods < newer pods < empty timestamp pods + if !s[i].CreationTimestamp.Equal(s[j].CreationTimestamp) { + return afterOrZero(s[j].CreationTimestamp, s[i].CreationTimestamp) + } + return false } // ActivePods type allows custom sorting of pods so a controller can pick the best ones to delete. @@ -619,7 +707,9 @@ func IsPodActive(p api.Pod) bool { func FilterActiveReplicaSets(replicaSets []*extensions.ReplicaSet) []*extensions.ReplicaSet { active := []*extensions.ReplicaSet{} for i := range replicaSets { - if replicaSets[i].Spec.Replicas > 0 { + rs := replicaSets[i] + + if rs != nil && rs.Spec.Replicas > 0 { active = append(active, replicaSets[i]) } } @@ -629,7 +719,7 @@ func FilterActiveReplicaSets(replicaSets []*extensions.ReplicaSet) []*extensions // PodKey returns a key unique to the given pod within a cluster. // It's used so we consistently use the same key scheme in this module. // It does exactly what cache.MetaNamespaceKeyFunc would have done -// expcept there's not possibility for error since we know the exact type. +// except there's not possibility for error since we know the exact type. func PodKey(pod *api.Pod) string { return fmt.Sprintf("%v/%v", pod.Namespace, pod.Name) } @@ -639,7 +729,6 @@ type ControllersByCreationTimestamp []*api.ReplicationController func (o ControllersByCreationTimestamp) Len() int { return len(o) } func (o ControllersByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } - func (o ControllersByCreationTimestamp) Less(i, j int) bool { if o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) { return o[i].Name < o[j].Name @@ -647,15 +736,40 @@ func (o ControllersByCreationTimestamp) Less(i, j int) bool { return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) } -// ReplicaSetsByCreationTimestamp sorts a list of ReplicationSets by creation timestamp, using their names as a tie breaker. +// ReplicaSetsByCreationTimestamp sorts a list of ReplicaSet by creation timestamp, using their names as a tie breaker. type ReplicaSetsByCreationTimestamp []*extensions.ReplicaSet func (o ReplicaSetsByCreationTimestamp) Len() int { return len(o) } func (o ReplicaSetsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] } - func (o ReplicaSetsByCreationTimestamp) Less(i, j int) bool { if o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) { return o[i].Name < o[j].Name } return o[i].CreationTimestamp.Before(o[j].CreationTimestamp) } + +// ReplicaSetsBySizeOlder sorts a list of ReplicaSet by size in descending order, using their creation timestamp or name as a tie breaker. +// By using the creation timestamp, this sorts from old to new replica sets. +type ReplicaSetsBySizeOlder []*extensions.ReplicaSet + +func (o ReplicaSetsBySizeOlder) Len() int { return len(o) } +func (o ReplicaSetsBySizeOlder) Swap(i, j int) { o[i], o[j] = o[j], o[i] } +func (o ReplicaSetsBySizeOlder) Less(i, j int) bool { + if o[i].Spec.Replicas == o[j].Spec.Replicas { + return ReplicaSetsByCreationTimestamp(o).Less(i, j) + } + return o[i].Spec.Replicas > o[j].Spec.Replicas +} + +// ReplicaSetsBySizeNewer sorts a list of ReplicaSet by size in descending order, using their creation timestamp or name as a tie breaker. +// By using the creation timestamp, this sorts from new to old replica sets. +type ReplicaSetsBySizeNewer []*extensions.ReplicaSet + +func (o ReplicaSetsBySizeNewer) Len() int { return len(o) } +func (o ReplicaSetsBySizeNewer) Swap(i, j int) { o[i], o[j] = o[j], o[i] } +func (o ReplicaSetsBySizeNewer) Less(i, j int) bool { + if o[i].Spec.Replicas == o[j].Spec.Replicas { + return ReplicaSetsByCreationTimestamp(o).Less(j, i) + } + return o[i].Spec.Replicas > o[j].Spec.Replicas +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/daemon/controller.go b/vendor/k8s.io/kubernetes/pkg/controller/daemon/daemoncontroller.go similarity index 91% rename from vendor/k8s.io/kubernetes/pkg/controller/daemon/controller.go rename to vendor/k8s.io/kubernetes/pkg/controller/daemon/daemoncontroller.go index ca7935b6e847..fc0d102ae77c 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/daemon/controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/daemon/daemoncontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,16 +17,16 @@ limitations under the License. package daemon import ( + "fmt" "reflect" "sort" "sync" "time" - "fmt" "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/cache" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" @@ -40,12 +40,11 @@ import ( "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/metrics" utilruntime "k8s.io/kubernetes/pkg/util/runtime" - "k8s.io/kubernetes/pkg/util/sets" - "k8s.io/kubernetes/pkg/util/validation/field" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/util/workqueue" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" + "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) const ( @@ -239,7 +238,7 @@ func (dsc *DaemonSetsController) Run(workers int, stopCh <-chan struct{}) { go dsc.podController.Run(stopCh) go dsc.nodeController.Run(stopCh) for i := 0; i < workers; i++ { - go wait.Until(dsc.worker, time.Second, stopCh) + go wait.Until(dsc.runWorker, time.Second, stopCh) } if dsc.internalPodInformer != nil { @@ -251,31 +250,17 @@ func (dsc *DaemonSetsController) Run(workers int, stopCh <-chan struct{}) { dsc.queue.ShutDown() } -func (dsc *DaemonSetsController) worker() { +func (dsc *DaemonSetsController) runWorker() { for { - func() { - dsKey, quit := dsc.queue.Get() - if quit { - return - } - defer dsc.queue.Done(dsKey) - err := dsc.syncHandler(dsKey.(string)) - if err != nil { - glog.Errorf("Error syncing daemon set with key %s: %v", dsKey.(string), err) - } - }() - } -} - -func (dsc *DaemonSetsController) enqueueAllDaemonSets() { - glog.V(4).Infof("Enqueueing all daemon sets") - ds, err := dsc.dsStore.List() - if err != nil { - glog.Errorf("Error enqueueing daemon sets: %v", err) - return - } - for i := range ds.Items { - dsc.enqueueDaemonSet(&ds.Items[i]) + dsKey, quit := dsc.queue.Get() + if quit { + continue + } + err := dsc.syncHandler(dsKey.(string)) + if err != nil { + glog.Errorf("Error syncing daemon set with key %s: %v", dsKey.(string), err) + } + dsc.queue.Done(dsKey) } } @@ -299,7 +284,7 @@ func (dsc *DaemonSetsController) getPodDaemonSet(pod *api.Pod) *extensions.Daemo glog.Errorf("lookup cache does not retuen a ReplicationController object") return nil } - if cached && dsc.isCacheValid(pod, ds) { + if dsc.isCacheValid(pod, ds) { return ds } } @@ -498,17 +483,18 @@ func (dsc *DaemonSetsController) manage(ds *extensions.DaemonSet) { daemonPods, isRunning := nodeToDaemonPods[node.Name] - if shouldRun && !isRunning { + switch { + case shouldRun && !isRunning: // If daemon pod is supposed to be running on node, but isn't, create daemon pod. nodesNeedingDaemonPods = append(nodesNeedingDaemonPods, node.Name) - } else if shouldRun && len(daemonPods) > 1 { + case shouldRun && len(daemonPods) > 1: // If daemon pod is supposed to be running on node, but more than 1 daemon pod is running, delete the excess daemon pods. // Sort the daemon pods by creation time, so the the oldest is preserved. sort.Sort(podByCreationTimestamp(daemonPods)) for i := 1; i < len(daemonPods); i++ { podsToDelete = append(podsToDelete, daemonPods[i].Name) } - } else if !shouldRun && isRunning { + case !shouldRun && isRunning: // If daemon pod isn't supposed to run on node, but it is, delete all daemon pods on node. for i := range daemonPods { podsToDelete = append(podsToDelete, daemonPods[i].Name) @@ -567,21 +553,22 @@ func (dsc *DaemonSetsController) manage(ds *extensions.DaemonSet) { } func storeDaemonSetStatus(dsClient unversionedextensions.DaemonSetInterface, ds *extensions.DaemonSet, desiredNumberScheduled, currentNumberScheduled, numberMisscheduled int) error { - if int(ds.Status.DesiredNumberScheduled) == desiredNumberScheduled && int(ds.Status.CurrentNumberScheduled) == currentNumberScheduled && int(ds.Status.NumberMisscheduled) == numberMisscheduled { + if int(ds.Status.DesiredNumberScheduled) == desiredNumberScheduled && + int(ds.Status.CurrentNumberScheduled) == currentNumberScheduled && + int(ds.Status.NumberMisscheduled) == numberMisscheduled { return nil } var updateErr, getErr error - for i := 0; i <= StatusUpdateRetries; i++ { + for i := 0; i < StatusUpdateRetries; i++ { ds.Status.DesiredNumberScheduled = int32(desiredNumberScheduled) ds.Status.CurrentNumberScheduled = int32(currentNumberScheduled) ds.Status.NumberMisscheduled = int32(numberMisscheduled) - _, updateErr = dsClient.UpdateStatus(ds) - if updateErr == nil { - // successful update + if _, updateErr = dsClient.UpdateStatus(ds); updateErr == nil { return nil } + // Update the set with the latest resource version for the next poll if ds, getErr = dsClient.Get(ds.Name); getErr != nil { // If the GET fails we can't trust status.Replicas anymore. This error @@ -597,29 +584,30 @@ func (dsc *DaemonSetsController) updateDaemonSetStatus(ds *extensions.DaemonSet) nodeToDaemonPods, err := dsc.getNodesToDaemonPods(ds) if err != nil { glog.Errorf("Error getting node to daemon pod mapping for daemon set %+v: %v", ds, err) + return } nodeList, err := dsc.nodeStore.List() if err != nil { glog.Errorf("Couldn't get list of nodes when updating daemon set %+v: %v", ds, err) + return } var desiredNumberScheduled, currentNumberScheduled, numberMisscheduled int for _, node := range nodeList.Items { shouldRun := dsc.nodeShouldRunDaemonPod(&node, ds) - numDaemonPods := len(nodeToDaemonPods[node.Name]) - - if shouldRun && numDaemonPods > 0 { - currentNumberScheduled++ - } + scheduled := len(nodeToDaemonPods[node.Name]) > 0 if shouldRun { desiredNumberScheduled++ - } - - if !shouldRun && numDaemonPods > 0 { - numberMisscheduled++ + if scheduled { + currentNumberScheduled++ + } + } else { + if scheduled { + numberMisscheduled++ + } } } @@ -671,7 +659,7 @@ func (dsc *DaemonSetsController) syncDaemonSet(key string) error { return err } dsNeedsSync := dsc.expectations.SatisfiedExpectations(dsKey) - if dsNeedsSync { + if dsNeedsSync && ds.DeletionTimestamp == nil { dsc.manage(ds) } @@ -680,25 +668,22 @@ func (dsc *DaemonSetsController) syncDaemonSet(key string) error { } func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *api.Node, ds *extensions.DaemonSet) bool { - // Check if the node satisfies the daemon set's node selector. - nodeSelector := labels.Set(ds.Spec.Template.Spec.NodeSelector).AsSelector() - if !nodeSelector.Matches(labels.Set(node.Labels)) { - return false - } // If the daemon set specifies a node name, check that it matches with node.Name. if !(ds.Spec.Template.Spec.NodeName == "" || ds.Spec.Template.Spec.NodeName == node.Name) { return false } + // TODO: Move it to the predicates for _, c := range node.Status.Conditions { if c.Type == api.NodeOutOfDisk && c.Status == api.ConditionTrue { return false } } - newPod := &api.Pod{Spec: ds.Spec.Template.Spec} + newPod := &api.Pod{Spec: ds.Spec.Template.Spec, ObjectMeta: ds.Spec.Template.ObjectMeta} newPod.Spec.NodeName = node.Name - pods := []*api.Pod{newPod} + + pods := []*api.Pod{} for _, m := range dsc.podStore.Indexer.List() { pod := m.(*api.Pod) @@ -715,19 +700,23 @@ func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *api.Node, ds *exte } pods = append(pods, pod) } - _, notFittingCPU, notFittingMemory, notFittingNvidiaGPU := predicates.CheckPodsExceedingFreeResources(pods, node.Status.Allocatable) - if len(notFittingCPU)+len(notFittingMemory)+len(notFittingNvidiaGPU) != 0 { - dsc.eventRecorder.Eventf(ds, api.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: insufficent free resources", node.ObjectMeta.Name) - return false - } - ports := sets.String{} - for _, pod := range pods { - if errs := validation.AccumulateUniqueHostPorts(pod.Spec.Containers, &ports, field.NewPath("spec", "containers")); len(errs) > 0 { - dsc.eventRecorder.Eventf(ds, api.EventTypeNormal, "FailedPlacement", "failed to place pod on %q: host port conflict", node.ObjectMeta.Name) - return false + + nodeInfo := schedulercache.NewNodeInfo(pods...) + nodeInfo.SetNode(node) + fit, err := predicates.GeneralPredicates(newPod, nil, nodeInfo) + if err != nil { + if re, ok := err.(*predicates.PredicateFailureError); ok { + message := re.Error() + glog.V(2).Infof("Predicate failed on Pod: %s, for reason: %v", newPod.Name, message) } + if re, ok := err.(*predicates.InsufficientResourceError); ok { + message := re.Error() + glog.V(2).Infof("Predicate failed on Pod: %s, for reason: %v", newPod.Name, message) + } + message := fmt.Sprintf("GeneralPredicates failed due to %v.", err) + glog.Warningf("Predicate failed on Pod %s - %s", newPod.Name, message) } - return true + return fit } // byCreationTimestamp sorts a list by creation timestamp, using their names as a tie breaker. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/daemon/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/daemon/doc.go index db689ac1bb6a..9a5190a29b38 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/daemon/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/daemon/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/deployment/deployment_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/deployment_controller.go index ada8a327d0f6..8bbc62618bff 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/deployment/deployment_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/deployment_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,19 +14,19 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package deployment contains all the logic for handling Kubernetes Deployments. +// It implements a set of strategies (rolling, recreate) for deploying an application, +// the means to rollback to previous versions, proportional scaling for mitigating +// risk, cleanup policy, and other useful features of Deployments. package deployment import ( "fmt" "reflect" - "sort" - "strconv" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/annotations" - "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/client/cache" @@ -34,15 +34,10 @@ import ( unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" + "k8s.io/kubernetes/pkg/controller/deployment/util" "k8s.io/kubernetes/pkg/controller/framework" "k8s.io/kubernetes/pkg/runtime" - deploymentutil "k8s.io/kubernetes/pkg/util/deployment" - utilerrors "k8s.io/kubernetes/pkg/util/errors" - "k8s.io/kubernetes/pkg/util/integer" - labelsutil "k8s.io/kubernetes/pkg/util/labels" "k8s.io/kubernetes/pkg/util/metrics" - podutil "k8s.io/kubernetes/pkg/util/pod" - rsutil "k8s.io/kubernetes/pkg/util/replicaset" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/util/workqueue" @@ -57,6 +52,8 @@ const ( // We must avoid creating new replica set / counting pods until the replica set / pods store has synced. // If it hasn't synced, to avoid a hot loop, we'll wait this long between checks. StoreSyncedPollPeriod = 100 * time.Millisecond + // MaxRetries is the number of times a deployment will be retried before it is dropped out of the queue. + MaxRetries = 5 ) // DeploymentController is responsible for synchronizing Deployment objects stored @@ -76,19 +73,23 @@ type DeploymentController struct { rsStore cache.StoreToReplicaSetLister // Watches changes to all ReplicaSets rsController *framework.Controller - // rsStoreSynced returns true if the ReplicaSet store has been synced at least once. - // Added as a member to the struct to allow injection for testing. - rsStoreSynced func() bool // A store of pods, populated by the podController podStore cache.StoreToPodLister // Watches changes to all pods podController *framework.Controller + + // dStoreSynced returns true if the Deployment store has been synced at least once. + // Added as a member to the struct to allow injection for testing. + dStoreSynced func() bool + // rsStoreSynced returns true if the ReplicaSet store has been synced at least once. + // Added as a member to the struct to allow injection for testing. + rsStoreSynced func() bool // podStoreSynced returns true if the pod store has been synced at least once. // Added as a member to the struct to allow injection for testing. podStoreSynced func() bool // Deployments that need to be synced - queue *workqueue.Type + queue workqueue.RateLimitingInterface } // NewDeploymentController creates a new DeploymentController. @@ -104,7 +105,7 @@ func NewDeploymentController(client clientset.Interface, resyncPeriod controller dc := &DeploymentController{ client: client, eventRecorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "deployment-controller"}), - queue: workqueue.New(), + queue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), } dc.dStore.Store, dc.dController = framework.NewInformer( @@ -164,6 +165,7 @@ func NewDeploymentController(client clientset.Interface, resyncPeriod controller ) dc.syncHandler = dc.syncDeployment + dc.dStoreSynced = dc.dController.HasSynced dc.rsStoreSynced = dc.rsController.HasSynced dc.podStoreSynced = dc.podController.HasSynced return dc @@ -172,17 +174,43 @@ func NewDeploymentController(client clientset.Interface, resyncPeriod controller // Run begins watching and syncing. func (dc *DeploymentController) Run(workers int, stopCh <-chan struct{}) { defer utilruntime.HandleCrash() + go dc.dController.Run(stopCh) go dc.rsController.Run(stopCh) go dc.podController.Run(stopCh) + + // Wait for the rc and dc stores to sync before starting any work in this controller. + ready := make(chan struct{}) + go dc.waitForSyncedStores(ready, stopCh) + select { + case <-ready: + case <-stopCh: + return + } + for i := 0; i < workers; i++ { go wait.Until(dc.worker, time.Second, stopCh) } + <-stopCh glog.Infof("Shutting down deployment controller") dc.queue.ShutDown() } +func (dc *DeploymentController) waitForSyncedStores(ready chan<- struct{}, stopCh <-chan struct{}) { + defer utilruntime.HandleCrash() + + for !dc.dStoreSynced() || !dc.rsStoreSynced() || !dc.podStoreSynced() { + select { + case <-time.After(StoreSyncedPollPeriod): + case <-stopCh: + return + } + } + + close(ready) +} + func (dc *DeploymentController) addDeploymentNotification(obj interface{}) { d := obj.(*extensions.Deployment) glog.V(4).Infof("Adding deployment %s", d.Name) @@ -388,19 +416,40 @@ func (dc *DeploymentController) enqueueDeployment(deployment *extensions.Deploym // worker runs a worker thread that just dequeues items, processes them, and marks them done. // It enforces that the syncHandler is never invoked concurrently with the same key. func (dc *DeploymentController) worker() { + work := func() bool { + key, quit := dc.queue.Get() + if quit { + return true + } + defer dc.queue.Done(key) + + err := dc.syncHandler(key.(string)) + dc.handleErr(err, key) + + return false + } + for { - func() { - key, quit := dc.queue.Get() - if quit { - return - } - defer dc.queue.Done(key) - err := dc.syncHandler(key.(string)) - if err != nil { - glog.Errorf("Error syncing deployment %v: %v", key, err) - } - }() + if quit := work(); quit { + return + } + } +} + +func (dc *DeploymentController) handleErr(err error, key interface{}) { + if err == nil { + dc.queue.Forget(key) + return + } + + if dc.queue.NumRequeues(key) < MaxRetries { + glog.V(2).Infof("Error syncing deployment %v: %v", key, err) + dc.queue.AddRateLimited(key) + return } + + utilruntime.HandleError(err) + dc.queue.Forget(key) } // syncDeployment will sync the deployment with the given key. @@ -411,18 +460,9 @@ func (dc *DeploymentController) syncDeployment(key string) error { glog.V(4).Infof("Finished syncing deployment %q (%v)", key, time.Now().Sub(startTime)) }() - if !dc.rsStoreSynced() || !dc.podStoreSynced() { - // Sleep so we give the replica set / pod reflector goroutine a chance to run. - time.Sleep(StoreSyncedPollPeriod) - glog.Infof("Waiting for replica set / pod controller to sync, requeuing deployment %s", key) - dc.queue.Add(key) - return nil - } - obj, exists, err := dc.dStore.Store.GetByKey(key) if err != nil { glog.Infof("Unable to retrieve deployment %v from store: %v", key, err) - dc.queue.Add(key) return err } if !exists { @@ -430,873 +470,48 @@ func (dc *DeploymentController) syncDeployment(key string) error { return nil } - d := obj.(*extensions.Deployment) + deployment := obj.(*extensions.Deployment) everything := unversioned.LabelSelector{} - if reflect.DeepEqual(d.Spec.Selector, &everything) { - dc.eventRecorder.Eventf(d, api.EventTypeWarning, "SelectingAll", "This deployment is selecting all pods. A non-empty selector is required.") + if reflect.DeepEqual(deployment.Spec.Selector, &everything) { + dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, "SelectingAll", "This deployment is selecting all pods. A non-empty selector is required.") return nil } - if d.Spec.Paused { - // TODO: Implement scaling for paused deployments. - // Don't take any action for paused deployment. - // But keep the status up-to-date. - // Ignore paused deployments - glog.V(4).Infof("Updating status only for paused deployment %s/%s", d.Namespace, d.Name) - return dc.syncPausedDeploymentStatus(d) - } - if d.Spec.RollbackTo != nil { - revision := d.Spec.RollbackTo.Revision - if _, err = dc.rollback(d, &revision); err != nil { - return err - } - } - - switch d.Spec.Strategy.Type { - case extensions.RecreateDeploymentStrategyType: - return dc.syncRecreateDeployment(d) - case extensions.RollingUpdateDeploymentStrategyType: - return dc.syncRollingUpdateDeployment(d) - } - return fmt.Errorf("unexpected deployment strategy type: %s", d.Spec.Strategy.Type) -} - -// Updates the status of a paused deployment -func (dc *DeploymentController) syncPausedDeploymentStatus(deployment *extensions.Deployment) error { - newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, false) + // Deep-copy otherwise we are mutating our cache. + // TODO: Deep-copy only when needed. + d, err := util.DeploymentDeepCopy(deployment) if err != nil { return err } - allRSs := append(controller.FilterActiveReplicaSets(oldRSs), newRS) - - // Sync deployment status - return dc.syncDeploymentStatus(allRSs, newRS, deployment) -} -// Rolling back to a revision; no-op if the toRevision is deployment's current revision -func (dc *DeploymentController) rollback(deployment *extensions.Deployment, toRevision *int64) (*extensions.Deployment, error) { - newRS, allOldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, true) - if err != nil { - return nil, err - } - allRSs := append(allOldRSs, newRS) - // If rollback revision is 0, rollback to the last revision - if *toRevision == 0 { - if *toRevision = lastRevision(allRSs); *toRevision == 0 { - // If we still can't find the last revision, gives up rollback - dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find last revision.") - // Gives up rollback - return dc.updateDeploymentAndClearRollbackTo(deployment) - } - } - for _, rs := range allRSs { - v, err := deploymentutil.Revision(rs) - if err != nil { - glog.V(4).Infof("Unable to extract revision from deployment's replica set %q: %v", rs.Name, err) - continue - } - if v == *toRevision { - glog.V(4).Infof("Found replica set %q with desired revision %d", rs.Name, v) - // rollback by copying podTemplate.Spec from the replica set, and increment revision number by 1 - // no-op if the the spec matches current deployment's podTemplate.Spec - deployment, performedRollback, err := dc.rollbackToTemplate(deployment, rs) - if performedRollback && err == nil { - dc.emitRollbackNormalEvent(deployment, fmt.Sprintf("Rolled back deployment %q to revision %d", deployment.Name, *toRevision)) - } - return deployment, err - } + if d.DeletionTimestamp != nil { + return dc.syncStatusOnly(d) } - dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find the revision to rollback to.") - // Gives up rollback - return dc.updateDeploymentAndClearRollbackTo(deployment) -} -func (dc *DeploymentController) emitRollbackWarningEvent(deployment *extensions.Deployment, reason, message string) { - dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, reason, message) -} - -func (dc *DeploymentController) emitRollbackNormalEvent(deployment *extensions.Deployment, message string) { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, deploymentutil.RollbackDone, message) -} - -// updateDeploymentAndClearRollbackTo sets .spec.rollbackTo to nil and update the input deployment -func (dc *DeploymentController) updateDeploymentAndClearRollbackTo(deployment *extensions.Deployment) (*extensions.Deployment, error) { - glog.V(4).Infof("Cleans up rollbackTo of deployment %s", deployment.Name) - deployment.Spec.RollbackTo = nil - return dc.updateDeployment(deployment) -} - -func (dc *DeploymentController) syncRecreateDeployment(deployment *extensions.Deployment) error { - // Don't create a new RS if not already existed, so that we avoid scaling up before scaling down - newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, false) - if err != nil { - return err - } - allRSs := append(controller.FilterActiveReplicaSets(oldRSs), newRS) - - // scale down old replica sets - scaledDown, err := dc.scaleDownOldReplicaSetsForRecreate(controller.FilterActiveReplicaSets(oldRSs), deployment) - if err != nil { - return err - } - if scaledDown { - // Update DeploymentStatus - return dc.updateDeploymentStatus(allRSs, newRS, deployment) + if d.Spec.Paused { + return dc.sync(d) } - // If we need to create a new RS, create it now - // TODO: Create a new RS without re-listing all RSs. - if newRS == nil { - newRS, oldRSs, err = dc.getAllReplicaSetsAndSyncRevision(deployment, true) - if err != nil { + if d.Spec.RollbackTo != nil { + revision := d.Spec.RollbackTo.Revision + if _, err = dc.rollback(d, &revision); err != nil { return err } - allRSs = append(oldRSs, newRS) - } - - // scale up new replica set - scaledUp, err := dc.scaleUpNewReplicaSetForRecreate(newRS, deployment) - if err != nil { - return err - } - if scaledUp { - // Update DeploymentStatus - return dc.updateDeploymentStatus(allRSs, newRS, deployment) } - if deployment.Spec.RevisionHistoryLimit != nil { - // Cleanup old replica sets - dc.cleanupOldReplicaSets(oldRSs, deployment) - } - - // Sync deployment status - return dc.syncDeploymentStatus(allRSs, newRS, deployment) -} - -func (dc *DeploymentController) syncRollingUpdateDeployment(deployment *extensions.Deployment) error { - newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, true) - if err != nil { - return err - } - allRSs := append(controller.FilterActiveReplicaSets(oldRSs), newRS) - - // Scale up, if we can. - scaledUp, err := dc.reconcileNewReplicaSet(allRSs, newRS, deployment) + scalingEvent, err := dc.isScalingEvent(d) if err != nil { return err } - if scaledUp { - // Update DeploymentStatus - return dc.updateDeploymentStatus(allRSs, newRS, deployment) - } - - // Scale down, if we can. - scaledDown, err := dc.reconcileOldReplicaSets(allRSs, controller.FilterActiveReplicaSets(oldRSs), newRS, deployment) - if err != nil { - return err - } - if scaledDown { - // Update DeploymentStatus - return dc.updateDeploymentStatus(allRSs, newRS, deployment) - } - - if deployment.Spec.RevisionHistoryLimit != nil { - // Cleanup old replicas sets - dc.cleanupOldReplicaSets(oldRSs, deployment) - } - - // Sync deployment status - return dc.syncDeploymentStatus(allRSs, newRS, deployment) -} - -// syncDeploymentStatus checks if the status is up-to-date and sync it if necessary -func (dc *DeploymentController) syncDeploymentStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, d *extensions.Deployment) error { - totalActualReplicas, updatedReplicas, availableReplicas, _, err := dc.calculateStatus(allRSs, newRS, d) - if err != nil { - return err - } - if d.Generation > d.Status.ObservedGeneration || d.Status.Replicas != totalActualReplicas || d.Status.UpdatedReplicas != updatedReplicas || d.Status.AvailableReplicas != availableReplicas { - return dc.updateDeploymentStatus(allRSs, newRS, d) - } - return nil -} - -// getAllReplicaSetsAndSyncRevision returns all the replica sets for the provided deployment (new and all old), with new RS's and deployment's revision updated. -// 1. Get all old RSes this deployment targets, and calculate the max revision number among them (maxOldV). -// 2. Get new RS this deployment targets (whose pod template matches deployment's), and update new RS's revision number to (maxOldV + 1), -// only if its revision number is smaller than (maxOldV + 1). If this step failed, we'll update it in the next deployment sync loop. -// 3. Copy new RS's revision number to deployment (update deployment's revision). If this step failed, we'll update it in the next deployment sync loop. -func (dc *DeploymentController) getAllReplicaSetsAndSyncRevision(deployment *extensions.Deployment, createIfNotExisted bool) (*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { - // List the deployment's RSes & Pods and apply pod-template-hash info to deployment's adopted RSes/Pods - rsList, podList, err := dc.rsAndPodsWithHashKeySynced(deployment) - if err != nil { - return nil, nil, fmt.Errorf("error labeling replica sets and pods with pod-template-hash: %v", err) - } - _, allOldRSs, err := deploymentutil.FindOldReplicaSets(deployment, rsList, podList) - if err != nil { - return nil, nil, err - } - - // Calculate the max revision number among all old RSes - maxOldV := maxRevision(allOldRSs) - - // Get new replica set with the updated revision number - newRS, err := dc.getNewReplicaSet(deployment, rsList, maxOldV, allOldRSs, createIfNotExisted) - if err != nil { - return nil, nil, err - } - - // Sync deployment's revision number with new replica set - if newRS != nil && newRS.Annotations != nil && len(newRS.Annotations[deploymentutil.RevisionAnnotation]) > 0 && - (deployment.Annotations == nil || deployment.Annotations[deploymentutil.RevisionAnnotation] != newRS.Annotations[deploymentutil.RevisionAnnotation]) { - if err = dc.updateDeploymentRevision(deployment, newRS.Annotations[deploymentutil.RevisionAnnotation]); err != nil { - glog.V(4).Infof("Error: %v. Unable to update deployment revision, will retry later.", err) - } - } - - return newRS, allOldRSs, nil -} - -func maxRevision(allRSs []*extensions.ReplicaSet) int64 { - max := int64(0) - for _, rs := range allRSs { - if v, err := deploymentutil.Revision(rs); err != nil { - // Skip the replica sets when it failed to parse their revision information - glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) - } else if v > max { - max = v - } - } - return max -} - -// lastRevision finds the second max revision number in all replica sets (the last revision) -func lastRevision(allRSs []*extensions.ReplicaSet) int64 { - max, secMax := int64(0), int64(0) - for _, rs := range allRSs { - if v, err := deploymentutil.Revision(rs); err != nil { - // Skip the replica sets when it failed to parse their revision information - glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) - } else if v >= max { - secMax = max - max = v - } else if v > secMax { - secMax = v - } + if scalingEvent { + return dc.sync(d) } - return secMax -} - -// Returns a replica set that matches the intent of the given deployment. Returns nil if the new replica set doesn't exist yet. -// 1. Get existing new RS (the RS that the given deployment targets, whose pod template is the same as deployment's). -// 2. If there's existing new RS, update its revision number if it's smaller than (maxOldRevision + 1), where maxOldRevision is the max revision number among all old RSes. -// 3. If there's no existing new RS and createIfNotExisted is true, create one with appropriate revision number (maxOldRevision + 1) and replicas. -// Note that the pod-template-hash will be added to adopted RSes and pods. -func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployment, rsList []extensions.ReplicaSet, maxOldRevision int64, oldRSs []*extensions.ReplicaSet, createIfNotExisted bool) (*extensions.ReplicaSet, error) { - // Calculate revision number for this new replica set - newRevision := strconv.FormatInt(maxOldRevision+1, 10) - existingNewRS, err := deploymentutil.FindNewReplicaSet(deployment, rsList) - if err != nil { - return nil, err - } else if existingNewRS != nil { - // Set existing new replica set's annotation - if setNewReplicaSetAnnotations(deployment, existingNewRS, newRevision) { - return dc.client.Extensions().ReplicaSets(deployment.ObjectMeta.Namespace).Update(existingNewRS) - } - return existingNewRS, nil - } - - if !createIfNotExisted { - return nil, nil - } - - // new ReplicaSet does not exist, create one. - namespace := deployment.ObjectMeta.Namespace - podTemplateSpecHash := podutil.GetPodTemplateSpecHash(deployment.Spec.Template) - newRSTemplate := deploymentutil.GetNewReplicaSetTemplate(deployment) - // Add podTemplateHash label to selector. - newRSSelector := labelsutil.CloneSelectorAndAddLabel(deployment.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey, podTemplateSpecHash) - - // Create new ReplicaSet - newRS := extensions.ReplicaSet{ - ObjectMeta: api.ObjectMeta{ - // Make the name deterministic, to ensure idempotence - Name: deployment.Name + "-" + fmt.Sprintf("%d", podTemplateSpecHash), - Namespace: namespace, - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: 0, - Selector: newRSSelector, - Template: newRSTemplate, - }, - } - // Set new replica set's annotation - setNewReplicaSetAnnotations(deployment, &newRS, newRevision) - allRSs := append(oldRSs, &newRS) - newReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, &newRS) - if err != nil { - return nil, err - } - - newRS.Spec.Replicas = newReplicasCount - createdRS, err := dc.client.Extensions().ReplicaSets(namespace).Create(&newRS) - if err != nil { - dc.enqueueDeployment(deployment) - return nil, fmt.Errorf("error creating replica set %v: %v", deployment.Name, err) - } - if newReplicasCount > 0 { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", "up", createdRS.Name, newReplicasCount) - } - - return createdRS, dc.updateDeploymentRevision(deployment, newRevision) -} - -// rsAndPodsWithHashKeySynced returns the RSes and pods the given deployment targets, with pod-template-hash information synced. -func (dc *DeploymentController) rsAndPodsWithHashKeySynced(deployment *extensions.Deployment) ([]extensions.ReplicaSet, *api.PodList, error) { - rsList, err := deploymentutil.ListReplicaSets(deployment, - func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { - return dc.rsStore.ReplicaSets(namespace).List(options.LabelSelector) - }) - if err != nil { - return nil, nil, fmt.Errorf("error listing ReplicaSets: %v", err) - } - syncedRSList := []extensions.ReplicaSet{} - for _, rs := range rsList { - // Add pod-template-hash information if it's not in the RS. - // Otherwise, new RS produced by Deployment will overlap with pre-existing ones - // that aren't constrained by the pod-template-hash. - syncedRS, err := dc.addHashKeyToRSAndPods(rs) - if err != nil { - return nil, nil, err - } - syncedRSList = append(syncedRSList, *syncedRS) - } - syncedPodList, err := dc.listPods(deployment) - if err != nil { - return nil, nil, err - } - return syncedRSList, syncedPodList, nil -} - -func (dc *DeploymentController) listPods(deployment *extensions.Deployment) (*api.PodList, error) { - return deploymentutil.ListPods(deployment, - func(namespace string, options api.ListOptions) (*api.PodList, error) { - podList, err := dc.podStore.Pods(namespace).List(options.LabelSelector) - return &podList, err - }) -} - -// addHashKeyToRSAndPods adds pod-template-hash information to the given rs, if it's not already there, with the following steps: -// 1. Add hash label to the rs's pod template, and make sure the controller sees this update so that no orphaned pods will be created -// 2. Add hash label to all pods this rs owns, wait until replicaset controller reports rs.Status.FullyLabeledReplicas equal to the desired number of replicas -// 3. Add hash label to the rs's label and selector -func (dc *DeploymentController) addHashKeyToRSAndPods(rs extensions.ReplicaSet) (updatedRS *extensions.ReplicaSet, err error) { - updatedRS = &rs - // If the rs already has the new hash label in its selector, it's done syncing - if labelsutil.SelectorHasLabel(rs.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey) { - return - } - namespace := rs.Namespace - hash := rsutil.GetPodTemplateSpecHash(rs) - rsUpdated := false - // 1. Add hash template label to the rs. This ensures that any newly created pods will have the new label. - updatedRS, rsUpdated, err = rsutil.UpdateRSWithRetries(dc.client.Extensions().ReplicaSets(namespace), updatedRS, - func(updated *extensions.ReplicaSet) error { - // Precondition: the RS doesn't contain the new hash in its pod template label. - if updated.Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash { - return utilerrors.ErrPreconditionViolated - } - updated.Spec.Template.Labels = labelsutil.AddLabel(updated.Spec.Template.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) - return nil - }) - if err != nil { - return nil, fmt.Errorf("error updating %s %s/%s pod template label with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) - } - if !rsUpdated { - // If RS wasn't updated but didn't return error in step 1, we've hit a RS not found error. - // Return here and retry in the next sync loop. - return &rs, nil - } - // Make sure rs pod template is updated so that it won't create pods without the new label (orphaned pods). - if updatedRS.Generation > updatedRS.Status.ObservedGeneration { - if err = deploymentutil.WaitForReplicaSetUpdated(dc.client, updatedRS.Generation, namespace, updatedRS.Name); err != nil { - return nil, fmt.Errorf("error waiting for %s %s/%s generation %d observed by controller: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, updatedRS.Generation, err) - } - } - glog.V(4).Infof("Observed the update of %s %s/%s's pod template with hash %s.", rs.Kind, rs.Namespace, rs.Name, hash) - - // 2. Update all pods managed by the rs to have the new hash label, so they will be correctly adopted. - selector, err := unversioned.LabelSelectorAsSelector(updatedRS.Spec.Selector) - if err != nil { - return nil, fmt.Errorf("error in converting selector to label selector for replica set %s: %s", updatedRS.Name, err) - } - options := api.ListOptions{LabelSelector: selector} - podList, err := dc.podStore.Pods(namespace).List(options.LabelSelector) - if err != nil { - return nil, fmt.Errorf("error in getting pod list for namespace %s and list options %+v: %s", namespace, options, err) - } - allPodsLabeled := false - if allPodsLabeled, err = deploymentutil.LabelPodsWithHash(&podList, updatedRS, dc.client, namespace, hash); err != nil { - return nil, fmt.Errorf("error in adding template hash label %s to pods %+v: %s", hash, podList, err) - } - // If not all pods are labeled but didn't return error in step 2, we've hit at least one pod not found error. - // Return here and retry in the next sync loop. - if !allPodsLabeled { - return updatedRS, nil - } - - // We need to wait for the replicaset controller to observe the pods being - // labeled with pod template hash. Because previously we've called - // WaitForReplicaSetUpdated, the replicaset controller should have dropped - // FullyLabeledReplicas to 0 already, we only need to wait it to increase - // back to the number of replicas in the spec. - if err = deploymentutil.WaitForPodsHashPopulated(dc.client, updatedRS.Generation, namespace, updatedRS.Name); err != nil { - return nil, fmt.Errorf("%s %s/%s: error waiting for replicaset controller to observe pods being labeled with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) - } - - // 3. Update rs label and selector to include the new hash label - // Copy the old selector, so that we can scrub out any orphaned pods - if updatedRS, rsUpdated, err = rsutil.UpdateRSWithRetries(dc.client.Extensions().ReplicaSets(namespace), updatedRS, - func(updated *extensions.ReplicaSet) error { - // Precondition: the RS doesn't contain the new hash in its label or selector. - if updated.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash && updated.Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey] == hash { - return utilerrors.ErrPreconditionViolated - } - updated.Labels = labelsutil.AddLabel(updated.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) - updated.Spec.Selector = labelsutil.AddLabelToSelector(updated.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey, hash) - return nil - }); err != nil { - return nil, fmt.Errorf("error updating %s %s/%s label and selector with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) - } - if rsUpdated { - glog.V(4).Infof("Updated %s %s/%s's selector and label with hash %s.", rs.Kind, rs.Namespace, rs.Name, hash) - } - // If the RS isn't actually updated in step 3, that's okay, we'll retry in the next sync loop since its selector isn't updated yet. - - // TODO: look for orphaned pods and label them in the background somewhere else periodically - - return updatedRS, nil -} - -// setNewReplicaSetAnnotations sets new replica set's annotations appropriately by updating its revision and -// copying required deployment annotations to it; it returns true if replica set's annotation is changed. -func setNewReplicaSetAnnotations(deployment *extensions.Deployment, newRS *extensions.ReplicaSet, newRevision string) bool { - // First, copy deployment's annotations (except for apply and revision annotations) - annotationChanged := copyDeploymentAnnotationsToReplicaSet(deployment, newRS) - // Then, update replica set's revision annotation - if newRS.Annotations == nil { - newRS.Annotations = make(map[string]string) - } - // The newRS's revision should be the greatest among all RSes. Usually, its revision number is newRevision (the max revision number - // of all old RSes + 1). However, it's possible that some of the old RSes are deleted after the newRS revision being updated, and - // newRevision becomes smaller than newRS's revision. We should only update newRS revision when it's smaller than newRevision. - if newRS.Annotations[deploymentutil.RevisionAnnotation] < newRevision { - newRS.Annotations[deploymentutil.RevisionAnnotation] = newRevision - annotationChanged = true - glog.V(4).Infof("updating replica set %q's revision to %s - %+v\n", newRS.Name, newRevision, newRS) - } - return annotationChanged -} - -// skipCopyAnnotation returns true if we should skip copying the annotation with the given annotation key -// TODO: How to decide which annotations should / should not be copied? -// See https://github.com/kubernetes/kubernetes/pull/20035#issuecomment-179558615 -func skipCopyAnnotation(key string) bool { - // Skip apply annotations and revision annotations. - return key == annotations.LastAppliedConfigAnnotation || key == deploymentutil.RevisionAnnotation -} - -func getSkippedAnnotations(annotations map[string]string) map[string]string { - skippedAnnotations := make(map[string]string) - for k, v := range annotations { - if skipCopyAnnotation(k) { - skippedAnnotations[k] = v - } - } - return skippedAnnotations -} - -// copyDeploymentAnnotationsToReplicaSet copies deployment's annotations to replica set's annotations, -// and returns true if replica set's annotation is changed. -// Note that apply and revision annotations are not copied. -func copyDeploymentAnnotationsToReplicaSet(deployment *extensions.Deployment, rs *extensions.ReplicaSet) bool { - rsAnnotationsChanged := false - if rs.Annotations == nil { - rs.Annotations = make(map[string]string) - } - for k, v := range deployment.Annotations { - // newRS revision is updated automatically in getNewReplicaSet, and the deployment's revision number is then updated - // by copying its newRS revision number. We should not copy deployment's revision to its newRS, since the update of - // deployment revision number may fail (revision becomes stale) and the revision number in newRS is more reliable. - if skipCopyAnnotation(k) || rs.Annotations[k] == v { - continue - } - rs.Annotations[k] = v - rsAnnotationsChanged = true - } - return rsAnnotationsChanged -} - -// setDeploymentAnnotationsTo sets deployment's annotations as given RS's annotations. -// This action should be done if and only if the deployment is rolling back to this rs. -// Note that apply and revision annotations are not changed. -func setDeploymentAnnotationsTo(deployment *extensions.Deployment, rollbackToRS *extensions.ReplicaSet) { - deployment.Annotations = getSkippedAnnotations(deployment.Annotations) - for k, v := range rollbackToRS.Annotations { - if !skipCopyAnnotation(k) { - deployment.Annotations[k] = v - } - } -} - -func (dc *DeploymentController) updateDeploymentRevision(deployment *extensions.Deployment, revision string) error { - if deployment.Annotations == nil { - deployment.Annotations = make(map[string]string) - } - if deployment.Annotations[deploymentutil.RevisionAnnotation] != revision { - deployment.Annotations[deploymentutil.RevisionAnnotation] = revision - _, err := dc.updateDeployment(deployment) - return err - } - return nil -} - -func (dc *DeploymentController) reconcileNewReplicaSet(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - if newRS.Spec.Replicas == deployment.Spec.Replicas { - // Scaling not required. - return false, nil - } - if newRS.Spec.Replicas > deployment.Spec.Replicas { - // Scale down. - scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) - return scaled, err - } - newReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, newRS) - if err != nil { - return false, err - } - scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, newReplicasCount, deployment) - return scaled, err -} - -func (dc *DeploymentController) getAvailablePodsForReplicaSets(deployment *extensions.Deployment, rss []*extensions.ReplicaSet, minReadySeconds int32) (int32, error) { - podList, err := dc.listPods(deployment) - if err != nil { - return 0, err - } - return deploymentutil.CountAvailablePodsForReplicaSets(podList, rss, minReadySeconds) -} - -func (dc *DeploymentController) reconcileOldReplicaSets(allRSs []*extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - oldPodsCount := deploymentutil.GetReplicaCountForReplicaSets(oldRSs) - if oldPodsCount == 0 { - // Can't scale down further - return false, nil - } - - minReadySeconds := deployment.Spec.MinReadySeconds - allPodsCount := deploymentutil.GetReplicaCountForReplicaSets(allRSs) - // TODO: use dc.getAvailablePodsForReplicaSets instead - newRSAvailablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, []*extensions.ReplicaSet{newRS}, minReadySeconds) - if err != nil { - return false, fmt.Errorf("could not find available pods: %v", err) - } - - _, maxUnavailable, err := deploymentutil.ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) - if err != nil { - return false, err - } - - // Check if we can scale down. We can scale down in the following 2 cases: - // * Some old replica sets have unhealthy replicas, we could safely scale down those unhealthy replicas since that won't further - // increase unavailability. - // * New replica set has scaled up and it's replicas becomes ready, then we can scale down old replica sets in a further step. - // - // maxScaledDown := allPodsCount - minAvailable - newReplicaSetPodsUnavailable - // take into account not only maxUnavailable and any surge pods that have been created, but also unavailable pods from - // the newRS, so that the unavailable pods from the newRS would not make us scale down old replica sets in a further - // step(that will increase unavailability). - // - // Concrete example: - // - // * 10 replicas - // * 2 maxUnavailable (absolute number, not percent) - // * 3 maxSurge (absolute number, not percent) - // - // case 1: - // * Deployment is updated, newRS is created with 3 replicas, oldRS is scaled down to 8, and newRS is scaled up to 5. - // * The new replica set pods crashloop and never become available. - // * allPodsCount is 13. minAvailable is 8. newRSPodsUnavailable is 5. - // * A node fails and causes one of the oldRS pods to become unavailable. However, 13 - 8 - 5 = 0, so the oldRS won't be scaled down. - // * The user notices the crashloop and does kubectl rollout undo to rollback. - // * newRSPodsUnavailable is 1, since we rolled back to the good replica set, so maxScaledDown = 13 - 8 - 1 = 4. 4 of the crashlooping pods will be scaled down. - // * The total number of pods will then be 9 and the newRS can be scaled up to 10. - // - // case 2: - // Same example, but pushing a new pod template instead of rolling back (aka "roll over"): - // * The new replica set created must start with 0 replicas because allPodsCount is already at 13. - // * However, newRSPodsUnavailable would also be 0, so the 2 old replica sets could be scaled down by 5 (13 - 8 - 0), which would then - // allow the new replica set to be scaled up by 5. - minAvailable := deployment.Spec.Replicas - maxUnavailable - newRSUnavailablePodCount := newRS.Spec.Replicas - newRSAvailablePodCount - maxScaledDown := allPodsCount - minAvailable - newRSUnavailablePodCount - if maxScaledDown <= 0 { - return false, nil - } - - // Clean up unhealthy replicas first, otherwise unhealthy replicas will block deployment - // and cause timeout. See https://github.com/kubernetes/kubernetes/issues/16737 - oldRSs, cleanupCount, err := dc.cleanupUnhealthyReplicas(oldRSs, deployment, deployment.Spec.MinReadySeconds, maxScaledDown) - if err != nil { - return false, nil - } - glog.V(4).Infof("Cleaned up unhealthy replicas from old RSes by %d", cleanupCount) - - // Scale down old replica sets, need check maxUnavailable to ensure we can scale down - allRSs = append(oldRSs, newRS) - scaledDownCount, err := dc.scaleDownOldReplicaSetsForRollingUpdate(allRSs, oldRSs, deployment) - if err != nil { - return false, nil - } - glog.V(4).Infof("Scaled down old RSes of deployment %s by %d", deployment.Name, scaledDownCount) - - totalScaledDown := cleanupCount + scaledDownCount - return totalScaledDown > 0, nil -} - -// cleanupUnhealthyReplicas will scale down old replica sets with unhealthy replicas, so that all unhealthy replicas will be deleted. -func (dc *DeploymentController) cleanupUnhealthyReplicas(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment, minReadySeconds, maxCleanupCount int32) ([]*extensions.ReplicaSet, int32, error) { - sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) - // Safely scale down all old replica sets with unhealthy replicas. Replica set will sort the pods in the order - // such that not-ready < ready, unscheduled < scheduled, and pending < running. This ensures that unhealthy replicas will - // been deleted first and won't increase unavailability. - totalScaledDown := int32(0) - for i, targetRS := range oldRSs { - if totalScaledDown >= maxCleanupCount { - break - } - if targetRS.Spec.Replicas == 0 { - // cannot scale down this replica set. - continue - } - // TODO: use dc.getAvailablePodsForReplicaSets instead - availablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, []*extensions.ReplicaSet{targetRS}, minReadySeconds) - if err != nil { - return nil, totalScaledDown, fmt.Errorf("could not find available pods: %v", err) - } - if targetRS.Spec.Replicas == availablePodCount { - // no unhealthy replicas found, no scaling required. - continue - } - - scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(targetRS.Spec.Replicas-availablePodCount))) - newReplicasCount := targetRS.Spec.Replicas - scaledDownCount - if newReplicasCount > targetRS.Spec.Replicas { - return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) - } - _, updatedOldRS, err := dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) - if err != nil { - return nil, totalScaledDown, err - } - totalScaledDown += scaledDownCount - oldRSs[i] = updatedOldRS - } - return oldRSs, totalScaledDown, nil -} - -// scaleDownOldReplicaSetsForRollingUpdate scales down old replica sets when deployment strategy is "RollingUpdate". -// Need check maxUnavailable to ensure availability -func (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(allRSs []*extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) (int32, error) { - _, maxUnavailable, err := deploymentutil.ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) - if err != nil { - return 0, err - } - - // Check if we can scale down. - minAvailable := deployment.Spec.Replicas - maxUnavailable - minReadySeconds := deployment.Spec.MinReadySeconds - // Find the number of ready pods. - // TODO: use dc.getAvailablePodsForReplicaSets instead - availablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, allRSs, minReadySeconds) - if err != nil { - return 0, fmt.Errorf("could not find available pods: %v", err) - } - if availablePodCount <= minAvailable { - // Cannot scale down. - return 0, nil - } - glog.V(4).Infof("Found %d available pods in deployment %s, scaling down old RSes", availablePodCount, deployment.Name) - - sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) - - totalScaledDown := int32(0) - totalScaleDownCount := availablePodCount - minAvailable - for _, targetRS := range oldRSs { - if totalScaledDown >= totalScaleDownCount { - // No further scaling required. - break - } - if targetRS.Spec.Replicas == 0 { - // cannot scale down this ReplicaSet. - continue - } - // Scale down. - scaleDownCount := int32(integer.IntMin(int(targetRS.Spec.Replicas), int(totalScaleDownCount-totalScaledDown))) - newReplicasCount := targetRS.Spec.Replicas - scaleDownCount - if newReplicasCount > targetRS.Spec.Replicas { - return 0, fmt.Errorf("when scaling down old RS, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) - } - _, _, err = dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) - if err != nil { - return totalScaledDown, err - } - - totalScaledDown += scaleDownCount - } - - return totalScaledDown, nil -} - -// scaleDownOldReplicaSetsForRecreate scales down old replica sets when deployment strategy is "Recreate" -func (dc *DeploymentController) scaleDownOldReplicaSetsForRecreate(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - scaled := false - for _, rs := range oldRSs { - // Scaling not required. - if rs.Spec.Replicas == 0 { - continue - } - scaledRS, _, err := dc.scaleReplicaSetAndRecordEvent(rs, 0, deployment) - if err != nil { - return false, err - } - if scaledRS { - scaled = true - } - } - return scaled, nil -} - -// scaleUpNewReplicaSetForRecreate scales up new replica set when deployment strategy is "Recreate" -func (dc *DeploymentController) scaleUpNewReplicaSetForRecreate(newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { - scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) - return scaled, err -} - -func (dc *DeploymentController) cleanupOldReplicaSets(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) error { - diff := int32(len(oldRSs)) - *deployment.Spec.RevisionHistoryLimit - if diff <= 0 { - return nil - } - - sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) - - var errList []error - // TODO: This should be parallelized. - for i := int32(0); i < diff; i++ { - rs := oldRSs[i] - // Avoid delete replica set with non-zero replica counts - if rs.Status.Replicas != 0 || rs.Spec.Replicas != 0 || rs.Generation > rs.Status.ObservedGeneration { - continue - } - if err := dc.client.Extensions().ReplicaSets(rs.Namespace).Delete(rs.Name, nil); err != nil && !errors.IsNotFound(err) { - glog.V(2).Infof("Failed deleting old replica set %v for deployment %v: %v", rs.Name, deployment.Name, err) - errList = append(errList, err) - } - } - - return utilerrors.NewAggregate(errList) -} - -func (dc *DeploymentController) updateDeploymentStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) error { - totalActualReplicas, updatedReplicas, availableReplicas, unavailableReplicas, err := dc.calculateStatus(allRSs, newRS, deployment) - if err != nil { - return err - } - newDeployment := *deployment - // TODO: Reconcile this with API definition. API definition talks about ready pods, while this just computes created pods. - newDeployment.Status = extensions.DeploymentStatus{ - // TODO: Ensure that if we start retrying status updates, we won't pick up a new Generation value. - ObservedGeneration: deployment.Generation, - Replicas: totalActualReplicas, - UpdatedReplicas: updatedReplicas, - AvailableReplicas: availableReplicas, - UnavailableReplicas: unavailableReplicas, - } - _, err = dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).UpdateStatus(&newDeployment) - if err == nil { - glog.V(4).Infof("Updated deployment %s status: %+v", deployment.Name, newDeployment.Status) - } - return err -} - -func (dc *DeploymentController) calculateStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (totalActualReplicas, updatedReplicas, availableReplicas, unavailableReplicas int32, err error) { - totalActualReplicas = deploymentutil.GetActualReplicaCountForReplicaSets(allRSs) - updatedReplicas = deploymentutil.GetActualReplicaCountForReplicaSets([]*extensions.ReplicaSet{newRS}) - minReadySeconds := deployment.Spec.MinReadySeconds - availableReplicas, err = dc.getAvailablePodsForReplicaSets(deployment, allRSs, minReadySeconds) - if err != nil { - err = fmt.Errorf("failed to count available pods: %v", err) - return - } - totalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs) - unavailableReplicas = totalReplicas - availableReplicas - return -} - -func (dc *DeploymentController) scaleReplicaSetAndRecordEvent(rs *extensions.ReplicaSet, newScale int32, deployment *extensions.Deployment) (bool, *extensions.ReplicaSet, error) { - // No need to scale - if rs.Spec.Replicas == newScale { - return false, rs, nil - } - var scalingOperation string - if rs.Spec.Replicas < newScale { - scalingOperation = "up" - } else { - scalingOperation = "down" - } - newRS, err := dc.scaleReplicaSet(rs, newScale) - if err == nil { - dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", scalingOperation, rs.Name, newScale) - } else { - dc.enqueueDeployment(deployment) - } - return true, newRS, err -} - -func (dc *DeploymentController) scaleReplicaSet(rs *extensions.ReplicaSet, newScale int32) (*extensions.ReplicaSet, error) { - // TODO: Using client for now, update to use store when it is ready. - // NOTE: This mutates the ReplicaSet passed in. Not sure if that's a good idea. - rs.Spec.Replicas = newScale - return dc.client.Extensions().ReplicaSets(rs.ObjectMeta.Namespace).Update(rs) -} - -func (dc *DeploymentController) updateDeployment(deployment *extensions.Deployment) (*extensions.Deployment, error) { - // TODO: Using client for now, update to use store when it is ready. - return dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).Update(deployment) -} - -func (dc *DeploymentController) rollbackToTemplate(deployment *extensions.Deployment, rs *extensions.ReplicaSet) (d *extensions.Deployment, performedRollback bool, err error) { - if !reflect.DeepEqual(deploymentutil.GetNewReplicaSetTemplate(deployment), rs.Spec.Template) { - glog.Infof("Rolling back deployment %s to template spec %+v", deployment.Name, rs.Spec.Template.Spec) - deploymentutil.SetFromReplicaSetTemplate(deployment, rs.Spec.Template) - // set RS (the old RS we'll rolling back to) annotations back to the deployment; - // otherwise, the deployment's current annotations (should be the same as current new RS) will be copied to the RS after the rollback. - // - // For example, - // A Deployment has old RS1 with annotation {change-cause:create}, and new RS2 {change-cause:edit}. - // Note that both annotations are copied from Deployment, and the Deployment should be annotated {change-cause:edit} as well. - // Now, rollback Deployment to RS1, we should update Deployment's pod-template and also copy annotation from RS1. - // Deployment is now annotated {change-cause:create}, and we have new RS1 {change-cause:create}, old RS2 {change-cause:edit}. - // - // If we don't copy the annotations back from RS to deployment on rollback, the Deployment will stay as {change-cause:edit}, - // and new RS1 becomes {change-cause:edit} (copied from deployment after rollback), old RS2 {change-cause:edit}, which is not correct. - setDeploymentAnnotationsTo(deployment, rs) - performedRollback = true - } else { - glog.V(4).Infof("Rolling back to a revision that contains the same template as current deployment %s, skipping rollback...", deployment.Name) - dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackTemplateUnchanged, fmt.Sprintf("The rollback revision contains the same template as current deployment %q", deployment.Name)) + switch d.Spec.Strategy.Type { + case extensions.RecreateDeploymentStrategyType: + return dc.rolloutRecreate(d) + case extensions.RollingUpdateDeploymentStrategyType: + return dc.rolloutRolling(d) } - d, err = dc.updateDeploymentAndClearRollbackTo(deployment) - return + return fmt.Errorf("unexpected deployment strategy type: %s", d.Spec.Strategy.Type) } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/deployment/recreate.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/recreate.go new file mode 100644 index 000000000000..385f5a2ad22b --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/recreate.go @@ -0,0 +1,115 @@ +/* +Copyright 2016 The Kubernetes 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 deployment + +import ( + "k8s.io/kubernetes/pkg/apis/extensions" + unversionedclient "k8s.io/kubernetes/pkg/client/unversioned" + "k8s.io/kubernetes/pkg/controller" + rsutil "k8s.io/kubernetes/pkg/util/replicaset" + "k8s.io/kubernetes/pkg/util/wait" +) + +// rolloutRecreate implements the logic for recreating a replica set. +func (dc *DeploymentController) rolloutRecreate(deployment *extensions.Deployment) error { + // Don't create a new RS if not already existed, so that we avoid scaling up before scaling down + newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, false) + if err != nil { + return err + } + allRSs := append(oldRSs, newRS) + activeOldRSs := controller.FilterActiveReplicaSets(oldRSs) + + // scale down old replica sets + scaledDown, err := dc.scaleDownOldReplicaSetsForRecreate(activeOldRSs, deployment) + if err != nil { + return err + } + if scaledDown { + // Update DeploymentStatus + return dc.updateDeploymentStatus(allRSs, newRS, deployment) + } + + // Wait for all old replica set to scale down to zero. + if err := dc.waitForInactiveReplicaSets(activeOldRSs); err != nil { + return err + } + + // If we need to create a new RS, create it now + // TODO: Create a new RS without re-listing all RSs. + if newRS == nil { + newRS, oldRSs, err = dc.getAllReplicaSetsAndSyncRevision(deployment, true) + if err != nil { + return err + } + allRSs = append(oldRSs, newRS) + } + + // scale up new replica set + scaledUp, err := dc.scaleUpNewReplicaSetForRecreate(newRS, deployment) + if err != nil { + return err + } + if scaledUp { + // Update DeploymentStatus + return dc.updateDeploymentStatus(allRSs, newRS, deployment) + } + + dc.cleanupDeployment(oldRSs, deployment) + + // Sync deployment status + return dc.syncDeploymentStatus(allRSs, newRS, deployment) +} + +// scaleDownOldReplicaSetsForRecreate scales down old replica sets when deployment strategy is "Recreate" +func (dc *DeploymentController) scaleDownOldReplicaSetsForRecreate(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { + scaled := false + for _, rs := range oldRSs { + // Scaling not required. + if rs.Spec.Replicas == 0 { + continue + } + scaledRS, _, err := dc.scaleReplicaSetAndRecordEvent(rs, 0, deployment) + if err != nil { + return false, err + } + if scaledRS { + scaled = true + } + } + return scaled, nil +} + +// waitForInactiveReplicaSets will wait until all passed replica sets are inactive and have been noticed +// by the replica set controller. +func (dc *DeploymentController) waitForInactiveReplicaSets(oldRSs []*extensions.ReplicaSet) error { + for i := range oldRSs { + rs := oldRSs[i] + + condition := rsutil.ReplicaSetIsInactive(dc.client.Extensions(), rs) + if err := wait.ExponentialBackoff(unversionedclient.DefaultRetry, condition); err != nil { + return err + } + } + return nil +} + +// scaleUpNewReplicaSetForRecreate scales up new replica set when deployment strategy is "Recreate" +func (dc *DeploymentController) scaleUpNewReplicaSetForRecreate(newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { + scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) + return scaled, err +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/deployment/rollback.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/rollback.go new file mode 100644 index 000000000000..a82db34dc22a --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/rollback.go @@ -0,0 +1,105 @@ +/* +Copyright 2016 The Kubernetes 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 deployment + +import ( + "fmt" + "reflect" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/extensions" + deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" +) + +// Rolling back to a revision; no-op if the toRevision is deployment's current revision +func (dc *DeploymentController) rollback(deployment *extensions.Deployment, toRevision *int64) (*extensions.Deployment, error) { + newRS, allOldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, true) + if err != nil { + return nil, err + } + allRSs := append(allOldRSs, newRS) + // If rollback revision is 0, rollback to the last revision + if *toRevision == 0 { + if *toRevision = deploymentutil.LastRevision(allRSs); *toRevision == 0 { + // If we still can't find the last revision, gives up rollback + dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find last revision.") + // Gives up rollback + return dc.updateDeploymentAndClearRollbackTo(deployment) + } + } + for _, rs := range allRSs { + v, err := deploymentutil.Revision(rs) + if err != nil { + glog.V(4).Infof("Unable to extract revision from deployment's replica set %q: %v", rs.Name, err) + continue + } + if v == *toRevision { + glog.V(4).Infof("Found replica set %q with desired revision %d", rs.Name, v) + // rollback by copying podTemplate.Spec from the replica set, and increment revision number by 1 + // no-op if the the spec matches current deployment's podTemplate.Spec + deployment, performedRollback, err := dc.rollbackToTemplate(deployment, rs) + if performedRollback && err == nil { + dc.emitRollbackNormalEvent(deployment, fmt.Sprintf("Rolled back deployment %q to revision %d", deployment.Name, *toRevision)) + } + return deployment, err + } + } + dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackRevisionNotFound, "Unable to find the revision to rollback to.") + // Gives up rollback + return dc.updateDeploymentAndClearRollbackTo(deployment) +} + +func (dc *DeploymentController) rollbackToTemplate(deployment *extensions.Deployment, rs *extensions.ReplicaSet) (d *extensions.Deployment, performedRollback bool, err error) { + if !reflect.DeepEqual(deploymentutil.GetNewReplicaSetTemplate(deployment), rs.Spec.Template) { + glog.Infof("Rolling back deployment %s to template spec %+v", deployment.Name, rs.Spec.Template.Spec) + deploymentutil.SetFromReplicaSetTemplate(deployment, rs.Spec.Template) + // set RS (the old RS we'll rolling back to) annotations back to the deployment; + // otherwise, the deployment's current annotations (should be the same as current new RS) will be copied to the RS after the rollback. + // + // For example, + // A Deployment has old RS1 with annotation {change-cause:create}, and new RS2 {change-cause:edit}. + // Note that both annotations are copied from Deployment, and the Deployment should be annotated {change-cause:edit} as well. + // Now, rollback Deployment to RS1, we should update Deployment's pod-template and also copy annotation from RS1. + // Deployment is now annotated {change-cause:create}, and we have new RS1 {change-cause:create}, old RS2 {change-cause:edit}. + // + // If we don't copy the annotations back from RS to deployment on rollback, the Deployment will stay as {change-cause:edit}, + // and new RS1 becomes {change-cause:edit} (copied from deployment after rollback), old RS2 {change-cause:edit}, which is not correct. + deploymentutil.SetDeploymentAnnotationsTo(deployment, rs) + performedRollback = true + } else { + glog.V(4).Infof("Rolling back to a revision that contains the same template as current deployment %s, skipping rollback...", deployment.Name) + dc.emitRollbackWarningEvent(deployment, deploymentutil.RollbackTemplateUnchanged, fmt.Sprintf("The rollback revision contains the same template as current deployment %q", deployment.Name)) + } + d, err = dc.updateDeploymentAndClearRollbackTo(deployment) + return +} + +func (dc *DeploymentController) emitRollbackWarningEvent(deployment *extensions.Deployment, reason, message string) { + dc.eventRecorder.Eventf(deployment, api.EventTypeWarning, reason, message) +} + +func (dc *DeploymentController) emitRollbackNormalEvent(deployment *extensions.Deployment, message string) { + dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, deploymentutil.RollbackDone, message) +} + +// updateDeploymentAndClearRollbackTo sets .spec.rollbackTo to nil and update the input deployment +func (dc *DeploymentController) updateDeploymentAndClearRollbackTo(deployment *extensions.Deployment) (*extensions.Deployment, error) { + glog.V(4).Infof("Cleans up rollbackTo of deployment %s", deployment.Name) + deployment.Spec.RollbackTo = nil + return dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).Update(deployment) +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/deployment/rolling.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/rolling.go new file mode 100644 index 000000000000..0b5e5af8c286 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/rolling.go @@ -0,0 +1,245 @@ +/* +Copyright 2016 The Kubernetes 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 deployment + +import ( + "fmt" + "sort" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/controller" + deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" + "k8s.io/kubernetes/pkg/util/integer" +) + +// rolloutRolling implements the logic for rolling a new replica set. +func (dc *DeploymentController) rolloutRolling(deployment *extensions.Deployment) error { + newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, true) + if err != nil { + return err + } + allRSs := append(oldRSs, newRS) + + // Scale up, if we can. + scaledUp, err := dc.reconcileNewReplicaSet(allRSs, newRS, deployment) + if err != nil { + return err + } + if scaledUp { + // Update DeploymentStatus + return dc.updateDeploymentStatus(allRSs, newRS, deployment) + } + + // Scale down, if we can. + scaledDown, err := dc.reconcileOldReplicaSets(allRSs, controller.FilterActiveReplicaSets(oldRSs), newRS, deployment) + if err != nil { + return err + } + if scaledDown { + // Update DeploymentStatus + return dc.updateDeploymentStatus(allRSs, newRS, deployment) + } + + dc.cleanupDeployment(oldRSs, deployment) + + // Sync deployment status + return dc.syncDeploymentStatus(allRSs, newRS, deployment) +} + +func (dc *DeploymentController) reconcileNewReplicaSet(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { + if newRS.Spec.Replicas == deployment.Spec.Replicas { + // Scaling not required. + return false, nil + } + if newRS.Spec.Replicas > deployment.Spec.Replicas { + // Scale down. + scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, deployment.Spec.Replicas, deployment) + return scaled, err + } + newReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, newRS) + if err != nil { + return false, err + } + scaled, _, err := dc.scaleReplicaSetAndRecordEvent(newRS, newReplicasCount, deployment) + return scaled, err +} + +func (dc *DeploymentController) reconcileOldReplicaSets(allRSs []*extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (bool, error) { + oldPodsCount := deploymentutil.GetReplicaCountForReplicaSets(oldRSs) + if oldPodsCount == 0 { + // Can't scale down further + return false, nil + } + + minReadySeconds := deployment.Spec.MinReadySeconds + allPodsCount := deploymentutil.GetReplicaCountForReplicaSets(allRSs) + // TODO: use dc.getAvailablePodsForReplicaSets instead + newRSAvailablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, []*extensions.ReplicaSet{newRS}, minReadySeconds) + if err != nil { + return false, fmt.Errorf("could not find available pods: %v", err) + } + glog.V(4).Infof("New RS %s/%s has %d available pods.", newRS.Namespace, newRS.Name, newRSAvailablePodCount) + maxUnavailable := deploymentutil.MaxUnavailable(*deployment) + + // Check if we can scale down. We can scale down in the following 2 cases: + // * Some old replica sets have unhealthy replicas, we could safely scale down those unhealthy replicas since that won't further + // increase unavailability. + // * New replica set has scaled up and it's replicas becomes ready, then we can scale down old replica sets in a further step. + // + // maxScaledDown := allPodsCount - minAvailable - newReplicaSetPodsUnavailable + // take into account not only maxUnavailable and any surge pods that have been created, but also unavailable pods from + // the newRS, so that the unavailable pods from the newRS would not make us scale down old replica sets in a further + // step(that will increase unavailability). + // + // Concrete example: + // + // * 10 replicas + // * 2 maxUnavailable (absolute number, not percent) + // * 3 maxSurge (absolute number, not percent) + // + // case 1: + // * Deployment is updated, newRS is created with 3 replicas, oldRS is scaled down to 8, and newRS is scaled up to 5. + // * The new replica set pods crashloop and never become available. + // * allPodsCount is 13. minAvailable is 8. newRSPodsUnavailable is 5. + // * A node fails and causes one of the oldRS pods to become unavailable. However, 13 - 8 - 5 = 0, so the oldRS won't be scaled down. + // * The user notices the crashloop and does kubectl rollout undo to rollback. + // * newRSPodsUnavailable is 1, since we rolled back to the good replica set, so maxScaledDown = 13 - 8 - 1 = 4. 4 of the crashlooping pods will be scaled down. + // * The total number of pods will then be 9 and the newRS can be scaled up to 10. + // + // case 2: + // Same example, but pushing a new pod template instead of rolling back (aka "roll over"): + // * The new replica set created must start with 0 replicas because allPodsCount is already at 13. + // * However, newRSPodsUnavailable would also be 0, so the 2 old replica sets could be scaled down by 5 (13 - 8 - 0), which would then + // allow the new replica set to be scaled up by 5. + minAvailable := deployment.Spec.Replicas - maxUnavailable + newRSUnavailablePodCount := newRS.Spec.Replicas - newRSAvailablePodCount + maxScaledDown := allPodsCount - minAvailable - newRSUnavailablePodCount + if maxScaledDown <= 0 { + return false, nil + } + + // Clean up unhealthy replicas first, otherwise unhealthy replicas will block deployment + // and cause timeout. See https://github.com/kubernetes/kubernetes/issues/16737 + oldRSs, cleanupCount, err := dc.cleanupUnhealthyReplicas(oldRSs, deployment, deployment.Spec.MinReadySeconds, maxScaledDown) + if err != nil { + return false, nil + } + glog.V(4).Infof("Cleaned up unhealthy replicas from old RSes by %d", cleanupCount) + + // Scale down old replica sets, need check maxUnavailable to ensure we can scale down + allRSs = append(oldRSs, newRS) + scaledDownCount, err := dc.scaleDownOldReplicaSetsForRollingUpdate(allRSs, oldRSs, deployment) + if err != nil { + return false, nil + } + glog.V(4).Infof("Scaled down old RSes of deployment %s by %d", deployment.Name, scaledDownCount) + + totalScaledDown := cleanupCount + scaledDownCount + return totalScaledDown > 0, nil +} + +// cleanupUnhealthyReplicas will scale down old replica sets with unhealthy replicas, so that all unhealthy replicas will be deleted. +func (dc *DeploymentController) cleanupUnhealthyReplicas(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment, minReadySeconds, maxCleanupCount int32) ([]*extensions.ReplicaSet, int32, error) { + sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) + // Safely scale down all old replica sets with unhealthy replicas. Replica set will sort the pods in the order + // such that not-ready < ready, unscheduled < scheduled, and pending < running. This ensures that unhealthy replicas will + // been deleted first and won't increase unavailability. + totalScaledDown := int32(0) + for i, targetRS := range oldRSs { + if totalScaledDown >= maxCleanupCount { + break + } + if targetRS.Spec.Replicas == 0 { + // cannot scale down this replica set. + continue + } + // TODO: use dc.getAvailablePodsForReplicaSets instead + availablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, []*extensions.ReplicaSet{targetRS}, minReadySeconds) + if err != nil { + return nil, totalScaledDown, fmt.Errorf("could not find available pods: %v", err) + } + glog.V(4).Infof("Found %d available pods in old RS %s/%s", availablePodCount, targetRS.Namespace, targetRS.Name) + if targetRS.Spec.Replicas == availablePodCount { + // no unhealthy replicas found, no scaling required. + continue + } + + scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(targetRS.Spec.Replicas-availablePodCount))) + newReplicasCount := targetRS.Spec.Replicas - scaledDownCount + if newReplicasCount > targetRS.Spec.Replicas { + return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) + } + _, updatedOldRS, err := dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) + if err != nil { + return nil, totalScaledDown, err + } + totalScaledDown += scaledDownCount + oldRSs[i] = updatedOldRS + } + return oldRSs, totalScaledDown, nil +} + +// scaleDownOldReplicaSetsForRollingUpdate scales down old replica sets when deployment strategy is "RollingUpdate". +// Need check maxUnavailable to ensure availability +func (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(allRSs []*extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) (int32, error) { + maxUnavailable := deploymentutil.MaxUnavailable(*deployment) + + // Check if we can scale down. + minAvailable := deployment.Spec.Replicas - maxUnavailable + minReadySeconds := deployment.Spec.MinReadySeconds + // Find the number of ready pods. + // TODO: use dc.getAvailablePodsForReplicaSets instead + availablePodCount, err := deploymentutil.GetAvailablePodsForReplicaSets(dc.client, deployment, allRSs, minReadySeconds) + if err != nil { + return 0, fmt.Errorf("could not find available pods: %v", err) + } + if availablePodCount <= minAvailable { + // Cannot scale down. + return 0, nil + } + glog.V(4).Infof("Found %d available pods in deployment %s, scaling down old RSes", availablePodCount, deployment.Name) + + sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) + + totalScaledDown := int32(0) + totalScaleDownCount := availablePodCount - minAvailable + for _, targetRS := range oldRSs { + if totalScaledDown >= totalScaleDownCount { + // No further scaling required. + break + } + if targetRS.Spec.Replicas == 0 { + // cannot scale down this ReplicaSet. + continue + } + // Scale down. + scaleDownCount := int32(integer.IntMin(int(targetRS.Spec.Replicas), int(totalScaleDownCount-totalScaledDown))) + newReplicasCount := targetRS.Spec.Replicas - scaleDownCount + if newReplicasCount > targetRS.Spec.Replicas { + return 0, fmt.Errorf("when scaling down old RS, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, targetRS.Spec.Replicas, newReplicasCount) + } + _, _, err = dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment) + if err != nil { + return totalScaledDown, err + } + + totalScaledDown += scaleDownCount + } + + return totalScaledDown, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/deployment/sync.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/sync.go new file mode 100644 index 000000000000..e6c82af1b90b --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/sync.go @@ -0,0 +1,545 @@ +/* +Copyright 2016 The Kubernetes 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 deployment + +import ( + "fmt" + "reflect" + "sort" + "strconv" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/controller" + deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util" + utilerrors "k8s.io/kubernetes/pkg/util/errors" + labelsutil "k8s.io/kubernetes/pkg/util/labels" + podutil "k8s.io/kubernetes/pkg/util/pod" + rsutil "k8s.io/kubernetes/pkg/util/replicaset" +) + +// syncStatusOnly only updates Deployments Status and doesn't take any mutating actions. +func (dc *DeploymentController) syncStatusOnly(deployment *extensions.Deployment) error { + newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, false) + if err != nil { + return err + } + + allRSs := append(oldRSs, newRS) + return dc.syncDeploymentStatus(allRSs, newRS, deployment) +} + +// sync is responsible for reconciling deployments on scaling events or when they +// are paused. +func (dc *DeploymentController) sync(deployment *extensions.Deployment) error { + newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(deployment, false) + if err != nil { + return err + } + if err := dc.scale(deployment, newRS, oldRSs); err != nil { + // If we get an error while trying to scale, the deployment will be requeued + // so we can abort this resync + return err + } + dc.cleanupDeployment(oldRSs, deployment) + + allRSs := append(oldRSs, newRS) + return dc.syncDeploymentStatus(allRSs, newRS, deployment) +} + +// getAllReplicaSetsAndSyncRevision returns all the replica sets for the provided deployment (new and all old), with new RS's and deployment's revision updated. +// 1. Get all old RSes this deployment targets, and calculate the max revision number among them (maxOldV). +// 2. Get new RS this deployment targets (whose pod template matches deployment's), and update new RS's revision number to (maxOldV + 1), +// only if its revision number is smaller than (maxOldV + 1). If this step failed, we'll update it in the next deployment sync loop. +// 3. Copy new RS's revision number to deployment (update deployment's revision). If this step failed, we'll update it in the next deployment sync loop. +// Note that currently the deployment controller is using caches to avoid querying the server for reads. +// This may lead to stale reads of replica sets, thus incorrect deployment status. +func (dc *DeploymentController) getAllReplicaSetsAndSyncRevision(deployment *extensions.Deployment, createIfNotExisted bool) (*extensions.ReplicaSet, []*extensions.ReplicaSet, error) { + // List the deployment's RSes & Pods and apply pod-template-hash info to deployment's adopted RSes/Pods + rsList, podList, err := dc.rsAndPodsWithHashKeySynced(deployment) + if err != nil { + return nil, nil, fmt.Errorf("error labeling replica sets and pods with pod-template-hash: %v", err) + } + _, allOldRSs, err := deploymentutil.FindOldReplicaSets(deployment, rsList, podList) + if err != nil { + return nil, nil, err + } + + // Calculate the max revision number among all old RSes + maxOldV := deploymentutil.MaxRevision(allOldRSs) + + // Get new replica set with the updated revision number + newRS, err := dc.getNewReplicaSet(deployment, rsList, maxOldV, allOldRSs, createIfNotExisted) + if err != nil { + return nil, nil, err + } + + // Sync deployment's revision number with new replica set + if newRS != nil && newRS.Annotations != nil && len(newRS.Annotations[deploymentutil.RevisionAnnotation]) > 0 && + (deployment.Annotations == nil || deployment.Annotations[deploymentutil.RevisionAnnotation] != newRS.Annotations[deploymentutil.RevisionAnnotation]) { + if err = dc.updateDeploymentRevision(deployment, newRS.Annotations[deploymentutil.RevisionAnnotation]); err != nil { + glog.V(4).Infof("Error: %v. Unable to update deployment revision, will retry later.", err) + } + } + + return newRS, allOldRSs, nil +} + +// rsAndPodsWithHashKeySynced returns the RSes and pods the given deployment targets, with pod-template-hash information synced. +func (dc *DeploymentController) rsAndPodsWithHashKeySynced(deployment *extensions.Deployment) ([]extensions.ReplicaSet, *api.PodList, error) { + rsList, err := deploymentutil.ListReplicaSets(deployment, + func(namespace string, options api.ListOptions) ([]extensions.ReplicaSet, error) { + return dc.rsStore.ReplicaSets(namespace).List(options.LabelSelector) + }) + if err != nil { + return nil, nil, fmt.Errorf("error listing ReplicaSets: %v", err) + } + syncedRSList := []extensions.ReplicaSet{} + for _, rs := range rsList { + // Add pod-template-hash information if it's not in the RS. + // Otherwise, new RS produced by Deployment will overlap with pre-existing ones + // that aren't constrained by the pod-template-hash. + syncedRS, err := dc.addHashKeyToRSAndPods(rs) + if err != nil { + return nil, nil, err + } + syncedRSList = append(syncedRSList, *syncedRS) + } + syncedPodList, err := dc.listPods(deployment) + if err != nil { + return nil, nil, err + } + return syncedRSList, syncedPodList, nil +} + +// addHashKeyToRSAndPods adds pod-template-hash information to the given rs, if it's not already there, with the following steps: +// 1. Add hash label to the rs's pod template, and make sure the controller sees this update so that no orphaned pods will be created +// 2. Add hash label to all pods this rs owns, wait until replicaset controller reports rs.Status.FullyLabeledReplicas equal to the desired number of replicas +// 3. Add hash label to the rs's label and selector +func (dc *DeploymentController) addHashKeyToRSAndPods(rs extensions.ReplicaSet) (updatedRS *extensions.ReplicaSet, err error) { + updatedRS = &rs + // If the rs already has the new hash label in its selector, it's done syncing + if labelsutil.SelectorHasLabel(rs.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey) { + return + } + namespace := rs.Namespace + hash := rsutil.GetPodTemplateSpecHash(rs) + rsUpdated := false + // 1. Add hash template label to the rs. This ensures that any newly created pods will have the new label. + updatedRS, rsUpdated, err = rsutil.UpdateRSWithRetries(dc.client.Extensions().ReplicaSets(namespace), updatedRS, + func(updated *extensions.ReplicaSet) error { + // Precondition: the RS doesn't contain the new hash in its pod template label. + if updated.Spec.Template.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash { + return utilerrors.ErrPreconditionViolated + } + updated.Spec.Template.Labels = labelsutil.AddLabel(updated.Spec.Template.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) + return nil + }) + if err != nil { + return nil, fmt.Errorf("error updating %s %s/%s pod template label with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) + } + if !rsUpdated { + // If RS wasn't updated but didn't return error in step 1, we've hit a RS not found error. + // Return here and retry in the next sync loop. + return &rs, nil + } + // Make sure rs pod template is updated so that it won't create pods without the new label (orphaned pods). + if updatedRS.Generation > updatedRS.Status.ObservedGeneration { + if err = deploymentutil.WaitForReplicaSetUpdated(dc.client, updatedRS.Generation, namespace, updatedRS.Name); err != nil { + return nil, fmt.Errorf("error waiting for %s %s/%s generation %d observed by controller: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, updatedRS.Generation, err) + } + } + glog.V(4).Infof("Observed the update of %s %s/%s's pod template with hash %s.", rs.Kind, rs.Namespace, rs.Name, hash) + + // 2. Update all pods managed by the rs to have the new hash label, so they will be correctly adopted. + selector, err := unversioned.LabelSelectorAsSelector(updatedRS.Spec.Selector) + if err != nil { + return nil, fmt.Errorf("error in converting selector to label selector for replica set %s: %s", updatedRS.Name, err) + } + options := api.ListOptions{LabelSelector: selector} + podList, err := dc.podStore.Pods(namespace).List(options.LabelSelector) + if err != nil { + return nil, fmt.Errorf("error in getting pod list for namespace %s and list options %+v: %s", namespace, options, err) + } + allPodsLabeled := false + if allPodsLabeled, err = deploymentutil.LabelPodsWithHash(&podList, updatedRS, dc.client, namespace, hash); err != nil { + return nil, fmt.Errorf("error in adding template hash label %s to pods %+v: %s", hash, podList, err) + } + // If not all pods are labeled but didn't return error in step 2, we've hit at least one pod not found error. + // Return here and retry in the next sync loop. + if !allPodsLabeled { + return updatedRS, nil + } + + // We need to wait for the replicaset controller to observe the pods being + // labeled with pod template hash. Because previously we've called + // WaitForReplicaSetUpdated, the replicaset controller should have dropped + // FullyLabeledReplicas to 0 already, we only need to wait it to increase + // back to the number of replicas in the spec. + if err = deploymentutil.WaitForPodsHashPopulated(dc.client, updatedRS.Generation, namespace, updatedRS.Name); err != nil { + return nil, fmt.Errorf("%s %s/%s: error waiting for replicaset controller to observe pods being labeled with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) + } + + // 3. Update rs label and selector to include the new hash label + // Copy the old selector, so that we can scrub out any orphaned pods + if updatedRS, rsUpdated, err = rsutil.UpdateRSWithRetries(dc.client.Extensions().ReplicaSets(namespace), updatedRS, + func(updated *extensions.ReplicaSet) error { + // Precondition: the RS doesn't contain the new hash in its label or selector. + if updated.Labels[extensions.DefaultDeploymentUniqueLabelKey] == hash && updated.Spec.Selector.MatchLabels[extensions.DefaultDeploymentUniqueLabelKey] == hash { + return utilerrors.ErrPreconditionViolated + } + updated.Labels = labelsutil.AddLabel(updated.Labels, extensions.DefaultDeploymentUniqueLabelKey, hash) + updated.Spec.Selector = labelsutil.AddLabelToSelector(updated.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey, hash) + return nil + }); err != nil { + return nil, fmt.Errorf("error updating %s %s/%s label and selector with template hash: %v", updatedRS.Kind, updatedRS.Namespace, updatedRS.Name, err) + } + if rsUpdated { + glog.V(4).Infof("Updated %s %s/%s's selector and label with hash %s.", rs.Kind, rs.Namespace, rs.Name, hash) + } + // If the RS isn't actually updated in step 3, that's okay, we'll retry in the next sync loop since its selector isn't updated yet. + + // TODO: look for orphaned pods and label them in the background somewhere else periodically + + return updatedRS, nil +} + +func (dc *DeploymentController) listPods(deployment *extensions.Deployment) (*api.PodList, error) { + return deploymentutil.ListPods(deployment, + func(namespace string, options api.ListOptions) (*api.PodList, error) { + podList, err := dc.podStore.Pods(namespace).List(options.LabelSelector) + return &podList, err + }) +} + +// Returns a replica set that matches the intent of the given deployment. Returns nil if the new replica set doesn't exist yet. +// 1. Get existing new RS (the RS that the given deployment targets, whose pod template is the same as deployment's). +// 2. If there's existing new RS, update its revision number if it's smaller than (maxOldRevision + 1), where maxOldRevision is the max revision number among all old RSes. +// 3. If there's no existing new RS and createIfNotExisted is true, create one with appropriate revision number (maxOldRevision + 1) and replicas. +// Note that the pod-template-hash will be added to adopted RSes and pods. +func (dc *DeploymentController) getNewReplicaSet(deployment *extensions.Deployment, rsList []extensions.ReplicaSet, maxOldRevision int64, oldRSs []*extensions.ReplicaSet, createIfNotExisted bool) (*extensions.ReplicaSet, error) { + // Calculate revision number for this new replica set + newRevision := strconv.FormatInt(maxOldRevision+1, 10) + + existingNewRS, err := deploymentutil.FindNewReplicaSet(deployment, rsList) + if err != nil { + return nil, err + } else if existingNewRS != nil { + // Set existing new replica set's annotation + if deploymentutil.SetNewReplicaSetAnnotations(deployment, existingNewRS, newRevision, true) { + return dc.client.Extensions().ReplicaSets(deployment.ObjectMeta.Namespace).Update(existingNewRS) + } + return existingNewRS, nil + } + + if !createIfNotExisted { + return nil, nil + } + + // new ReplicaSet does not exist, create one. + namespace := deployment.ObjectMeta.Namespace + podTemplateSpecHash := podutil.GetPodTemplateSpecHash(deployment.Spec.Template) + newRSTemplate := deploymentutil.GetNewReplicaSetTemplate(deployment) + // Add podTemplateHash label to selector. + newRSSelector := labelsutil.CloneSelectorAndAddLabel(deployment.Spec.Selector, extensions.DefaultDeploymentUniqueLabelKey, podTemplateSpecHash) + + // Create new ReplicaSet + newRS := extensions.ReplicaSet{ + ObjectMeta: api.ObjectMeta{ + // Make the name deterministic, to ensure idempotence + Name: deployment.Name + "-" + fmt.Sprintf("%d", podTemplateSpecHash), + Namespace: namespace, + }, + Spec: extensions.ReplicaSetSpec{ + Replicas: 0, + Selector: newRSSelector, + Template: newRSTemplate, + }, + } + allRSs := append(oldRSs, &newRS) + newReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, &newRS) + if err != nil { + return nil, err + } + + newRS.Spec.Replicas = newReplicasCount + // Set new replica set's annotation + deploymentutil.SetNewReplicaSetAnnotations(deployment, &newRS, newRevision, false) + createdRS, err := dc.client.Extensions().ReplicaSets(namespace).Create(&newRS) + if err != nil { + return nil, fmt.Errorf("error creating replica set %v: %v", deployment.Name, err) + } + if newReplicasCount > 0 { + dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", "up", createdRS.Name, newReplicasCount) + } + + return createdRS, dc.updateDeploymentRevision(deployment, newRevision) +} + +func (dc *DeploymentController) updateDeploymentRevision(deployment *extensions.Deployment, revision string) error { + if deployment.Annotations == nil { + deployment.Annotations = make(map[string]string) + } + if deployment.Annotations[deploymentutil.RevisionAnnotation] != revision { + deployment.Annotations[deploymentutil.RevisionAnnotation] = revision + _, err := dc.client.Extensions().Deployments(deployment.ObjectMeta.Namespace).Update(deployment) + return err + } + return nil +} + +// scale scales proportionally in order to mitigate risk. Otherwise, scaling up can increase the size +// of the new replica set and scaling down can decrease the sizes of the old ones, both of which would +// have the effect of hastening the rollout progress, which could produce a higher proportion of unavailable +// replicas in the event of a problem with the rolled out template. Should run only on scaling events or +// when a deployment is paused and not during the normal rollout process. +func (dc *DeploymentController) scale(deployment *extensions.Deployment, newRS *extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet) error { + // If there is only one active replica set then we should scale that up to the full count of the + // deployment. If there is no active replica set, then we should scale up the newest replica set. + if activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil { + if activeOrLatest.Spec.Replicas == deployment.Spec.Replicas { + return nil + } + _, _, err := dc.scaleReplicaSetAndRecordEvent(activeOrLatest, deployment.Spec.Replicas, deployment) + return err + } + + // If the new replica set is saturated, old replica sets should be fully scaled down. + // This case handles replica set adoption during a saturated new replica set. + if deploymentutil.IsSaturated(deployment, newRS) { + for _, old := range controller.FilterActiveReplicaSets(oldRSs) { + if _, _, err := dc.scaleReplicaSetAndRecordEvent(old, 0, deployment); err != nil { + return err + } + } + return nil + } + + // There are old replica sets with pods and the new replica set is not saturated. + // We need to proportionally scale all replica sets (new and old) in case of a + // rolling deployment. + if deploymentutil.IsRollingUpdate(deployment) { + allRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS)) + allRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs) + + allowedSize := int32(0) + if deployment.Spec.Replicas > 0 { + allowedSize = deployment.Spec.Replicas + deploymentutil.MaxSurge(*deployment) + } + + // Number of additional replicas that can be either added or removed from the total + // replicas count. These replicas should be distributed proportionally to the active + // replica sets. + deploymentReplicasToAdd := allowedSize - allRSsReplicas + + // The additional replicas should be distributed proportionally amongst the active + // replica sets from the larger to the smaller in size replica set. Scaling direction + // drives what happens in case we are trying to scale replica sets of the same size. + // In such a case when scaling up, we should scale up newer replica sets first, and + // when scaling down, we should scale down older replica sets first. + scalingOperation := "up" + switch { + case deploymentReplicasToAdd > 0: + sort.Sort(controller.ReplicaSetsBySizeNewer(allRSs)) + + case deploymentReplicasToAdd < 0: + sort.Sort(controller.ReplicaSetsBySizeOlder(allRSs)) + scalingOperation = "down" + + default: /* deploymentReplicasToAdd == 0 */ + // Nothing to add. + return nil + } + + // Iterate over all active replica sets and estimate proportions for each of them. + // The absolute value of deploymentReplicasAdded should never exceed the absolute + // value of deploymentReplicasToAdd. + deploymentReplicasAdded := int32(0) + for i := range allRSs { + rs := allRSs[i] + + proportion := deploymentutil.GetProportion(rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded) + + rs.Spec.Replicas += proportion + deploymentReplicasAdded += proportion + } + + // Update all replica sets + for i := range allRSs { + rs := allRSs[i] + + // Add/remove any leftovers to the largest replica set. + if i == 0 { + leftover := deploymentReplicasToAdd - deploymentReplicasAdded + rs.Spec.Replicas += leftover + if rs.Spec.Replicas < 0 { + rs.Spec.Replicas = 0 + } + } + + if _, err := dc.scaleReplicaSet(rs, rs.Spec.Replicas, deployment, scalingOperation); err != nil { + // Return as soon as we fail, the deployment is requeued + return err + } + } + } + return nil +} + +func (dc *DeploymentController) scaleReplicaSetAndRecordEvent(rs *extensions.ReplicaSet, newScale int32, deployment *extensions.Deployment) (bool, *extensions.ReplicaSet, error) { + // No need to scale + if rs.Spec.Replicas == newScale { + return false, rs, nil + } + var scalingOperation string + if rs.Spec.Replicas < newScale { + scalingOperation = "up" + } else { + scalingOperation = "down" + } + newRS, err := dc.scaleReplicaSet(rs, newScale, deployment, scalingOperation) + return true, newRS, err +} + +func (dc *DeploymentController) scaleReplicaSet(rs *extensions.ReplicaSet, newScale int32, deployment *extensions.Deployment, scalingOperation string) (*extensions.ReplicaSet, error) { + // NOTE: This mutates the ReplicaSet passed in. Not sure if that's a good idea. + rs.Spec.Replicas = newScale + deploymentutil.SetReplicasAnnotations(rs, deployment.Spec.Replicas, deployment.Spec.Replicas+deploymentutil.MaxSurge(*deployment)) + rs, err := dc.client.Extensions().ReplicaSets(rs.ObjectMeta.Namespace).Update(rs) + if err == nil { + dc.eventRecorder.Eventf(deployment, api.EventTypeNormal, "ScalingReplicaSet", "Scaled %s replica set %s to %d", scalingOperation, rs.Name, newScale) + } + return rs, err +} + +// cleanupDeployment is responsible for cleaning up a deployment ie. retains all but the latest N old replica sets +// where N=d.Spec.RevisionHistoryLimit. Old replica sets are older versions of the podtemplate of a deployment kept +// around by default 1) for historical reasons and 2) for the ability to rollback a deployment. +func (dc *DeploymentController) cleanupDeployment(oldRSs []*extensions.ReplicaSet, deployment *extensions.Deployment) error { + if deployment.Spec.RevisionHistoryLimit == nil { + return nil + } + diff := int32(len(oldRSs)) - *deployment.Spec.RevisionHistoryLimit + if diff <= 0 { + return nil + } + + sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs)) + + var errList []error + // TODO: This should be parallelized. + for i := int32(0); i < diff; i++ { + rs := oldRSs[i] + // Avoid delete replica set with non-zero replica counts + if rs.Status.Replicas != 0 || rs.Spec.Replicas != 0 || rs.Generation > rs.Status.ObservedGeneration { + continue + } + if err := dc.client.Extensions().ReplicaSets(rs.Namespace).Delete(rs.Name, nil); err != nil && !errors.IsNotFound(err) { + glog.V(2).Infof("Failed deleting old replica set %v for deployment %v: %v", rs.Name, deployment.Name, err) + errList = append(errList, err) + } + } + + return utilerrors.NewAggregate(errList) +} + +// syncDeploymentStatus checks if the status is up-to-date and sync it if necessary +func (dc *DeploymentController) syncDeploymentStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, d *extensions.Deployment) error { + newStatus, err := dc.calculateStatus(allRSs, newRS, d) + if err != nil { + return err + } + if !reflect.DeepEqual(d.Status, newStatus) { + return dc.updateDeploymentStatus(allRSs, newRS, d) + } + return nil +} + +func (dc *DeploymentController) calculateStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) (extensions.DeploymentStatus, error) { + availableReplicas, err := dc.getAvailablePodsForReplicaSets(deployment, allRSs) + if err != nil { + return deployment.Status, fmt.Errorf("failed to count available pods: %v", err) + } + totalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs) + + return extensions.DeploymentStatus{ + // TODO: Ensure that if we start retrying status updates, we won't pick up a new Generation value. + ObservedGeneration: deployment.Generation, + Replicas: deploymentutil.GetActualReplicaCountForReplicaSets(allRSs), + UpdatedReplicas: deploymentutil.GetActualReplicaCountForReplicaSets([]*extensions.ReplicaSet{newRS}), + AvailableReplicas: availableReplicas, + UnavailableReplicas: totalReplicas - availableReplicas, + }, nil +} + +func (dc *DeploymentController) getAvailablePodsForReplicaSets(deployment *extensions.Deployment, rss []*extensions.ReplicaSet) (int32, error) { + podList, err := dc.listPods(deployment) + if err != nil { + return 0, err + } + return deploymentutil.CountAvailablePodsForReplicaSets(podList, rss, deployment.Spec.MinReadySeconds) +} + +func (dc *DeploymentController) updateDeploymentStatus(allRSs []*extensions.ReplicaSet, newRS *extensions.ReplicaSet, deployment *extensions.Deployment) error { + newStatus, err := dc.calculateStatus(allRSs, newRS, deployment) + if err != nil { + return err + } + newDeployment := deployment + newDeployment.Status = newStatus + _, err = dc.client.Extensions().Deployments(deployment.Namespace).UpdateStatus(newDeployment) + return err +} + +// isScalingEvent checks whether the provided deployment has been updated with a scaling event +// by looking at the desired-replicas annotation in the active replica sets of the deployment. +func (dc *DeploymentController) isScalingEvent(d *extensions.Deployment) (bool, error) { + newRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(d, false) + if err != nil { + return false, err + } + // If there is no new replica set matching this deployment and the deployment isn't paused + // then there is a new rollout that waits to happen + if newRS == nil && !d.Spec.Paused { + // Update all active replicas sets to the new deployment size. SetReplicasAnnotations makes + // sure that we will update only replica sets that don't have the current size of the deployment. + maxSurge := deploymentutil.MaxSurge(*d) + for _, rs := range controller.FilterActiveReplicaSets(oldRSs) { + if updated := deploymentutil.SetReplicasAnnotations(rs, d.Spec.Replicas, d.Spec.Replicas+maxSurge); updated { + if _, err := dc.client.Extensions().ReplicaSets(rs.Namespace).Update(rs); err != nil { + glog.Infof("Cannot update annotations for replica set %q: %v", rs.Name, err) + return false, err + } + } + } + return false, nil + } + allRSs := append(oldRSs, newRS) + for _, rs := range controller.FilterActiveReplicaSets(allRSs) { + desired, ok := deploymentutil.GetDesiredReplicasAnnotation(rs) + if !ok { + continue + } + if desired != d.Spec.Replicas { + return true, nil + } + } + return false, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/deployment/deployment.go b/vendor/k8s.io/kubernetes/pkg/controller/deployment/util/deployment_util.go similarity index 57% rename from vendor/k8s.io/kubernetes/pkg/util/deployment/deployment.go rename to vendor/k8s.io/kubernetes/pkg/controller/deployment/util/deployment_util.go index e75bb94004bf..7ca9611c58e0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/deployment/deployment.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/deployment/util/deployment_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,16 +14,18 @@ See the License for the specific language governing permissions and limitations under the License. */ -package deployment +package util import ( "fmt" + "sort" "strconv" "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/annotations" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" @@ -39,15 +41,269 @@ import ( ) const ( - // The revision annotation of a deployment's replica sets which records its rollout sequence + // RevisionAnnotation is the revision annotation of a deployment's replica sets which records its rollout sequence RevisionAnnotation = "deployment.kubernetes.io/revision" - - // Here are the possible rollback event reasons - RollbackRevisionNotFound = "DeploymentRollbackRevisionNotFound" + // DesiredReplicasAnnotation is the desired replicas for a deployment recorded as an annotation + // in its replica sets. Helps in separating scaling events from the rollout process and for + // determining if the new replica set for a deployment is really saturated. + DesiredReplicasAnnotation = "deployment.kubernetes.io/desired-replicas" + // MaxReplicasAnnotation is the maximum replicas a deployment can have at a given point, which + // is deployment.spec.replicas + maxSurge. Used by the underlying replica sets to estimate their + // proportions in case the deployment has surge replicas. + MaxReplicasAnnotation = "deployment.kubernetes.io/max-replicas" + + // RollbackRevisionNotFound is not found rollback event reason + RollbackRevisionNotFound = "DeploymentRollbackRevisionNotFound" + // RollbackTemplateUnchanged is the template unchanged rollback event reason RollbackTemplateUnchanged = "DeploymentRollbackTemplateUnchanged" - RollbackDone = "DeploymentRollback" + // RollbackDone is the done rollback event reason + RollbackDone = "DeploymentRollback" ) +// MaxRevision finds the highest revision in the replica sets +func MaxRevision(allRSs []*extensions.ReplicaSet) int64 { + max := int64(0) + for _, rs := range allRSs { + if v, err := Revision(rs); err != nil { + // Skip the replica sets when it failed to parse their revision information + glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) + } else if v > max { + max = v + } + } + return max +} + +// LastRevision finds the second max revision number in all replica sets (the last revision) +func LastRevision(allRSs []*extensions.ReplicaSet) int64 { + max, secMax := int64(0), int64(0) + for _, rs := range allRSs { + if v, err := Revision(rs); err != nil { + // Skip the replica sets when it failed to parse their revision information + glog.V(4).Infof("Error: %v. Couldn't parse revision for replica set %#v, deployment controller will skip it when reconciling revisions.", err, rs) + } else if v >= max { + secMax = max + max = v + } else if v > secMax { + secMax = v + } + } + return secMax +} + +// SetNewReplicaSetAnnotations sets new replica set's annotations appropriately by updating its revision and +// copying required deployment annotations to it; it returns true if replica set's annotation is changed. +func SetNewReplicaSetAnnotations(deployment *extensions.Deployment, newRS *extensions.ReplicaSet, newRevision string, exists bool) bool { + // First, copy deployment's annotations (except for apply and revision annotations) + annotationChanged := copyDeploymentAnnotationsToReplicaSet(deployment, newRS) + // Then, update replica set's revision annotation + if newRS.Annotations == nil { + newRS.Annotations = make(map[string]string) + } + // The newRS's revision should be the greatest among all RSes. Usually, its revision number is newRevision (the max revision number + // of all old RSes + 1). However, it's possible that some of the old RSes are deleted after the newRS revision being updated, and + // newRevision becomes smaller than newRS's revision. We should only update newRS revision when it's smaller than newRevision. + if newRS.Annotations[RevisionAnnotation] < newRevision { + newRS.Annotations[RevisionAnnotation] = newRevision + annotationChanged = true + glog.V(4).Infof("Updating replica set %q revision to %s", newRS.Name, newRevision) + } + if !exists && SetReplicasAnnotations(newRS, deployment.Spec.Replicas, deployment.Spec.Replicas+MaxSurge(*deployment)) { + annotationChanged = true + } + return annotationChanged +} + +var annotationsToSkip = map[string]bool{ + annotations.LastAppliedConfigAnnotation: true, + RevisionAnnotation: true, + DesiredReplicasAnnotation: true, + MaxReplicasAnnotation: true, +} + +// skipCopyAnnotation returns true if we should skip copying the annotation with the given annotation key +// TODO: How to decide which annotations should / should not be copied? +// See https://github.com/kubernetes/kubernetes/pull/20035#issuecomment-179558615 +func skipCopyAnnotation(key string) bool { + return annotationsToSkip[key] +} + +// copyDeploymentAnnotationsToReplicaSet copies deployment's annotations to replica set's annotations, +// and returns true if replica set's annotation is changed. +// Note that apply and revision annotations are not copied. +func copyDeploymentAnnotationsToReplicaSet(deployment *extensions.Deployment, rs *extensions.ReplicaSet) bool { + rsAnnotationsChanged := false + if rs.Annotations == nil { + rs.Annotations = make(map[string]string) + } + for k, v := range deployment.Annotations { + // newRS revision is updated automatically in getNewReplicaSet, and the deployment's revision number is then updated + // by copying its newRS revision number. We should not copy deployment's revision to its newRS, since the update of + // deployment revision number may fail (revision becomes stale) and the revision number in newRS is more reliable. + if skipCopyAnnotation(k) || rs.Annotations[k] == v { + continue + } + rs.Annotations[k] = v + rsAnnotationsChanged = true + } + return rsAnnotationsChanged +} + +// SetDeploymentAnnotationsTo sets deployment's annotations as given RS's annotations. +// This action should be done if and only if the deployment is rolling back to this rs. +// Note that apply and revision annotations are not changed. +func SetDeploymentAnnotationsTo(deployment *extensions.Deployment, rollbackToRS *extensions.ReplicaSet) { + deployment.Annotations = getSkippedAnnotations(deployment.Annotations) + for k, v := range rollbackToRS.Annotations { + if !skipCopyAnnotation(k) { + deployment.Annotations[k] = v + } + } +} + +func getSkippedAnnotations(annotations map[string]string) map[string]string { + skippedAnnotations := make(map[string]string) + for k, v := range annotations { + if skipCopyAnnotation(k) { + skippedAnnotations[k] = v + } + } + return skippedAnnotations +} + +// FindActiveOrLatest returns the only active or the latest replica set in case there is at most one active +// replica set. If there are more active replica sets, then we should proportionally scale them. +func FindActiveOrLatest(newRS *extensions.ReplicaSet, oldRSs []*extensions.ReplicaSet) *extensions.ReplicaSet { + if newRS == nil && len(oldRSs) == 0 { + return nil + } + + sort.Sort(sort.Reverse(controller.ReplicaSetsByCreationTimestamp(oldRSs))) + allRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS)) + + switch len(allRSs) { + case 0: + // If there is no active replica set then we should return the newest. + if newRS != nil { + return newRS + } + return oldRSs[0] + case 1: + return allRSs[0] + default: + return nil + } +} + +// GetDesiredReplicasAnnotation returns the number of desired replicas +func GetDesiredReplicasAnnotation(rs *extensions.ReplicaSet) (int32, bool) { + return getIntFromAnnotation(rs, DesiredReplicasAnnotation) +} + +func getMaxReplicasAnnotation(rs *extensions.ReplicaSet) (int32, bool) { + return getIntFromAnnotation(rs, MaxReplicasAnnotation) +} + +func getIntFromAnnotation(rs *extensions.ReplicaSet, annotationKey string) (int32, bool) { + annotationValue, ok := rs.Annotations[annotationKey] + if !ok { + return int32(0), false + } + intValue, err := strconv.Atoi(annotationValue) + if err != nil { + glog.Warningf("Cannot convert the value %q with annotation key %q for the replica set %q", + annotationValue, annotationKey, rs.Name) + return int32(0), false + } + return int32(intValue), true +} + +// SetReplicasAnnotations sets the desiredReplicas and maxReplicas into the annotations +func SetReplicasAnnotations(rs *extensions.ReplicaSet, desiredReplicas, maxReplicas int32) bool { + updated := false + if rs.Annotations == nil { + rs.Annotations = make(map[string]string) + } + desiredString := fmt.Sprintf("%d", desiredReplicas) + if hasString := rs.Annotations[DesiredReplicasAnnotation]; hasString != desiredString { + rs.Annotations[DesiredReplicasAnnotation] = desiredString + updated = true + } + maxString := fmt.Sprintf("%d", maxReplicas) + if hasString := rs.Annotations[MaxReplicasAnnotation]; hasString != maxString { + rs.Annotations[MaxReplicasAnnotation] = maxString + updated = true + } + return updated +} + +// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take. +func MaxUnavailable(deployment extensions.Deployment) int32 { + if !IsRollingUpdate(&deployment) { + return int32(0) + } + // Error caught by validation + _, maxUnavailable, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) + return maxUnavailable +} + +// MaxSurge returns the maximum surge pods a rolling deployment can take. +func MaxSurge(deployment extensions.Deployment) int32 { + if !IsRollingUpdate(&deployment) { + return int32(0) + } + // Error caught by validation + maxSurge, _, _ := ResolveFenceposts(&deployment.Spec.Strategy.RollingUpdate.MaxSurge, &deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, deployment.Spec.Replicas) + return maxSurge +} + +// GetProportion will estimate the proportion for the provided replica set using 1. the current size +// of the parent deployment, 2. the replica count that needs be added on the replica sets of the +// deployment, and 3. the total replicas added in the replica sets of the deployment so far. +func GetProportion(rs *extensions.ReplicaSet, d extensions.Deployment, deploymentReplicasToAdd, deploymentReplicasAdded int32) int32 { + if rs == nil || rs.Spec.Replicas == 0 || deploymentReplicasToAdd == 0 || deploymentReplicasToAdd == deploymentReplicasAdded { + return int32(0) + } + + rsFraction := getReplicaSetFraction(*rs, d) + allowed := deploymentReplicasToAdd - deploymentReplicasAdded + + if deploymentReplicasToAdd > 0 { + // Use the minimum between the replica set fraction and the maximum allowed replicas + // when scaling up. This way we ensure we will not scale up more than the allowed + // replicas we can add. + return integer.Int32Min(rsFraction, allowed) + } + // Use the maximum between the replica set fraction and the maximum allowed replicas + // when scaling down. This way we ensure we will not scale down more than the allowed + // replicas we can remove. + return integer.Int32Max(rsFraction, allowed) +} + +// getReplicaSetFraction estimates the fraction of replicas a replica set can have in +// 1. a scaling event during a rollout or 2. when scaling a paused deployment. +func getReplicaSetFraction(rs extensions.ReplicaSet, d extensions.Deployment) int32 { + // If we are scaling down to zero then the fraction of this replica set is its whole size (negative) + if d.Spec.Replicas == int32(0) { + return -rs.Spec.Replicas + } + + deploymentReplicas := d.Spec.Replicas + MaxSurge(d) + annotatedReplicas, ok := getMaxReplicasAnnotation(&rs) + if !ok { + // If we cannot find the annotation then fallback to the current deployment size. Note that this + // will not be an accurate proportion estimation in case other replica sets have different values + // which means that the deployment was scaled at some point but we at least will stay in limits + // due to the min-max comparisons in getProportion. + annotatedReplicas = d.Status.Replicas + } + + // We should never proportionally scale up from zero which means rs.spec.replicas and annotatedReplicas + // will never be zero here. + newRSsize := (float64(rs.Spec.Replicas * deploymentReplicas)) / float64(annotatedReplicas) + return integer.RoundToInt32(newRSsize) - rs.Spec.Replicas +} + // GetAllReplicaSets returns the old and new replica sets targeted by the given Deployment. It gets PodList and ReplicaSetList from client interface. // Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets. // The third returned value is the new replica set, and it may be nil if it doesn't exist yet. @@ -146,26 +402,17 @@ func ListPods(deployment *extensions.Deployment, getPodList podListFunc) (*api.P // (e.g. the addition of a new field will cause the hash code to change) // Note that we assume input podTemplateSpecs contain non-empty labels func equalIgnoreHash(template1, template2 api.PodTemplateSpec) (bool, error) { - // First, compare template.Labels (ignoring hash) - labels1, labels2 := template1.Labels, template2.Labels // The podTemplateSpec must have a non-empty label so that label selectors can find them. // This is checked by validation (of resources contain a podTemplateSpec). - if len(labels1) == 0 || len(labels2) == 0 { + if len(template1.Labels) == 0 || len(template2.Labels) == 0 { return false, fmt.Errorf("Unexpected empty labels found in given template") } - if len(labels1) > len(labels2) { - labels1, labels2 = labels2, labels1 - } - // We make sure len(labels2) >= len(labels1) - for k, v := range labels2 { - if labels1[k] != v && k != extensions.DefaultDeploymentUniqueLabelKey { - return false, nil - } - } - - // Then, compare the templates without comparing their labels - template1.Labels, template2.Labels = nil, nil + hash1 := template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] + hash2 := template2.Labels[extensions.DefaultDeploymentUniqueLabelKey] + // compare equality ignoring pod-template-hash + template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] = hash2 result := api.Semantic.DeepEqual(template1, template2) + template1.Labels[extensions.DefaultDeploymentUniqueLabelKey] = hash1 return result, nil } @@ -228,6 +475,7 @@ func FindOldReplicaSets(deployment *extensions.Deployment, rsList []extensions.R return requiredRSs, allRSs, nil } +// WaitForReplicaSetUpdated polls the replica set until it is updated. func WaitForReplicaSetUpdated(c clientset.Interface, desiredGeneration int64, namespace, name string) error { return wait.Poll(10*time.Millisecond, 1*time.Minute, func() (bool, error) { rs, err := c.Extensions().ReplicaSets(namespace).Get(name) @@ -238,6 +486,7 @@ func WaitForReplicaSetUpdated(c clientset.Interface, desiredGeneration int64, na }) } +// WaitForPodsHashPopulated polls the replica set until updated and fully labeled. func WaitForPodsHashPopulated(c clientset.Interface, desiredGeneration int64, namespace, name string) error { return wait.Poll(1*time.Second, 1*time.Minute, func() (bool, error) { rs, err := c.Extensions().ReplicaSets(namespace).Get(name) @@ -278,7 +527,7 @@ func LabelPodsWithHash(podList *api.PodList, rs *extensions.ReplicaSet, c client return allPodsLabeled, nil } -// Returns the desired PodTemplateSpec for the new ReplicaSet corresponding to the given ReplicaSet. +// GetNewReplicaSetTemplate returns the desired PodTemplateSpec for the new ReplicaSet corresponding to the given ReplicaSet. func GetNewReplicaSetTemplate(deployment *extensions.Deployment) api.PodTemplateSpec { // newRS will have the same template as in deployment spec, plus a unique label in some cases. newRSTemplate := api.PodTemplateSpec{ @@ -302,7 +551,7 @@ func SetFromReplicaSetTemplate(deployment *extensions.Deployment, template api.P return deployment } -// Returns the sum of Replicas of the given replica sets. +// GetReplicaCountForReplicaSets returns the sum of Replicas of the given replica sets. func GetReplicaCountForReplicaSets(replicaSets []*extensions.ReplicaSet) int32 { totalReplicaCount := int32(0) for _, rs := range replicaSets { @@ -355,14 +604,18 @@ func GetAvailablePodsForDeployment(c clientset.Interface, deployment *extensions func countAvailablePods(pods []api.Pod, minReadySeconds int32) int32 { availablePodCount := int32(0) for _, pod := range pods { - if IsPodAvailable(&pod, minReadySeconds) { + // TODO: Make the time.Now() as argument to allow unit test this. + // FIXME: avoid using time.Now + if IsPodAvailable(&pod, minReadySeconds, time.Now()) { + glog.V(4).Infof("Pod %s/%s is available.", pod.Namespace, pod.Name) availablePodCount++ } } return availablePodCount } -func IsPodAvailable(pod *api.Pod, minReadySeconds int32) bool { +// IsPodAvailable return true if the pod is available. +func IsPodAvailable(pod *api.Pod, minReadySeconds int32, now time.Time) bool { if !controller.IsPodActive(*pod) { return false } @@ -371,11 +624,12 @@ func IsPodAvailable(pod *api.Pod, minReadySeconds int32) bool { for _, c := range pod.Status.Conditions { // we only care about pod ready conditions if c.Type == api.PodReady && c.Status == api.ConditionTrue { + glog.V(4).Infof("Comparing pod %s/%s ready condition last transition time %s + minReadySeconds %d with now %s.", pod.Namespace, pod.Name, c.LastTransitionTime.String(), minReadySeconds, now.String()) // 2 cases that this ready condition is valid (passed minReadySeconds, i.e. the pod is available): // 1. minReadySeconds == 0, or // 2. LastTransitionTime (is set) + minReadySeconds (>0) < current time minReadySecondsDuration := time.Duration(minReadySeconds) * time.Second - if minReadySeconds == 0 || !c.LastTransitionTime.IsZero() && c.LastTransitionTime.Add(minReadySecondsDuration).Before(time.Now()) { + if minReadySeconds == 0 || !c.LastTransitionTime.IsZero() && c.LastTransitionTime.Add(minReadySecondsDuration).Before(now) { return true } } @@ -408,6 +662,7 @@ func Revision(rs *extensions.ReplicaSet) (int64, error) { return strconv.ParseInt(v, 10, 64) } +// IsRollingUpdate returns true if the strategy type is a rolling update. func IsRollingUpdate(deployment *extensions.Deployment) bool { return deployment.Spec.Strategy.Type == extensions.RollingUpdateDeploymentStrategyType } @@ -443,7 +698,22 @@ func NewRSNewReplicas(deployment *extensions.Deployment, allRSs []*extensions.Re } } -// Polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration. +// IsSaturated checks if the new replica set is saturated by comparing its size with its deployment size. +// Both the deployment and the replica set have to believe this replica set can own all of the desired +// replicas in the deployment and the annotation helps in achieving that. +func IsSaturated(deployment *extensions.Deployment, rs *extensions.ReplicaSet) bool { + if rs == nil { + return false + } + desiredString := rs.Annotations[DesiredReplicasAnnotation] + desired, err := strconv.Atoi(desiredString) + if err != nil { + return false + } + return rs.Spec.Replicas == deployment.Spec.Replicas && int32(desired) == deployment.Spec.Replicas +} + +// WaitForObservedDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration >= desiredGeneration. // Returns error if polling timesout. func WaitForObservedDeployment(getDeploymentFunc func() (*extensions.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error { // TODO: This should take clientset.Interface when all code is updated to use clientset. Keeping it this way allows the function to be used by callers who have client.Interface. @@ -485,3 +755,15 @@ func ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired return int32(surge), int32(unavailable), nil } + +func DeploymentDeepCopy(deployment *extensions.Deployment) (*extensions.Deployment, error) { + objCopy, err := api.Scheme.DeepCopy(deployment) + if err != nil { + return nil, err + } + copied, ok := objCopy.(*extensions.Deployment) + if !ok { + return nil, fmt.Errorf("expected Deployment, got %#v", objCopy) + } + return copied, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/doc.go index 1e310b466f5d..ded3905820ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/endpoint/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/endpoint/doc.go index c51ec65183be..2a84e5754f38 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/endpoint/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/endpoint/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/endpoint/endpoints_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/endpoint/endpoints_controller.go index 232ececb8fad..d9ed3a89b5cd 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/endpoint/endpoints_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/endpoint/endpoints_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -273,6 +273,7 @@ func (e *EndpointController) deletePod(obj interface{}) { podKey, err := keyFunc(obj) if err != nil { glog.Errorf("Couldn't get key for object %+v: %v", obj, err) + return } glog.Infof("Pod %q was deleted but we don't have a record of its final state, so it will take up to %v before it will be removed from all endpoint records.", podKey, FullServiceResyncPeriod) @@ -284,6 +285,7 @@ func (e *EndpointController) enqueueService(obj interface{}) { key, err := keyFunc(obj) if err != nil { glog.Errorf("Couldn't get key for object %+v: %v", obj, err) + return } e.queue.Add(key) diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/controller.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/controller.go index c6363952b0cf..8cbd124a3610 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/framework/controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/controller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/doc.go index ecd3cf28abe0..feceba36c996 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/framework/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source.go index 9e90e7c916e4..ee00c0586e13 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/fake_controller_source.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/core.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/core.go new file mode 100644 index 000000000000..744aaabad4c7 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/core.go @@ -0,0 +1,273 @@ +/* +Copyright 2016 The Kubernetes 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 informers + +import ( + "reflect" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/cache" + "k8s.io/kubernetes/pkg/controller/framework" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/watch" +) + +// PodInformer is type of SharedIndexInformer which watches and lists all pods. +// Interface provides constructor for informer and lister for pods +type PodInformer interface { + Informer() framework.SharedIndexInformer + Lister() *cache.StoreToPodLister +} + +type podInformer struct { + *sharedInformerFactory +} + +// Informer checks whether podInformer exists in sharedInformerFactory and if not, it creates new informer of type +// podInformer and connects it to sharedInformerFactory +func (f *podInformer) Informer() framework.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerObj := &api.Pod{} + informerType := reflect.TypeOf(informerObj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + + informer = framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return f.client.Core().Pods(api.NamespaceAll).List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return f.client.Core().Pods(api.NamespaceAll).Watch(options) + }, + }, + informerObj, + f.defaultResync, + cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, + ) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for podInformer +func (f *podInformer) Lister() *cache.StoreToPodLister { + informer := f.Informer() + return &cache.StoreToPodLister{Indexer: informer.GetIndexer()} +} + +//***************************************************************************** + +// NamespaceInformer is type of SharedIndexInformer which watches and lists all namespaces. +// Interface provides constructor for informer and lister for namsespaces +type NamespaceInformer interface { + Informer() framework.SharedIndexInformer + Lister() *cache.IndexerToNamespaceLister +} + +type namespaceInformer struct { + *sharedInformerFactory +} + +// Informer checks whether namespaceInformer exists in sharedInformerFactory and if not, it creates new informer of type +// namespaceInformer and connects it to sharedInformerFactory +func (f *namespaceInformer) Informer() framework.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + informerObj := &api.Namespace{} + informerType := reflect.TypeOf(informerObj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + informer = framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return f.client.Core().Namespaces().List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return f.client.Core().Namespaces().Watch(options) + }, + }, + informerObj, + f.defaultResync, + cache.Indexers{}, + ) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for namespaceInformer +func (f *namespaceInformer) Lister() *cache.IndexerToNamespaceLister { + informer := f.Informer() + return &cache.IndexerToNamespaceLister{Indexer: informer.GetIndexer()} +} + +//***************************************************************************** + +// NodeInformer is type of SharedIndexInformer which watches and lists all nodes. +// Interface provides constructor for informer and lister for nodes +type NodeInformer interface { + Informer() framework.SharedIndexInformer + Lister() *cache.StoreToNodeLister +} + +type nodeInformer struct { + *sharedInformerFactory +} + +// Informer checks whether nodeInformer exists in sharedInformerFactory and if not, it creates new informer of type +// nodeInformer and connects it to sharedInformerFactory +func (f *nodeInformer) Informer() framework.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerObj := &api.Node{} + informerType := reflect.TypeOf(informerObj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + + informer = framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return f.client.Core().Nodes().List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return f.client.Core().Nodes().Watch(options) + }, + }, + informerObj, + f.defaultResync, + cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, + ) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for nodeInformer +func (f *nodeInformer) Lister() *cache.StoreToNodeLister { + informer := f.Informer() + return &cache.StoreToNodeLister{Store: informer.GetStore()} +} + +//***************************************************************************** + +// PVCInformer is type of SharedIndexInformer which watches and lists all persistent volume claims. +// Interface provides constructor for informer and lister for persistent volume claims +type PVCInformer interface { + Informer() framework.SharedIndexInformer + Lister() *cache.StoreToPVCFetcher +} + +type pvcInformer struct { + *sharedInformerFactory +} + +// Informer checks whether pvcInformer exists in sharedInformerFactory and if not, it creates new informer of type +// pvcInformer and connects it to sharedInformerFactory +func (f *pvcInformer) Informer() framework.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerObj := &api.PersistentVolumeClaim{} + informerType := reflect.TypeOf(informerObj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + + informer = framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return f.client.Core().PersistentVolumeClaims(api.NamespaceAll).List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return f.client.Core().PersistentVolumeClaims(api.NamespaceAll).Watch(options) + }, + }, + informerObj, + f.defaultResync, + cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, + ) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for pvcInformer +func (f *pvcInformer) Lister() *cache.StoreToPVCFetcher { + informer := f.Informer() + return &cache.StoreToPVCFetcher{Store: informer.GetStore()} +} + +//***************************************************************************** + +// PVInformer is type of SharedIndexInformer which watches and lists all persistent volumes. +// Interface provides constructor for informer and lister for persistent volumes +type PVInformer interface { + Informer() framework.SharedIndexInformer + Lister() *cache.StoreToPVFetcher +} + +type pvInformer struct { + *sharedInformerFactory +} + +// Informer checks whether pvInformer exists in sharedInformerFactory and if not, it creates new informer of type +// pvInformer and connects it to sharedInformerFactory +func (f *pvInformer) Informer() framework.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informerObj := &api.PersistentVolume{} + informerType := reflect.TypeOf(informerObj) + informer, exists := f.informers[informerType] + if exists { + return informer + } + + informer = framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return f.client.Core().PersistentVolumes().List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return f.client.Core().PersistentVolumes().Watch(options) + }, + }, + informerObj, + f.defaultResync, + cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, + ) + f.informers[informerType] = informer + + return informer +} + +// Lister returns lister for pvInformer +func (f *pvInformer) Lister() *cache.StoreToPVFetcher { + informer := f.Informer() + return &cache.StoreToPVFetcher{Store: informer.GetStore()} +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/factory.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/factory.go index 6e432ef9cdd8..850b42af00ec 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/factory.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/informers/factory.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,6 +17,8 @@ limitations under the License. package informers import ( + "reflect" + "sync" "time" "k8s.io/kubernetes/pkg/api" @@ -27,6 +29,70 @@ import ( "k8s.io/kubernetes/pkg/watch" ) +// SharedInformerFactory provides interface which holds unique informers for pods, nodes, namespaces, persistent volume +// claims and persistent volumes +type SharedInformerFactory interface { + // Start starts informers that can start AFTER the API server and controllers have started + Start(stopCh <-chan struct{}) + + Pods() PodInformer + Nodes() NodeInformer + Namespaces() NamespaceInformer + PersistentVolumeClaims() PVCInformer + PersistentVolumes() PVInformer +} + +type sharedInformerFactory struct { + client clientset.Interface + lock sync.Mutex + defaultResync time.Duration + informers map[reflect.Type]framework.SharedIndexInformer +} + +// NewSharedInformerFactory constructs a new instance of sharedInformerFactory +func NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory { + return &sharedInformerFactory{ + client: client, + defaultResync: defaultResync, + informers: make(map[reflect.Type]framework.SharedIndexInformer), + } +} + +// Start initializes all requested informers. +func (s *sharedInformerFactory) Start(stopCh <-chan struct{}) { + s.lock.Lock() + defer s.lock.Unlock() + + for _, informer := range s.informers { + go informer.Run(stopCh) + } +} + +// Pods returns a SharedIndexInformer that lists and watches all pods +func (f *sharedInformerFactory) Pods() PodInformer { + return &podInformer{sharedInformerFactory: f} +} + +// Nodes returns a SharedIndexInformer that lists and watches all nodes +func (f *sharedInformerFactory) Nodes() NodeInformer { + return &nodeInformer{sharedInformerFactory: f} +} + +// Namespaces returns a SharedIndexInformer that lists and watches all namespaces +func (f *sharedInformerFactory) Namespaces() NamespaceInformer { + return &namespaceInformer{sharedInformerFactory: f} +} + +// PersistentVolumeClaims returns a SharedIndexInformer that lists and watches all persistent volume claims +func (f *sharedInformerFactory) PersistentVolumeClaims() PVCInformer { + return &pvcInformer{sharedInformerFactory: f} +} + +// PersistentVolumes returns a SharedIndexInformer that lists and watches all persistent volumes +func (f *sharedInformerFactory) PersistentVolumes() PVInformer { + return &pvInformer{sharedInformerFactory: f} +} + // CreateSharedPodInformer returns a SharedIndexInformer that lists and watches all pods func CreateSharedPodInformer(client clientset.Interface, resyncPeriod time.Duration) framework.SharedIndexInformer { sharedInformer := framework.NewSharedIndexInformer( @@ -118,3 +184,21 @@ func CreateSharedPVIndexInformer(client clientset.Interface, resyncPeriod time.D return sharedIndexInformer } + +// CreateSharedNamespaceIndexInformer returns a SharedIndexInformer that lists and watches namespaces +func CreateSharedNamespaceIndexInformer(client clientset.Interface, resyncPeriod time.Duration) framework.SharedIndexInformer { + sharedIndexInformer := framework.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return client.Core().Namespaces().List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return client.Core().Namespaces().Watch(options) + }, + }, + &api.Namespace{}, + resyncPeriod, + cache.Indexers{}) + + return sharedIndexInformer +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/framework/shared_informer.go b/vendor/k8s.io/kubernetes/pkg/controller/framework/shared_informer.go index c557bf97548a..87dcac6d22bb 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/framework/shared_informer.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/framework/shared_informer.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -44,6 +44,7 @@ type SharedInformer interface { GetController() ControllerInterface Run(stopCh <-chan struct{}) HasSynced() bool + LastSyncResourceVersion() string } type SharedIndexInformer interface { @@ -87,6 +88,13 @@ type sharedIndexInformer struct { started bool startedLock sync.Mutex + + // blockDeltas gives a way to stop all event distribution so that a late event handler + // can safely join the shared informer. + blockDeltas sync.Mutex + // stopCh is the channel used to stop the main Run process. We have to track it so that + // late joiners can have a proper stop + stopCh <-chan struct{} } // dummyController hides the fact that a SharedInformer is different from a dedicated one @@ -141,6 +149,7 @@ func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) { s.started = true }() + s.stopCh = stopCh s.processor.run(stopCh) s.controller.Run(stopCh) } @@ -161,6 +170,16 @@ func (s *sharedIndexInformer) HasSynced() bool { return s.controller.HasSynced() } +func (s *sharedIndexInformer) LastSyncResourceVersion() string { + s.startedLock.Lock() + defer s.startedLock.Unlock() + + if s.controller == nil { + return "" + } + return s.controller.reflector.LastSyncResourceVersion() +} + func (s *sharedIndexInformer) GetStore() cache.Store { return s.indexer } @@ -188,16 +207,38 @@ func (s *sharedIndexInformer) AddEventHandler(handler ResourceEventHandler) erro s.startedLock.Lock() defer s.startedLock.Unlock() - if s.started { - return fmt.Errorf("informer has already started") + if !s.started { + listener := newProcessListener(handler) + s.processor.listeners = append(s.processor.listeners, listener) + return nil } + // in order to safely join, we have to + // 1. stop sending add/update/delete notifications + // 2. do a list against the store + // 3. send synthetic "Add" events to the new handler + // 4. unblock + s.blockDeltas.Lock() + defer s.blockDeltas.Unlock() + listener := newProcessListener(handler) s.processor.listeners = append(s.processor.listeners, listener) + + go listener.run(s.stopCh) + go listener.pop(s.stopCh) + + items := s.indexer.List() + for i := range items { + listener.add(addNotification{newObj: items[i]}) + } + return nil } func (s *sharedIndexInformer) HandleDeltas(obj interface{}) error { + s.blockDeltas.Lock() + defer s.blockDeltas.Unlock() + // from oldest to newest for _, d := range obj.(cache.Deltas) { switch d.Type { diff --git a/vendor/k8s.io/kubernetes/pkg/controller/garbagecollector/garbagecollector.go b/vendor/k8s.io/kubernetes/pkg/controller/garbagecollector/garbagecollector.go index cbd0ba29e76e..35ea45552256 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/garbagecollector/garbagecollector.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/garbagecollector/garbagecollector.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -279,6 +279,7 @@ func (gc *GarbageCollector) removeOrphanFinalizer(owner *node) error { for _, f := range finalizers { if f == api.FinalizerOrphan { found = true + break } else { newFinalizers = append(newFinalizers, f) } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/job/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/job/doc.go index 9c569bfc08c2..281ab9ad7369 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/job/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/job/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/job/controller.go b/vendor/k8s.io/kubernetes/pkg/controller/job/jobcontroller.go similarity index 99% rename from vendor/k8s.io/kubernetes/pkg/controller/job/controller.go rename to vendor/k8s.io/kubernetes/pkg/controller/job/jobcontroller.go index 964a4ec14d6e..46156d687947 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/job/controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/job/jobcontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -374,7 +374,7 @@ func (jm *JobController) syncJob(key string) error { job.Status.Conditions = append(job.Status.Conditions, newCondition(batch.JobFailed, "DeadlineExceeded", "Job was active longer than specified deadline")) jm.recorder.Event(&job, api.EventTypeNormal, "DeadlineExceeded", "Job was active longer than specified deadline") } else { - if jobNeedsSync { + if jobNeedsSync && job.DeletionTimestamp == nil { active = jm.manageJob(activePods, succeeded, &job) } completions := succeeded diff --git a/vendor/k8s.io/kubernetes/pkg/controller/lookup_cache.go b/vendor/k8s.io/kubernetes/pkg/controller/lookup_cache.go index 0333eff38ceb..84029c5f3fa6 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/lookup_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/lookup_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/namespace/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/namespace/doc.go index fea657af5e7a..7a5556480f6b 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/namespace/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/namespace/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller.go index 0583313ab860..0c367bdfe2f1 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller_utils.go index 9971e3ee5ef0..f6ed3f33995c 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/namespace/namespace_controller_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_allocator.go b/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_allocator.go index fe1b2c74868e..2bf1ac08cdcd 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_allocator.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_allocator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_set.go b/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_set.go index 02f2a63eb2e9..c4d9aaa8900a 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_set.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/cidr_set.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/controller_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/node/controller_utils.go new file mode 100644 index 000000000000..3d4eb5aa8407 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/controller_utils.go @@ -0,0 +1,322 @@ +/* +Copyright 2016 The Kubernetes 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 node + +import ( + "fmt" + "strings" + "time" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/cache" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "k8s.io/kubernetes/pkg/client/record" + "k8s.io/kubernetes/pkg/cloudprovider" + "k8s.io/kubernetes/pkg/fields" + "k8s.io/kubernetes/pkg/kubelet/util/format" + "k8s.io/kubernetes/pkg/types" + utilruntime "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/version" + + "github.com/golang/glog" +) + +// This function is expected to get a slice of NodeReadyConditions for all Nodes in a given zone. +func ComputeZoneState(nodeReadyConditions []*api.NodeCondition) zoneState { + seenReady := false + for i := range nodeReadyConditions { + if nodeReadyConditions[i] != nil && nodeReadyConditions[i].Status == api.ConditionTrue { + seenReady = true + } + } + if seenReady { + return stateNormal + } + return stateFullSegmentation +} + +// cleanupOrphanedPods deletes pods that are bound to nodes that don't +// exist. +func cleanupOrphanedPods(pods []*api.Pod, nodeStore cache.Store, forcefulDeletePodFunc func(*api.Pod) error) { + for _, pod := range pods { + if pod.Spec.NodeName == "" { + continue + } + if _, exists, _ := nodeStore.GetByKey(pod.Spec.NodeName); exists { + continue + } + if err := forcefulDeletePodFunc(pod); err != nil { + utilruntime.HandleError(err) + } + } +} + +// deletePods will delete all pods from master running on given node, and return true +// if any pods were deleted. +func deletePods(kubeClient clientset.Interface, recorder record.EventRecorder, nodeName string, daemonStore cache.StoreToDaemonSetLister) (bool, error) { + remaining := false + selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) + options := api.ListOptions{FieldSelector: selector} + pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(options) + if err != nil { + return remaining, err + } + + if len(pods.Items) > 0 { + recordNodeEvent(recorder, nodeName, api.EventTypeNormal, "DeletingAllPods", fmt.Sprintf("Deleting all Pods from Node %v.", nodeName)) + } + + for _, pod := range pods.Items { + // Defensive check, also needed for tests. + if pod.Spec.NodeName != nodeName { + continue + } + // if the pod has already been deleted, ignore it + if pod.DeletionGracePeriodSeconds != nil { + continue + } + // if the pod is managed by a daemonset, ignore it + _, err := daemonStore.GetPodDaemonSets(&pod) + if err == nil { // No error means at least one daemonset was found + continue + } + + glog.V(2).Infof("Starting deletion of pod %v", pod.Name) + recorder.Eventf(&pod, api.EventTypeNormal, "NodeControllerEviction", "Marking for deletion Pod %s from Node %s", pod.Name, nodeName) + if err := kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil { + return false, err + } + remaining = true + } + return remaining, nil +} + +func forcefullyDeletePod(c clientset.Interface, pod *api.Pod) error { + var zero int64 + err := c.Core().Pods(pod.Namespace).Delete(pod.Name, &api.DeleteOptions{GracePeriodSeconds: &zero}) + if err == nil { + glog.V(4).Infof("forceful deletion of %s succeeded", pod.Name) + } + return err +} + +// forcefullyDeleteNode immediately deletes all pods on the node, and then +// deletes the node itself. +func forcefullyDeleteNode(kubeClient clientset.Interface, nodeName string, forcefulDeletePodFunc func(*api.Pod) error) error { + selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) + options := api.ListOptions{FieldSelector: selector} + pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(options) + if err != nil { + return fmt.Errorf("unable to list pods on node %q: %v", nodeName, err) + } + for _, pod := range pods.Items { + if pod.Spec.NodeName != nodeName { + continue + } + if err := forcefulDeletePodFunc(&pod); err != nil { + return fmt.Errorf("unable to delete pod %q on node %q: %v", pod.Name, nodeName, err) + } + } + if err := kubeClient.Core().Nodes().Delete(nodeName, nil); err != nil { + return fmt.Errorf("unable to delete node %q: %v", nodeName, err) + } + return nil +} + +// maybeDeleteTerminatingPod non-gracefully deletes pods that are terminating +// that should not be gracefully terminated. +func (nc *NodeController) maybeDeleteTerminatingPod(obj interface{}, nodeStore cache.Store, forcefulDeletePodFunc func(*api.Pod) error) { + pod, ok := obj.(*api.Pod) + if !ok { + return + } + + // consider only terminating pods + if pod.DeletionTimestamp == nil { + return + } + + // delete terminating pods that have not yet been scheduled + if len(pod.Spec.NodeName) == 0 { + utilruntime.HandleError(forcefulDeletePodFunc(pod)) + return + } + + nodeObj, found, err := nodeStore.GetByKey(pod.Spec.NodeName) + if err != nil { + // this can only happen if the Store.KeyFunc has a problem creating + // a key for the pod. If it happens once, it will happen again so + // don't bother requeuing the pod. + utilruntime.HandleError(err) + return + } + + // delete terminating pods that have been scheduled on + // nonexistent nodes + if !found { + glog.Warningf("Unable to find Node: %v, deleting all assigned Pods.", pod.Spec.NodeName) + utilruntime.HandleError(forcefulDeletePodFunc(pod)) + return + } + + // delete terminating pods that have been scheduled on + // nodes that do not support graceful termination + // TODO(mikedanese): this can be removed when we no longer + // guarantee backwards compatibility of master API to kubelets with + // versions less than 1.1.0 + node := nodeObj.(*api.Node) + v, err := version.Parse(node.Status.NodeInfo.KubeletVersion) + if err != nil { + glog.V(0).Infof("couldn't parse verions %q of minion: %v", node.Status.NodeInfo.KubeletVersion, err) + utilruntime.HandleError(forcefulDeletePodFunc(pod)) + return + } + if gracefulDeletionVersion.GT(v) { + utilruntime.HandleError(forcefulDeletePodFunc(pod)) + return + } +} + +// update ready status of all pods running on given node from master +// return true if success +func markAllPodsNotReady(kubeClient clientset.Interface, nodeName string) error { + glog.V(2).Infof("Update ready status of pods on node [%v]", nodeName) + opts := api.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, nodeName)} + pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(opts) + if err != nil { + return err + } + + errMsg := []string{} + for _, pod := range pods.Items { + // Defensive check, also needed for tests. + if pod.Spec.NodeName != nodeName { + continue + } + + for i, cond := range pod.Status.Conditions { + if cond.Type == api.PodReady { + pod.Status.Conditions[i].Status = api.ConditionFalse + glog.V(2).Infof("Updating ready status of pod %v to false", pod.Name) + _, err := kubeClient.Core().Pods(pod.Namespace).UpdateStatus(&pod) + if err != nil { + glog.Warningf("Failed to update status for pod %q: %v", format.Pod(&pod), err) + errMsg = append(errMsg, fmt.Sprintf("%v", err)) + } + break + } + } + } + if len(errMsg) == 0 { + return nil + } + return fmt.Errorf("%v", strings.Join(errMsg, "; ")) +} + +func nodeExistsInCloudProvider(cloud cloudprovider.Interface, nodeName string) (bool, error) { + instances, ok := cloud.Instances() + if !ok { + return false, fmt.Errorf("%v", ErrCloudInstance) + } + if _, err := instances.ExternalID(nodeName); err != nil { + if err == cloudprovider.InstanceNotFound { + return false, nil + } + return false, err + } + return true, nil +} + +func recordNodeEvent(recorder record.EventRecorder, nodeName, eventtype, reason, event string) { + ref := &api.ObjectReference{ + Kind: "Node", + Name: nodeName, + UID: types.UID(nodeName), + Namespace: "", + } + glog.V(2).Infof("Recording %s event message for node %s", event, nodeName) + recorder.Eventf(ref, eventtype, reason, "Node %s event: %s", nodeName, event) +} + +func recordNodeStatusChange(recorder record.EventRecorder, node *api.Node, new_status string) { + ref := &api.ObjectReference{ + Kind: "Node", + Name: node.Name, + UID: types.UID(node.Name), + Namespace: "", + } + glog.V(2).Infof("Recording status change %s event message for node %s", new_status, node.Name) + // TODO: This requires a transaction, either both node status is updated + // and event is recorded or neither should happen, see issue #6055. + recorder.Eventf(ref, api.EventTypeNormal, new_status, "Node %s status is now: %s", node.Name, new_status) +} + +// terminatePods will ensure all pods on the given node that are in terminating state are eventually +// cleaned up. Returns true if the node has no pods in terminating state, a duration that indicates how +// long before we should check again (the next deadline for a pod to complete), or an error. +func terminatePods(kubeClient clientset.Interface, recorder record.EventRecorder, nodeName string, since time.Time, maxGracePeriod time.Duration) (bool, time.Duration, error) { + // the time before we should try again + nextAttempt := time.Duration(0) + // have we deleted all pods + complete := true + + selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) + options := api.ListOptions{FieldSelector: selector} + pods, err := kubeClient.Core().Pods(api.NamespaceAll).List(options) + if err != nil { + return false, nextAttempt, err + } + + now := time.Now() + elapsed := now.Sub(since) + for _, pod := range pods.Items { + // Defensive check, also needed for tests. + if pod.Spec.NodeName != nodeName { + continue + } + // only clean terminated pods + if pod.DeletionGracePeriodSeconds == nil { + continue + } + + // the user's requested grace period + grace := time.Duration(*pod.DeletionGracePeriodSeconds) * time.Second + if grace > maxGracePeriod { + grace = maxGracePeriod + } + + // the time remaining before the pod should have been deleted + remaining := grace - elapsed + if remaining < 0 { + remaining = 0 + glog.V(2).Infof("Removing pod %v after %s grace period", pod.Name, grace) + recordNodeEvent(recorder, nodeName, api.EventTypeNormal, "TerminatingEvictedPod", fmt.Sprintf("Pod %s has exceeded the grace period for deletion after being evicted from Node %q and is being force killed", pod.Name, nodeName)) + if err := kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, api.NewDeleteOptions(0)); err != nil { + glog.Errorf("Error completing deletion of pod %s: %v", pod.Name, err) + complete = false + } + } else { + glog.V(2).Infof("Pod %v still terminating, requested grace period %s, %s remaining", pod.Name, grace, remaining) + complete = false + } + + if nextAttempt < remaining { + nextAttempt = remaining + } + } + return complete, nextAttempt, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/node/doc.go index 084754e699d3..ac61e4858653 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/nodecontroller.go b/vendor/k8s.io/kubernetes/pkg/controller/node/nodecontroller.go index 266e1ef3301d..f883aa308315 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/nodecontroller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/nodecontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import ( "errors" "fmt" "net" - "strings" "sync" "time" @@ -36,14 +35,12 @@ import ( "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/framework" "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/flowcontrol" "k8s.io/kubernetes/pkg/util/metrics" + utilnode "k8s.io/kubernetes/pkg/util/node" utilruntime "k8s.io/kubernetes/pkg/util/runtime" - "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/system" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/version" @@ -51,7 +48,8 @@ import ( ) var ( - ErrCloudInstance = errors.New("cloud provider doesn't support instances.") + ErrCloudInstance = errors.New("cloud provider doesn't support instances.") + gracefulDeletionVersion = version.MustParse("v1.1.0") ) const ( @@ -59,10 +57,20 @@ const ( nodeStatusUpdateRetry = 5 // controls how often NodeController will try to evict Pods from non-responsive Nodes. nodeEvictionPeriod = 100 * time.Millisecond + // Burst value for all eviction rate limiters + evictionRateLimiterBurst = 1 // The amount of time the nodecontroller polls on the list nodes endpoint. apiserverStartupGracePeriod = 10 * time.Minute ) +type zoneState string + +const ( + stateNormal = zoneState("Normal") + stateFullSegmentation = zoneState("FullSegmentation") + statePartialSegmentation = zoneState("PartialSegmentation") +) + type nodeStatusData struct { probeTimestamp unversioned.Time readyTransitionTimestamp unversioned.Time @@ -70,13 +78,12 @@ type nodeStatusData struct { } type NodeController struct { - allocateNodeCIDRs bool - cloud cloudprovider.Interface - clusterCIDR *net.IPNet - serviceCIDR *net.IPNet - deletingPodsRateLimiter flowcontrol.RateLimiter - knownNodeSet sets.String - kubeClient clientset.Interface + allocateNodeCIDRs bool + cloud cloudprovider.Interface + clusterCIDR *net.IPNet + serviceCIDR *net.IPNet + knownNodeSet map[string]*api.Node + kubeClient clientset.Interface // Method for easy mocking in unittest. lookupIP func(host string) ([]net.IP, error) // Value used if sync_nodes_status=False. NodeController will not proactively @@ -107,11 +114,12 @@ type NodeController struct { nodeStatusMap map[string]nodeStatusData now func() unversioned.Time // Lock to access evictor workers - evictorLock *sync.Mutex + evictorLock sync.Mutex // workers that evicts pods from unresponsive nodes. - podEvictor *RateLimitedTimedQueue - terminationEvictor *RateLimitedTimedQueue - podEvictionTimeout time.Duration + zonePodEvictor map[string]*RateLimitedTimedQueue + zoneTerminationEvictor map[string]*RateLimitedTimedQueue + evictionLimiterQPS float32 + podEvictionTimeout time.Duration // The maximum duration before a pod evicted from a node can be forcefully terminated. maximumGracePeriod time.Duration recorder record.EventRecorder @@ -129,11 +137,9 @@ type NodeController struct { forcefullyDeletePod func(*api.Pod) error nodeExistsInCloudProvider func(string) (bool, error) + computeZoneStateFunc func(nodeConditions []*api.NodeCondition) zoneState - // If in network segmentation mode NodeController won't evict Pods from unhealthy Nodes. - // It is enabled when all Nodes observed by the NodeController are NotReady and disabled - // when NC sees any healthy Node. This is a temporary fix for v1.3. - networkSegmentationMode bool + zoneStates map[string]zoneState } // NewNodeController returns a new node controller to sync instances from cloudprovider. @@ -144,8 +150,7 @@ func NewNodeController( cloud cloudprovider.Interface, kubeClient clientset.Interface, podEvictionTimeout time.Duration, - deletionEvictionLimiter flowcontrol.RateLimiter, - terminationEvictionLimiter flowcontrol.RateLimiter, + evictionLimiterQPS float32, nodeMonitorGracePeriod time.Duration, nodeStartupGracePeriod time.Duration, nodeMonitorPeriod time.Duration, @@ -176,18 +181,16 @@ func NewNodeController( glog.Fatal("NodeController: Invalid clusterCIDR, mask size of clusterCIDR must be less than nodeCIDRMaskSize.") } } - evictorLock := sync.Mutex{} nc := &NodeController{ cloud: cloud, - knownNodeSet: make(sets.String), + knownNodeSet: make(map[string]*api.Node), kubeClient: kubeClient, recorder: recorder, podEvictionTimeout: podEvictionTimeout, maximumGracePeriod: 5 * time.Minute, - evictorLock: &evictorLock, - podEvictor: NewRateLimitedTimedQueue(deletionEvictionLimiter), - terminationEvictor: NewRateLimitedTimedQueue(terminationEvictionLimiter), + zonePodEvictor: make(map[string]*RateLimitedTimedQueue), + zoneTerminationEvictor: make(map[string]*RateLimitedTimedQueue), nodeStatusMap: make(map[string]nodeStatusData), nodeMonitorGracePeriod: nodeMonitorGracePeriod, nodeMonitorPeriod: nodeMonitorPeriod, @@ -199,6 +202,9 @@ func NewNodeController( allocateNodeCIDRs: allocateNodeCIDRs, forcefullyDeletePod: func(p *api.Pod) error { return forcefullyDeletePod(kubeClient, p) }, nodeExistsInCloudProvider: func(nodeName string) (bool, error) { return nodeExistsInCloudProvider(cloud, nodeName) }, + computeZoneStateFunc: ComputeZoneState, + evictionLimiterQPS: evictionLimiterQPS, + zoneStates: make(map[string]zoneState), } nc.podStore.Indexer, nc.podController = framework.NewIndexerInformer( @@ -213,8 +219,12 @@ func NewNodeController( &api.Pod{}, controller.NoResyncPeriodFunc(), framework.ResourceEventHandlerFuncs{ - AddFunc: nc.maybeDeleteTerminatingPod, - UpdateFunc: func(_, obj interface{}) { nc.maybeDeleteTerminatingPod(obj) }, + AddFunc: func(obj interface{}) { + nc.maybeDeleteTerminatingPod(obj, nc.nodeStore.Store, nc.forcefullyDeletePod) + }, + UpdateFunc: func(_, obj interface{}) { + nc.maybeDeleteTerminatingPod(obj, nc.nodeStore.Store, nc.forcefullyDeletePod) + }, }, // We don't need to build a index for podStore here actually, but build one for consistency. // It will ensure that if people start making use of the podStore in more specific ways, @@ -353,18 +363,20 @@ func (nc *NodeController) Run(period time.Duration) { go wait.Until(func() { nc.evictorLock.Lock() defer nc.evictorLock.Unlock() - nc.podEvictor.Try(func(value TimedValue) (bool, time.Duration) { - remaining, err := nc.deletePods(value.Value) - if err != nil { - utilruntime.HandleError(fmt.Errorf("unable to evict node %q: %v", value.Value, err)) - return false, 0 - } + for k := range nc.zonePodEvictor { + nc.zonePodEvictor[k].Try(func(value TimedValue) (bool, time.Duration) { + remaining, err := deletePods(nc.kubeClient, nc.recorder, value.Value, nc.daemonSetStore) + if err != nil { + utilruntime.HandleError(fmt.Errorf("unable to evict node %q: %v", value.Value, err)) + return false, 0 + } - if remaining { - nc.terminationEvictor.Add(value.Value) - } - return true, 0 - }) + if remaining { + nc.zoneTerminationEvictor[k].Add(value.Value) + } + return true, 0 + }) + } }, nodeEvictionPeriod, wait.NeverStop) // TODO: replace with a controller that ensures pods that are terminating complete @@ -372,116 +384,38 @@ func (nc *NodeController) Run(period time.Duration) { go wait.Until(func() { nc.evictorLock.Lock() defer nc.evictorLock.Unlock() - nc.terminationEvictor.Try(func(value TimedValue) (bool, time.Duration) { - completed, remaining, err := nc.terminatePods(value.Value, value.AddedAt) - if err != nil { - utilruntime.HandleError(fmt.Errorf("unable to terminate pods on node %q: %v", value.Value, err)) - return false, 0 - } + for k := range nc.zoneTerminationEvictor { + nc.zoneTerminationEvictor[k].Try(func(value TimedValue) (bool, time.Duration) { + completed, remaining, err := terminatePods(nc.kubeClient, nc.recorder, value.Value, value.AddedAt, nc.maximumGracePeriod) + if err != nil { + utilruntime.HandleError(fmt.Errorf("unable to terminate pods on node %q: %v", value.Value, err)) + return false, 0 + } - if completed { - glog.V(2).Infof("All pods terminated on %s", value.Value) - nc.recordNodeEvent(value.Value, api.EventTypeNormal, "TerminatedAllPods", fmt.Sprintf("Terminated all Pods on Node %s.", value.Value)) - return true, 0 - } + if completed { + glog.V(2).Infof("All pods terminated on %s", value.Value) + recordNodeEvent(nc.recorder, value.Value, api.EventTypeNormal, "TerminatedAllPods", fmt.Sprintf("Terminated all Pods on Node %s.", value.Value)) + return true, 0 + } - glog.V(2).Infof("Pods terminating since %s on %q, estimated completion %s", value.AddedAt, value.Value, remaining) - // clamp very short intervals - if remaining < nodeEvictionPeriod { - remaining = nodeEvictionPeriod - } - return false, remaining - }) + glog.V(2).Infof("Pods terminating since %s on %q, estimated completion %s", value.AddedAt, value.Value, remaining) + // clamp very short intervals + if remaining < nodeEvictionPeriod { + remaining = nodeEvictionPeriod + } + return false, remaining + }) + } }, nodeEvictionPeriod, wait.NeverStop) - go wait.Until(nc.cleanupOrphanedPods, 30*time.Second, wait.NeverStop) -} - -var gracefulDeletionVersion = version.MustParse("v1.1.0") - -// maybeDeleteTerminatingPod non-gracefully deletes pods that are terminating -// that should not be gracefully terminated. -func (nc *NodeController) maybeDeleteTerminatingPod(obj interface{}) { - pod, ok := obj.(*api.Pod) - if !ok { - return - } - - // consider only terminating pods - if pod.DeletionTimestamp == nil { - return - } - - // delete terminating pods that have not yet been scheduled - if len(pod.Spec.NodeName) == 0 { - utilruntime.HandleError(nc.forcefullyDeletePod(pod)) - return - } - - nodeObj, found, err := nc.nodeStore.GetByKey(pod.Spec.NodeName) - if err != nil { - // this can only happen if the Store.KeyFunc has a problem creating - // a key for the pod. If it happens once, it will happen again so - // don't bother requeuing the pod. - utilruntime.HandleError(err) - return - } - - // delete terminating pods that have been scheduled on - // nonexistent nodes - if !found { - glog.Warningf("Unable to find Node: %v, deleting all assigned Pods.", pod.Spec.NodeName) - utilruntime.HandleError(nc.forcefullyDeletePod(pod)) - return - } - - // delete terminating pods that have been scheduled on - // nodes that do not support graceful termination - // TODO(mikedanese): this can be removed when we no longer - // guarantee backwards compatibility of master API to kubelets with - // versions less than 1.1.0 - node := nodeObj.(*api.Node) - v, err := version.Parse(node.Status.NodeInfo.KubeletVersion) - if err != nil { - glog.V(0).Infof("couldn't parse verions %q of minion: %v", node.Status.NodeInfo.KubeletVersion, err) - utilruntime.HandleError(nc.forcefullyDeletePod(pod)) - return - } - if gracefulDeletionVersion.GT(v) { - utilruntime.HandleError(nc.forcefullyDeletePod(pod)) - return - } -} - -// cleanupOrphanedPods deletes pods that are bound to nodes that don't -// exist. -func (nc *NodeController) cleanupOrphanedPods() { - pods, err := nc.podStore.List(labels.Everything()) - if err != nil { - utilruntime.HandleError(err) - return - } - - for _, pod := range pods { - if pod.Spec.NodeName == "" { - continue - } - if _, exists, _ := nc.nodeStore.Store.GetByKey(pod.Spec.NodeName); exists { - continue - } - if err := nc.forcefullyDeletePod(pod); err != nil { + go wait.Until(func() { + pods, err := nc.podStore.List(labels.Everything()) + if err != nil { utilruntime.HandleError(err) + return } - } -} - -func forcefullyDeletePod(c clientset.Interface, pod *api.Pod) error { - var zero int64 - err := c.Core().Pods(pod.Namespace).Delete(pod.Name, &api.DeleteOptions{GracePeriodSeconds: &zero}) - if err == nil { - glog.V(4).Infof("forceful deletion of %s succeeded", pod.Name) - } - return err + cleanupOrphanedPods(pods, nc.nodeStore.Store, nc.forcefullyDeletePod) + }, 30*time.Second, wait.NeverStop) } // monitorNodeStatus verifies node status are constantly updated by kubelet, and if not, @@ -492,31 +426,33 @@ func (nc *NodeController) monitorNodeStatus() error { if err != nil { return err } - for _, node := range nodes.Items { - if !nc.knownNodeSet.Has(node.Name) { - glog.V(1).Infof("NodeController observed a new Node: %#v", node) - nc.recordNodeEvent(node.Name, api.EventTypeNormal, "RegisteredNode", fmt.Sprintf("Registered Node %v in NodeController", node.Name)) - nc.cancelPodEviction(node.Name) - nc.knownNodeSet.Insert(node.Name) + added, deleted := nc.checkForNodeAddedDeleted(nodes) + for i := range added { + glog.V(1).Infof("NodeController observed a new Node: %#v", added[i].Name) + recordNodeEvent(nc.recorder, added[i].Name, api.EventTypeNormal, "RegisteredNode", fmt.Sprintf("Registered Node %v in NodeController", added[i].Name)) + nc.knownNodeSet[added[i].Name] = added[i] + // When adding new Nodes we need to check if new zone appeared, and if so add new evictor. + zone := utilnode.GetZoneKey(added[i]) + if _, found := nc.zonePodEvictor[zone]; !found { + nc.zonePodEvictor[zone] = + NewRateLimitedTimedQueue( + flowcontrol.NewTokenBucketRateLimiter(nc.evictionLimiterQPS, evictionRateLimiterBurst)) } - } - // If there's a difference between lengths of known Nodes and observed nodes - // we must have removed some Node. - if len(nc.knownNodeSet) != len(nodes.Items) { - observedSet := make(sets.String) - for _, node := range nodes.Items { - observedSet.Insert(node.Name) - } - deleted := nc.knownNodeSet.Difference(observedSet) - for nodeName := range deleted { - glog.V(1).Infof("NodeController observed a Node deletion: %v", nodeName) - nc.recordNodeEvent(nodeName, api.EventTypeNormal, "RemovingNode", fmt.Sprintf("Removing Node %v from NodeController", nodeName)) - nc.evictPods(nodeName) - nc.knownNodeSet.Delete(nodeName) + if _, found := nc.zoneTerminationEvictor[zone]; !found { + nc.zoneTerminationEvictor[zone] = NewRateLimitedTimedQueue( + flowcontrol.NewTokenBucketRateLimiter(nc.evictionLimiterQPS, evictionRateLimiterBurst)) } + nc.cancelPodEviction(added[i]) + } + + for i := range deleted { + glog.V(1).Infof("NodeController observed a Node deletion: %v", deleted[i].Name) + recordNodeEvent(nc.recorder, deleted[i].Name, api.EventTypeNormal, "RemovingNode", fmt.Sprintf("Removing Node %v from NodeController", deleted[i].Name)) + nc.evictPods(deleted[i]) + delete(nc.knownNodeSet, deleted[i].Name) } - seenReady := false + zoneToNodeConditions := map[string][]*api.NodeCondition{} for i := range nodes.Items { var gracePeriod time.Duration var observedReadyCondition api.NodeCondition @@ -539,29 +475,28 @@ func (nc *NodeController) monitorNodeStatus() error { "Skipping - no pods will be evicted.", node.Name) continue } + // We do not treat a master node as a part of the cluster for network segmentation checking. + if !system.IsMasterNode(node) { + zoneToNodeConditions[utilnode.GetZoneKey(node)] = append(zoneToNodeConditions[utilnode.GetZoneKey(node)], currentReadyCondition) + } decisionTimestamp := nc.now() - if currentReadyCondition != nil { // Check eviction timeout against decisionTimestamp if observedReadyCondition.Status == api.ConditionFalse && decisionTimestamp.After(nc.nodeStatusMap[node.Name].readyTransitionTimestamp.Add(nc.podEvictionTimeout)) { - if nc.evictPods(node.Name) { + if nc.evictPods(node) { glog.V(4).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout) } } if observedReadyCondition.Status == api.ConditionUnknown && decisionTimestamp.After(nc.nodeStatusMap[node.Name].probeTimestamp.Add(nc.podEvictionTimeout)) { - if nc.evictPods(node.Name) { + if nc.evictPods(node) { glog.V(4).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout-gracePeriod) } } if observedReadyCondition.Status == api.ConditionTrue { - // We do not treat a master node as a part of the cluster for network segmentation checking. - if !system.IsMasterNode(node) { - seenReady = true - } - if nc.cancelPodEviction(node.Name) { + if nc.cancelPodEviction(node) { glog.V(2).Infof("Node %s is ready again, cancelled pod eviction", node.Name) } } @@ -569,7 +504,7 @@ func (nc *NodeController) monitorNodeStatus() error { // Report node event. if currentReadyCondition.Status != api.ConditionTrue && observedReadyCondition.Status == api.ConditionTrue { recordNodeStatusChange(nc.recorder, node, "NodeNotReady") - if err = nc.markAllPodsNotReady(node.Name); err != nil { + if err = markAllPodsNotReady(nc.kubeClient, node.Name); err != nil { utilruntime.HandleError(fmt.Errorf("Unable to mark all pods NotReady on node %v: %v", node.Name, err)) } } @@ -584,13 +519,13 @@ func (nc *NodeController) monitorNodeStatus() error { } if !exists { glog.V(2).Infof("Deleting node (no longer present in cloud provider): %s", node.Name) - nc.recordNodeEvent(node.Name, api.EventTypeNormal, "DeletingNode", fmt.Sprintf("Deleting Node %v because it's not present according to cloud provider", node.Name)) + recordNodeEvent(nc.recorder, node.Name, api.EventTypeNormal, "DeletingNode", fmt.Sprintf("Deleting Node %v because it's not present according to cloud provider", node.Name)) go func(nodeName string) { defer utilruntime.HandleCrash() // Kubelet is not reporting and Cloud Provider says node // is gone. Delete it without worrying about grace // periods. - if err := nc.forcefullyDeleteNode(nodeName); err != nil { + if err := forcefullyDeleteNode(nc.kubeClient, nodeName, nc.forcefullyDeletePod); err != nil { glog.Errorf("Unable to forcefully delete node %q: %v", nodeName, err) } }(node.Name) @@ -600,81 +535,36 @@ func (nc *NodeController) monitorNodeStatus() error { } } - // NC don't see any Ready Node. We assume that the network is segmented and Nodes cannot connect to API server and - // update their statuses. NC enteres network segmentation mode and cancels all evictions in progress. - if !seenReady { - nc.networkSegmentationMode = true - nc.stopAllPodEvictions() - glog.V(2).Info("NodeController is entering network segmentation mode.") - } else { - if nc.networkSegmentationMode { - nc.forceUpdateAllProbeTimes() - nc.networkSegmentationMode = false - glog.V(2).Info("NodeController exited network segmentation mode.") - } - } - return nil -} - -func nodeExistsInCloudProvider(cloud cloudprovider.Interface, nodeName string) (bool, error) { - instances, ok := cloud.Instances() - if !ok { - return false, fmt.Errorf("%v", ErrCloudInstance) - } - if _, err := instances.ExternalID(nodeName); err != nil { - if err == cloudprovider.InstanceNotFound { - return false, nil - } - return false, err - } - return true, nil -} - -// forcefullyDeleteNode immediately deletes all pods on the node, and then -// deletes the node itself. -func (nc *NodeController) forcefullyDeleteNode(nodeName string) error { - selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) - options := api.ListOptions{FieldSelector: selector} - pods, err := nc.kubeClient.Core().Pods(api.NamespaceAll).List(options) - if err != nil { - return fmt.Errorf("unable to list pods on node %q: %v", nodeName, err) - } - for _, pod := range pods.Items { - if pod.Spec.NodeName != nodeName { + for k, v := range zoneToNodeConditions { + newState := nc.computeZoneStateFunc(v) + if newState == nc.zoneStates[k] { continue } - if err := nc.forcefullyDeletePod(&pod); err != nil { - return fmt.Errorf("unable to delete pod %q on node %q: %v", pod.Name, nodeName, err) + if newState == stateFullSegmentation { + glog.V(2).Infof("NodeController is entering network segmentation mode in zone %v.", k) + } else if newState == stateNormal { + glog.V(2).Infof("NodeController exited network segmentation mode in zone %v.", k) } + for i := range nodes.Items { + if utilnode.GetZoneKey(&nodes.Items[i]) == k { + if newState == stateFullSegmentation { + // When zone is fully segmented we stop the eviction all together. + nc.cancelPodEviction(&nodes.Items[i]) + } + if newState == stateNormal && nc.zoneStates[k] == stateFullSegmentation { + // When exiting segmentation mode update probe timestamps on all Nodes. + now := nc.now() + v := nc.nodeStatusMap[nodes.Items[i].Name] + v.probeTimestamp = now + v.readyTransitionTimestamp = now + nc.nodeStatusMap[nodes.Items[i].Name] = v + } + } + } + nc.zoneStates[k] = newState } - if err := nc.kubeClient.Core().Nodes().Delete(nodeName, nil); err != nil { - return fmt.Errorf("unable to delete node %q: %v", nodeName, err) - } - return nil -} - -func (nc *NodeController) recordNodeEvent(nodeName, eventtype, reason, event string) { - ref := &api.ObjectReference{ - Kind: "Node", - Name: nodeName, - UID: types.UID(nodeName), - Namespace: "", - } - glog.V(2).Infof("Recording %s event message for node %s", event, nodeName) - nc.recorder.Eventf(ref, eventtype, reason, "Node %s event: %s", nodeName, event) -} -func recordNodeStatusChange(recorder record.EventRecorder, node *api.Node, new_status string) { - ref := &api.ObjectReference{ - Kind: "Node", - Name: node.Name, - UID: types.UID(node.Name), - Namespace: "", - } - glog.V(2).Infof("Recording status change %s event message for node %s", new_status, node.Name) - // TODO: This requires a transaction, either both node status is updated - // and event is recorded or neither should happen, see issue #6055. - recorder.Eventf(ref, api.EventTypeNormal, new_status, "Node %s status is now: %s", node.Name, new_status) + return nil } // For a given node checks its conditions and tries to update it. Returns grace period to which given node @@ -842,179 +732,59 @@ func (nc *NodeController) tryUpdateNodeStatus(node *api.Node) (time.Duration, ap return gracePeriod, observedReadyCondition, currentReadyCondition, err } -// forceUpdateAllProbeTimes bumps all observed timestamps in saved nodeStatuses to now. This makes -// all eviction timer to reset. -func (nc *NodeController) forceUpdateAllProbeTimes() { - now := nc.now() - for k, v := range nc.nodeStatusMap { - v.probeTimestamp = now - v.readyTransitionTimestamp = now - nc.nodeStatusMap[k] = v +func (nc *NodeController) checkForNodeAddedDeleted(nodes *api.NodeList) (added, deleted []*api.Node) { + for i := range nodes.Items { + if _, has := nc.knownNodeSet[nodes.Items[i].Name]; !has { + added = append(added, &nodes.Items[i]) + } } -} - -// evictPods queues an eviction for the provided node name, and returns false if the node is already -// queued for eviction. -func (nc *NodeController) evictPods(nodeName string) bool { - if nc.networkSegmentationMode { - return false + // If there's a difference between lengths of known Nodes and observed nodes + // we must have removed some Node. + if len(nc.knownNodeSet)+len(added) != len(nodes.Items) { + knowSetCopy := map[string]*api.Node{} + for k, v := range nc.knownNodeSet { + knowSetCopy[k] = v + } + for i := range nodes.Items { + delete(knowSetCopy, nodes.Items[i].Name) + } + for i := range knowSetCopy { + deleted = append(deleted, knowSetCopy[i]) + } } - nc.evictorLock.Lock() - defer nc.evictorLock.Unlock() - return nc.podEvictor.Add(nodeName) + return } // cancelPodEviction removes any queued evictions, typically because the node is available again. It // returns true if an eviction was queued. -func (nc *NodeController) cancelPodEviction(nodeName string) bool { +func (nc *NodeController) cancelPodEviction(node *api.Node) bool { + zone := utilnode.GetZoneKey(node) nc.evictorLock.Lock() defer nc.evictorLock.Unlock() - wasDeleting := nc.podEvictor.Remove(nodeName) - wasTerminating := nc.terminationEvictor.Remove(nodeName) + wasDeleting := nc.zonePodEvictor[zone].Remove(node.Name) + wasTerminating := nc.zoneTerminationEvictor[zone].Remove(node.Name) if wasDeleting || wasTerminating { - glog.V(2).Infof("Cancelling pod Eviction on Node: %v", nodeName) + glog.V(2).Infof("Cancelling pod Eviction on Node: %v", node.Name) return true } return false } -// stopAllPodEvictions removes any queued evictions for all Nodes. -func (nc *NodeController) stopAllPodEvictions() { +// evictPods queues an eviction for the provided node name, and returns false if the node is already +// queued for eviction. +func (nc *NodeController) evictPods(node *api.Node) bool { nc.evictorLock.Lock() defer nc.evictorLock.Unlock() - glog.V(3).Infof("Cancelling all pod evictions.") - nc.podEvictor.Clear() - nc.terminationEvictor.Clear() -} - -// deletePods will delete all pods from master running on given node, and return true -// if any pods were deleted. -func (nc *NodeController) deletePods(nodeName string) (bool, error) { - remaining := false - selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) - options := api.ListOptions{FieldSelector: selector} - pods, err := nc.kubeClient.Core().Pods(api.NamespaceAll).List(options) - if err != nil { - return remaining, err - } - - if len(pods.Items) > 0 { - nc.recordNodeEvent(nodeName, api.EventTypeNormal, "DeletingAllPods", fmt.Sprintf("Deleting all Pods from Node %v.", nodeName)) - } - - for _, pod := range pods.Items { - // Defensive check, also needed for tests. - if pod.Spec.NodeName != nodeName { - continue - } - // if the pod has already been deleted, ignore it - if pod.DeletionGracePeriodSeconds != nil { - continue - } - // if the pod is managed by a daemonset, ignore it - _, err := nc.daemonSetStore.GetPodDaemonSets(&pod) - if err == nil { // No error means at least one daemonset was found - continue - } - - glog.V(2).Infof("Starting deletion of pod %v", pod.Name) - nc.recorder.Eventf(&pod, api.EventTypeNormal, "NodeControllerEviction", "Marking for deletion Pod %s from Node %s", pod.Name, nodeName) - if err := nc.kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil { - return false, err - } - remaining = true - } - return remaining, nil -} - -// update ready status of all pods running on given node from master -// return true if success -func (nc *NodeController) markAllPodsNotReady(nodeName string) error { - glog.V(2).Infof("Update ready status of pods on node [%v]", nodeName) - opts := api.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.PodHostField, nodeName)} - pods, err := nc.kubeClient.Core().Pods(api.NamespaceAll).List(opts) - if err != nil { - return err - } - - errMsg := []string{} - for _, pod := range pods.Items { - // Defensive check, also needed for tests. - if pod.Spec.NodeName != nodeName { - continue - } - - for i, cond := range pod.Status.Conditions { - if cond.Type == api.PodReady { - pod.Status.Conditions[i].Status = api.ConditionFalse - glog.V(2).Infof("Updating ready status of pod %v to false", pod.Name) - pod, err := nc.kubeClient.Core().Pods(pod.Namespace).UpdateStatus(&pod) - if err != nil { - glog.Warningf("Failed to update status for pod %q: %v", format.Pod(pod), err) - errMsg = append(errMsg, fmt.Sprintf("%v", err)) - } - break - } + foundHealty := false + for _, state := range nc.zoneStates { + if state != stateFullSegmentation { + foundHealty = true + break } } - if len(errMsg) == 0 { - return nil - } - return fmt.Errorf("%v", strings.Join(errMsg, "; ")) -} - -// terminatePods will ensure all pods on the given node that are in terminating state are eventually -// cleaned up. Returns true if the node has no pods in terminating state, a duration that indicates how -// long before we should check again (the next deadline for a pod to complete), or an error. -func (nc *NodeController) terminatePods(nodeName string, since time.Time) (bool, time.Duration, error) { - // the time before we should try again - nextAttempt := time.Duration(0) - // have we deleted all pods - complete := true - - selector := fields.OneTermEqualSelector(api.PodHostField, nodeName) - options := api.ListOptions{FieldSelector: selector} - pods, err := nc.kubeClient.Core().Pods(api.NamespaceAll).List(options) - if err != nil { - return false, nextAttempt, err - } - - now := time.Now() - elapsed := now.Sub(since) - for _, pod := range pods.Items { - // Defensive check, also needed for tests. - if pod.Spec.NodeName != nodeName { - continue - } - // only clean terminated pods - if pod.DeletionGracePeriodSeconds == nil { - continue - } - - // the user's requested grace period - grace := time.Duration(*pod.DeletionGracePeriodSeconds) * time.Second - if grace > nc.maximumGracePeriod { - grace = nc.maximumGracePeriod - } - - // the time remaining before the pod should have been deleted - remaining := grace - elapsed - if remaining < 0 { - remaining = 0 - glog.V(2).Infof("Removing pod %v after %s grace period", pod.Name, grace) - nc.recordNodeEvent(nodeName, api.EventTypeNormal, "TerminatingEvictedPod", fmt.Sprintf("Pod %s has exceeded the grace period for deletion after being evicted from Node %q and is being force killed", pod.Name, nodeName)) - if err := nc.kubeClient.Core().Pods(pod.Namespace).Delete(pod.Name, api.NewDeleteOptions(0)); err != nil { - glog.Errorf("Error completing deletion of pod %s: %v", pod.Name, err) - complete = false - } - } else { - glog.V(2).Infof("Pod %v still terminating, requested grace period %s, %s remaining", pod.Name, grace, remaining) - complete = false - } - - if nextAttempt < remaining { - nextAttempt = remaining - } + if !foundHealty { + return false } - return complete, nextAttempt, nil + zone := utilnode.GetZoneKey(node) + return nc.zonePodEvictor[zone].Add(node.Name) } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/rate_limited_queue.go b/vendor/k8s.io/kubernetes/pkg/controller/node/rate_limited_queue.go index a2865418fb7f..305ba129fe6d 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/rate_limited_queue.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/rate_limited_queue.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -148,8 +148,9 @@ func (q *UniqueQueue) Clear() { // RateLimitedTimedQueue is a unique item priority queue ordered by the expected next time // of execution. It is also rate limited. type RateLimitedTimedQueue struct { - queue UniqueQueue - limiter flowcontrol.RateLimiter + queue UniqueQueue + limiterLock sync.Mutex + limiter flowcontrol.RateLimiter } // Creates new queue which will use given RateLimiter to oversee execution. @@ -173,6 +174,8 @@ type ActionFunc func(TimedValue) (bool, time.Duration) // time to execute the next item in the queue. func (q *RateLimitedTimedQueue) Try(fn ActionFunc) { val, ok := q.queue.Head() + q.limiterLock.Lock() + defer q.limiterLock.Unlock() for ok { // rate limit the queue checking if !q.limiter.TryAccept() { @@ -216,3 +219,35 @@ func (q *RateLimitedTimedQueue) Remove(value string) bool { func (q *RateLimitedTimedQueue) Clear() { q.queue.Clear() } + +// SwapLimiter safely swaps current limiter for this queue with the passed one if capacities or qps's differ. +func (q *RateLimitedTimedQueue) SwapLimiter(newQPS float32) { + q.limiterLock.Lock() + defer q.limiterLock.Unlock() + if q.limiter.QPS() == newQPS { + return + } + var newLimiter flowcontrol.RateLimiter + if newQPS <= 0 { + newLimiter = flowcontrol.NewFakeNeverRateLimiter() + } else { + newLimiter = flowcontrol.NewTokenBucketRateLimiter(newQPS, evictionRateLimiterBurst) + } + // If we're currently waiting on limiter, we drain the new one - this is a good approach when Burst value is 1 + // TODO: figure out if we need to support higher Burst values and decide on the drain logic, should we keep: + // - saturation (percentage of used tokens) + // - number of used tokens + // - number of available tokens + // - something else + for q.limiter.Saturation() > newLimiter.Saturation() { + // Check if we're not using fake limiter + previousSaturation := newLimiter.Saturation() + newLimiter.TryAccept() + // It's a fake limiter + if newLimiter.Saturation() == previousSaturation { + break + } + } + q.limiter.Stop() + q.limiter = newLimiter +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/node/test_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/node/test_utils.go index 94e50c5b40b9..cd55e19163a3 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/node/test_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/node/test_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,8 @@ import ( "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" + utilnode "k8s.io/kubernetes/pkg/util/node" + "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/watch" ) @@ -186,7 +188,7 @@ func (m *FakeNodeHandler) Watch(opts api.ListOptions) (watch.Interface, error) { return nil, nil } -func (m *FakeNodeHandler) Patch(name string, pt api.PatchType, data []byte) (*api.Node, error) { +func (m *FakeNodeHandler) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (*api.Node, error) { return nil, nil } @@ -235,3 +237,13 @@ func contains(node *api.Node, nodes []*api.Node) bool { } return false } + +// Returns list of zones for all Nodes stored in FakeNodeHandler +func getZones(nodeHandler *FakeNodeHandler) []string { + nodes, _ := nodeHandler.List(api.ListOptions{}) + zones := sets.NewString() + for _, node := range nodes.Items { + zones.Insert(utilnode.GetZoneKey(&node)) + } + return zones.List() +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/fakes.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/fakes.go index 6c1c8e713f4a..a0f4b948fc5a 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/fakes.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/fakes.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/identity_mappers.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/identity_mappers.go index ae72ef2a8f9e..985d289f0c51 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/identity_mappers.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/identity_mappers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/iterator.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/iterator.go index 81df6814ccd9..e564af6660a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/iterator.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/iterator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import ( // newPCB generates a new PCB using the id string as a unique qualifier func newPCB(id string, ps *apps.PetSet) (*pcb, error) { - petPod, err := controller.GetPodFromTemplate(&ps.Spec.Template, ps) + petPod, err := controller.GetPodFromTemplate(&ps.Spec.Template, ps, nil) if err != nil { return nil, err } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet.go index aa3534c442bc..65c4816bc9c6 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -231,7 +231,9 @@ func (p *apiServerPetClient) getPVC(pvcName, pvcNamespace string) (*api.Persiste if errors.IsNotFound(err) { found = false } - if err != nil || !found { + if !found { + return nil, found, nil + } else if err != nil { return nil, found, err } return pvc, true, nil @@ -249,7 +251,8 @@ func (p *apiServerPetClient) SyncPVCs(pet *pcb) error { for i, pvc := range pet.pvcs { _, exists, err := p.getPVC(pvc.Name, pet.parent.Namespace) if !exists { - if err := p.createPVC(&pet.pvcs[i]); err != nil { + var err error + if err = p.createPVC(&pet.pvcs[i]); err != nil { errMsg += fmt.Sprintf("Failed to create %v: %v", pvc.Name, err) } p.event(pet.parent, "Create", fmt.Sprintf("pvc: %v", pvc.Name), err) diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set.go index a34eb6d5c2e6..bc03a9a452be 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set_utils.go index d6d373050dd6..21b13c166091 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/petset/pet_set_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ func (u *unhealthyPetTracker) Get(ps *apps.PetSet, knownPets []*api.Pod) (*pcb, glog.V(4).Infof("Ignoring healthy pet %v for PetSet %v", p.Name, ps.Name) continue } - glog.Infof("No recorded blocking pet, but found unhealty pet %v for PetSet %v", p.Name, ps.Name) + glog.Infof("No recorded blocking pet, but found unhealthy pet %v for PetSet %v", p.Name, ps.Name) return &pcb{pod: p, parent: ps}, nil } return nil, nil diff --git a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/doc.go index 34ce53aec78b..fbbf843b01b3 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/horizontal.go b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/horizontal.go index 2ca083ff20d1..9c6cc436b133 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/horizontal.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/horizontal.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/metrics/metrics_client.go b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/metrics/metrics_client.go index 0e6f208ee625..9319ab3086a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/metrics/metrics_client.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/podautoscaler/metrics/metrics_client.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api/v1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/util/sets" heapster "k8s.io/heapster/metrics/api/v1/types" metrics_api "k8s.io/heapster/metrics/apis/metrics/v1alpha1" @@ -172,7 +173,21 @@ func (h *HeapsterMetricsClient) getCpuUtilizationForPods(namespace string, selec } if len(metrics) != len(podNames) { - return 0, time.Time{}, fmt.Errorf("metrics obtained for %d/%d of pods", len(metrics), len(podNames)) + present := sets.NewString() + for _, m := range metrics { + present.Insert(m.Name) + } + missing := make([]string, 0) + for expected := range podNames { + if !present.Has(expected) { + missing = append(missing, expected) + } + } + hint := "" + if len(missing) > 0 { + hint = fmt.Sprintf(" (sample missing pod: %s/%s)", namespace, missing[0]) + } + return 0, time.Time{}, fmt.Errorf("metrics obtained for %d/%d of pods%s", len(metrics), len(podNames), hint) } sum := int64(0) @@ -250,7 +265,17 @@ func (h *HeapsterMetricsClient) getCustomMetricForPods(metricSpec metricDefiniti sum, count, timestamp := metricSpec.aggregator(metrics) if count != len(podNames) { - return nil, time.Time{}, fmt.Errorf("metrics obtained for %d/%d of pods", count, len(podNames)) + missing := make([]string, 0) + for i, expected := range podNames { + if len(metrics.Items) > i && len(metrics.Items[i].Metrics) == 0 { + missing = append(missing, expected) + } + } + hint := "" + if len(missing) > 0 { + hint = fmt.Sprintf(" (sample missing pod: %s/%s)", namespace, missing[0]) + } + return nil, time.Time{}, fmt.Errorf("metrics obtained for %d/%d of pods%s", count, len(podNames), hint) } return &sum, timestamp, nil diff --git a/vendor/k8s.io/kubernetes/pkg/controller/gc/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/podgc/doc.go similarity index 67% rename from vendor/k8s.io/kubernetes/pkg/controller/gc/doc.go rename to vendor/k8s.io/kubernetes/pkg/controller/podgc/doc.go index db08e7a36da7..6a23ea63141d 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/gc/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/podgc/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package gc contains a very simple pod "garbage collector" implementation, -// GCController, that runs in the controller manager. If the number of pods +// Package podgc contains a very simple pod "garbage collector" implementation, +// PodGCController, that runs in the controller manager. If the number of pods // in terminated phases (right now either Failed or Succeeded) surpasses a // configurable threshold, the controller will delete pods in terminated state -// until the system reaches the allowed threshold again. The GCController +// until the system reaches the allowed threshold again. The PodGCController // prioritizes pods to delete by sorting by creation timestamp and deleting the -// oldest objects first. The GCController will not delete non-terminated pods. -package gc +// oldest objects first. The PodGCController will not delete non-terminated +// pods. +package podgc diff --git a/vendor/k8s.io/kubernetes/pkg/controller/gc/gc_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/podgc/gc_controller.go similarity index 94% rename from vendor/k8s.io/kubernetes/pkg/controller/gc/gc_controller.go rename to vendor/k8s.io/kubernetes/pkg/controller/podgc/gc_controller.go index 485c326c177f..a2175c5addb0 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/gc/gc_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/podgc/gc_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package gc +package podgc import ( "sort" @@ -41,7 +41,7 @@ const ( gcCheckPeriod = 20 * time.Second ) -type GCController struct { +type PodGCController struct { kubeClient clientset.Interface podStore cache.StoreToPodLister podStoreSyncer *framework.Controller @@ -49,11 +49,11 @@ type GCController struct { threshold int } -func New(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, threshold int) *GCController { +func New(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, threshold int) *PodGCController { if kubeClient != nil && kubeClient.Core().GetRESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("gc_controller", kubeClient.Core().GetRESTClient().GetRateLimiter()) } - gcc := &GCController{ + gcc := &PodGCController{ kubeClient: kubeClient, threshold: threshold, deletePod: func(namespace, name string) error { @@ -85,13 +85,13 @@ func New(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFun return gcc } -func (gcc *GCController) Run(stop <-chan struct{}) { +func (gcc *PodGCController) Run(stop <-chan struct{}) { go gcc.podStoreSyncer.Run(stop) go wait.Until(gcc.gc, gcCheckPeriod, stop) <-stop } -func (gcc *GCController) gc() { +func (gcc *PodGCController) gc() { terminatedPods, _ := gcc.podStore.List(labels.Everything()) terminatedPodCount := len(terminatedPods) sort.Sort(byCreationTimestamp(terminatedPods)) diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/doc.go index 9d42796d990e..d93c793804a1 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set.go b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set.go index 6d6ddffb51b1..89c50d8c2d13 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,16 +27,20 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/client/cache" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/controller" "k8s.io/kubernetes/pkg/controller/framework" + "k8s.io/kubernetes/pkg/controller/framework/informers" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" + utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/metrics" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" @@ -62,12 +66,23 @@ const ( statusUpdateRetries = 1 ) +func getRSKind() unversioned.GroupVersionKind { + return v1beta1.SchemeGroupVersion.WithKind("ReplicaSet") +} + // ReplicaSetController is responsible for synchronizing ReplicaSet objects stored // in the system with actual running pods. type ReplicaSetController struct { kubeClient clientset.Interface podControl controller.PodControlInterface + // internalPodInformer is used to hold a personal informer. If we're using + // a normal shared informer, then the informer will be started for us. If + // we have a personal informer, we must start it ourselves. If you start + // the controller using NewReplicationManager(passing SharedInformer), this + // will be null + internalPodInformer framework.SharedIndexInformer + // A ReplicaSet is temporarily suspended after creating/deleting these many replicas. // It resumes normal action after observing the watch events for them. burstReplicas int @@ -84,7 +99,7 @@ type ReplicaSetController struct { // A store of pods, populated by the podController podStore cache.StoreToPodLister // Watches changes to all pods - podController *framework.Controller + podController framework.ControllerInterface // podStoreSynced returns true if the pod store has been synced at least once. // Added as a member to the struct to allow injection for testing. podStoreSynced func() bool @@ -93,14 +108,25 @@ type ReplicaSetController struct { // Controllers that need to be synced queue *workqueue.Type + + // garbageCollectorEnabled denotes if the garbage collector is enabled. RC + // manager behaves differently if GC is enabled. + garbageCollectorEnabled bool } // NewReplicaSetController creates a new ReplicaSetController. -func NewReplicaSetController(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicaSetController { +func NewReplicaSetController(podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int, garbageCollectorEnabled bool) *ReplicaSetController { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) + return newReplicaSetController( + eventBroadcaster.NewRecorder(api.EventSource{Component: "replicaset-controller"}), + podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) +} + +// newReplicaSetController configures a replica set controller with the specified event recorder +func newReplicaSetController(eventRecorder record.EventRecorder, podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int, garbageCollectorEnabled bool) *ReplicaSetController { if kubeClient != nil && kubeClient.Core().GetRESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("replicaset_controller", kubeClient.Core().GetRESTClient().GetRateLimiter()) } @@ -109,11 +135,12 @@ func NewReplicaSetController(kubeClient clientset.Interface, resyncPeriod contro kubeClient: kubeClient, podControl: controller.RealPodControl{ KubeClient: kubeClient, - Recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "replicaset-controller"}), + Recorder: eventRecorder, }, burstReplicas: burstReplicas, expectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()), queue: workqueue.New(), + garbageCollectorEnabled: garbageCollectorEnabled, } rsc.rsStore.Store, rsc.rsController = framework.NewInformer( @@ -129,43 +156,8 @@ func NewReplicaSetController(kubeClient clientset.Interface, resyncPeriod contro // TODO: Can we have much longer period here? FullControllerResyncPeriod, framework.ResourceEventHandlerFuncs{ - AddFunc: rsc.enqueueReplicaSet, - UpdateFunc: func(old, cur interface{}) { - oldRS := old.(*extensions.ReplicaSet) - curRS := cur.(*extensions.ReplicaSet) - - // We should invalidate the whole lookup cache if a RS's selector has been updated. - // - // Imagine that you have two RSs: - // * old RS1 - // * new RS2 - // You also have a pod that is attached to RS2 (because it doesn't match RS1 selector). - // Now imagine that you are changing RS1 selector so that it is now matching that pod, - // in such case we must invalidate the whole cache so that pod could be adopted by RS1 - // - // This makes the lookup cache less helpful, but selector update does not happen often, - // so it's not a big problem - if !reflect.DeepEqual(oldRS.Spec.Selector, curRS.Spec.Selector) { - rsc.lookupCache.InvalidateAll() - } - - // You might imagine that we only really need to enqueue the - // replica set when Spec changes, but it is safer to sync any - // time this function is triggered. That way a full informer - // resync can requeue any replica set that don't yet have pods - // but whose last attempts at creating a pod have failed (since - // we don't block on creation of pods) instead of those - // replica sets stalling indefinitely. Enqueueing every time - // does result in some spurious syncs (like when Status.Replica - // is updated and the watch notification from it retriggers - // this function), but in general extra resyncs shouldn't be - // that bad as ReplicaSets that haven't met expectations yet won't - // sync, and all the listing is done using local stores. - if oldRS.Status.Replicas != curRS.Status.Replicas { - glog.V(4).Infof("Observed updated replica count for ReplicaSet: %v, %d->%d", curRS.Name, oldRS.Status.Replicas, curRS.Status.Replicas) - } - rsc.enqueueReplicaSet(cur) - }, + AddFunc: rsc.enqueueReplicaSet, + UpdateFunc: rsc.updateRS, // This will enter the sync loop and no-op, because the replica set has been deleted from the store. // Note that deleting a replica set immediately after scaling it to 0 will not work. The recommended // way of achieving this is by performing a `stop` operation on the replica set. @@ -173,27 +165,16 @@ func NewReplicaSetController(kubeClient clientset.Interface, resyncPeriod contro }, ) - rsc.podStore.Indexer, rsc.podController = framework.NewIndexerInformer( - &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return rsc.kubeClient.Core().Pods(api.NamespaceAll).List(options) - }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return rsc.kubeClient.Core().Pods(api.NamespaceAll).Watch(options) - }, - }, - &api.Pod{}, - resyncPeriod(), - framework.ResourceEventHandlerFuncs{ - AddFunc: rsc.addPod, - // This invokes the ReplicaSet for every pod change, eg: host assignment. Though this might seem like - // overkill the most frequent pod update is status, and the associated ReplicaSet will only list from - // local storage, so it should be ok. - UpdateFunc: rsc.updatePod, - DeleteFunc: rsc.deletePod, - }, - cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, - ) + podInformer.AddEventHandler(framework.ResourceEventHandlerFuncs{ + AddFunc: rsc.addPod, + // This invokes the ReplicaSet for every pod change, eg: host assignment. Though this might seem like + // overkill the most frequent pod update is status, and the associated ReplicaSet will only list from + // local storage, so it should be ok. + UpdateFunc: rsc.updatePod, + DeleteFunc: rsc.deletePod, + }) + rsc.podStore.Indexer = podInformer.GetIndexer() + rsc.podController = podInformer.GetController() rsc.syncHandler = rsc.syncReplicaSet rsc.podStoreSynced = rsc.podController.HasSynced @@ -201,6 +182,15 @@ func NewReplicaSetController(kubeClient clientset.Interface, resyncPeriod contro return rsc } +// NewReplicationManagerFromClient creates a new ReplicationManager that runs its own informer. +func NewReplicaSetControllerFromClient(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicaSetController { + podInformer := informers.CreateSharedPodIndexInformer(kubeClient, resyncPeriod()) + garbageCollectorEnabled := false + rsc := NewReplicaSetController(podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) + rsc.internalPodInformer = podInformer + return rsc +} + // SetEventRecorder replaces the event recorder used by the ReplicaSetController // with the given recorder. Only used for testing. func (rsc *ReplicaSetController) SetEventRecorder(recorder record.EventRecorder) { @@ -217,6 +207,9 @@ func (rsc *ReplicaSetController) Run(workers int, stopCh <-chan struct{}) { for i := 0; i < workers; i++ { go wait.Until(rsc.worker, time.Second, stopCh) } + if rsc.internalPodInformer != nil { + go rsc.internalPodInformer.Run(stopCh) + } <-stopCh glog.Infof("Shutting down ReplicaSet Controller") rsc.queue.ShutDown() @@ -224,13 +217,14 @@ func (rsc *ReplicaSetController) Run(workers int, stopCh <-chan struct{}) { // getPodReplicaSet returns the replica set managing the given pod. // TODO: Surface that we are ignoring multiple replica sets for a single pod. +// TODO: use ownerReference.Controller to determine if the rs controls the pod. func (rsc *ReplicaSetController) getPodReplicaSet(pod *api.Pod) *extensions.ReplicaSet { // look up in the cache, if cached and the cache is valid, just return cached value if obj, cached := rsc.lookupCache.GetMatchingObject(pod); cached { rs, ok := obj.(*extensions.ReplicaSet) if !ok { // This should not happen - glog.Errorf("lookup cache does not retuen a ReplicaSet object") + glog.Errorf("lookup cache does not return a ReplicaSet object") return nil } if cached && rsc.isCacheValid(pod, rs) { @@ -263,6 +257,44 @@ func (rsc *ReplicaSetController) getPodReplicaSet(pod *api.Pod) *extensions.Repl return &rss[0] } +// callback when RS is updated +func (rsc *ReplicaSetController) updateRS(old, cur interface{}) { + oldRS := old.(*extensions.ReplicaSet) + curRS := cur.(*extensions.ReplicaSet) + + // We should invalidate the whole lookup cache if a RS's selector has been updated. + // + // Imagine that you have two RSs: + // * old RS1 + // * new RS2 + // You also have a pod that is attached to RS2 (because it doesn't match RS1 selector). + // Now imagine that you are changing RS1 selector so that it is now matching that pod, + // in such case we must invalidate the whole cache so that pod could be adopted by RS1 + // + // This makes the lookup cache less helpful, but selector update does not happen often, + // so it's not a big problem + if !reflect.DeepEqual(oldRS.Spec.Selector, curRS.Spec.Selector) { + rsc.lookupCache.InvalidateAll() + } + + // You might imagine that we only really need to enqueue the + // replica set when Spec changes, but it is safer to sync any + // time this function is triggered. That way a full informer + // resync can requeue any replica set that don't yet have pods + // but whose last attempts at creating a pod have failed (since + // we don't block on creation of pods) instead of those + // replica sets stalling indefinitely. Enqueueing every time + // does result in some spurious syncs (like when Status.Replica + // is updated and the watch notification from it retriggers + // this function), but in general extra resyncs shouldn't be + // that bad as ReplicaSets that haven't met expectations yet won't + // sync, and all the listing is done using local stores. + if oldRS.Status.Replicas != curRS.Status.Replicas { + glog.V(4).Infof("Observed updated replica count for ReplicaSet: %v, %d->%d", curRS.Name, oldRS.Status.Replicas, curRS.Status.Replicas) + } + rsc.enqueueReplicaSet(cur) +} + // isCacheValid check if the cache is valid func (rsc *ReplicaSetController) isCacheValid(pod *api.Pod, cachedRS *extensions.ReplicaSet) bool { _, exists, err := rsc.rsStore.Get(cachedRS) @@ -342,9 +374,7 @@ func (rsc *ReplicaSetController) updatePod(old, cur interface{}) { return } - if rs := rsc.getPodReplicaSet(curPod); rs != nil { - rsc.enqueueReplicaSet(rs) - } + // Enqueue the oldRC before the curRC to give curRC a chance to adopt the oldPod. if labelChanged { // If the old and new ReplicaSet are the same, the first one that syncs // will set expectations preventing any damage from the second. @@ -352,6 +382,10 @@ func (rsc *ReplicaSetController) updatePod(old, cur interface{}) { rsc.enqueueReplicaSet(oldRS) } } + + if curRS := rsc.getPodReplicaSet(curPod); curRS != nil { + rsc.enqueueReplicaSet(curRS) + } } // When a pod is deleted, enqueue the replica set that manages the pod and update its expectations. @@ -441,13 +475,28 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext // into a performance bottleneck. We should generate a UID for the pod // beforehand and store it via ExpectCreations. rsc.expectations.ExpectCreations(rsKey, diff) - wait := sync.WaitGroup{} - wait.Add(diff) + var wg sync.WaitGroup + wg.Add(diff) glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rs.Namespace, rs.Name, rs.Spec.Replicas, diff) for i := 0; i < diff; i++ { go func() { - defer wait.Done() - if err := rsc.podControl.CreatePods(rs.Namespace, &rs.Spec.Template, rs); err != nil { + defer wg.Done() + var err error + + if rsc.garbageCollectorEnabled { + var trueVar = true + controllerRef := &api.OwnerReference{ + APIVersion: getRSKind().GroupVersion().String(), + Kind: getRSKind().Kind, + Name: rs.Name, + UID: rs.UID, + Controller: &trueVar, + } + err = rsc.podControl.CreatePodsWithControllerRef(rs.Namespace, &rs.Spec.Template, rs, controllerRef) + } else { + err = rsc.podControl.CreatePods(rs.Namespace, &rs.Spec.Template, rs) + } + if err != nil { // Decrement the expected number of creates because the informer won't observe this pod glog.V(2).Infof("Failed creation, decrementing expectations for replica set %q/%q", rs.Namespace, rs.Name) rsc.expectations.CreationObserved(rsKey) @@ -455,7 +504,7 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext } }() } - wait.Wait() + wg.Wait() } else if diff > 0 { if diff > rsc.burstReplicas { diff = rsc.burstReplicas @@ -479,11 +528,11 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext deletedPodKeys = append(deletedPodKeys, controller.PodKey(filteredPods[i])) } rsc.expectations.ExpectDeletions(rsKey, deletedPodKeys) - wait := sync.WaitGroup{} - wait.Add(diff) + var wg sync.WaitGroup + wg.Add(diff) for i := 0; i < diff; i++ { go func(ix int) { - defer wait.Done() + defer wg.Done() if err := rsc.podControl.DeletePod(rs.Namespace, filteredPods[ix].Name, rs); err != nil { // Decrement the expected number of deletes because the informer won't observe this deletion podKey := controller.PodKey(filteredPods[ix]) @@ -493,7 +542,7 @@ func (rsc *ReplicaSetController) manageReplicas(filteredPods []*api.Pod, rs *ext } }(i) } - wait.Wait() + wg.Wait() } } @@ -542,16 +591,60 @@ func (rsc *ReplicaSetController) syncReplicaSet(key string) error { glog.Errorf("Error converting pod selector to selector: %v", err) return err } - podList, err := rsc.podStore.Pods(rs.Namespace).List(selector) - if err != nil { - glog.Errorf("Error getting pods for ReplicaSet %q: %v", key, err) - rsc.queue.Add(key) - return err + + // TODO: Do the List and Filter in a single pass, or use an index. + var filteredPods []*api.Pod + if rsc.garbageCollectorEnabled { + // list all pods to include the pods that don't match the rs`s selector + // anymore but has the stale controller ref. + podList, err := rsc.podStore.Pods(rs.Namespace).List(labels.Everything()) + if err != nil { + glog.Errorf("Error getting pods for rs %q: %v", key, err) + rsc.queue.Add(key) + return err + } + cm := controller.NewPodControllerRefManager(rsc.podControl, rs.ObjectMeta, selector, getRSKind()) + matchesAndControlled, matchesNeedsController, controlledDoesNotMatch := cm.Classify(podList.Items) + for _, pod := range matchesNeedsController { + err := cm.AdoptPod(pod) + // continue to next pod if adoption fails. + if err != nil { + // If the pod no longer exists, don't even log the error. + if !errors.IsNotFound(err) { + utilruntime.HandleError(err) + } + } else { + matchesAndControlled = append(matchesAndControlled, pod) + } + } + filteredPods = matchesAndControlled + // remove the controllerRef for the pods that no longer have matching labels + var errlist []error + for _, pod := range controlledDoesNotMatch { + err := cm.ReleasePod(pod) + if err != nil { + errlist = append(errlist, err) + } + } + if len(errlist) != 0 { + aggregate := utilerrors.NewAggregate(errlist) + // push the RS into work queue again. We need to try to free the + // pods again otherwise they will stuck with the stale + // controllerRef. + rsc.queue.Add(key) + return aggregate + } + } else { + podList, err := rsc.podStore.Pods(rs.Namespace).List(selector) + if err != nil { + glog.Errorf("Error getting pods for rs %q: %v", key, err) + rsc.queue.Add(key) + return err + } + filteredPods = controller.FilterActivePods(podList.Items) } - // TODO: Do this in a single pass, or use an index. - filteredPods := controller.FilterActivePods(podList.Items) - if rsNeedsSync { + if rsNeedsSync && rs.DeletionTimestamp == nil { rsc.manageReplicas(filteredPods, &rs) } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set_utils.go index fd8bd70626e4..9f230b7690fb 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replicaset/replica_set_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replication/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/replication/doc.go index b60e1d99c4e3..eb0f42158f1a 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replication/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replication/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller.go index 2b8406a1219e..bedb2295d50f 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,9 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/client/cache" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned" @@ -36,6 +39,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" + utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/metrics" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wait" @@ -65,6 +69,10 @@ const ( statusUpdateRetries = 1 ) +func getRCKind() unversioned.GroupVersionKind { + return v1.SchemeGroupVersion.WithKind("ReplicationController") +} + // ReplicationManager is responsible for synchronizing ReplicationController objects stored // in the system with actual running pods. // TODO: this really should be called ReplicationController. The only reason why it's a Manager @@ -105,20 +113,24 @@ type ReplicationManager struct { // Controllers that need to be synced queue *workqueue.Type + + // garbageCollectorEnabled denotes if the garbage collector is enabled. RC + // manager behaves differently if GC is enabled. + garbageCollectorEnabled bool } // NewReplicationManager creates a replication manager -func NewReplicationManager(podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicationManager { +func NewReplicationManager(podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int, garbageCollectorEnabled bool) *ReplicationManager { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(glog.Infof) eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")}) - return newReplicationManagerInternal( + return newReplicationManager( eventBroadcaster.NewRecorder(api.EventSource{Component: "replication-controller"}), - podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize) + podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) } -// newReplicationManagerInternal configures a replication manager with the specified event recorder -func newReplicationManagerInternal(eventRecorder record.EventRecorder, podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicationManager { +// newReplicationManager configures a replication manager with the specified event recorder +func newReplicationManager(eventRecorder record.EventRecorder, podInformer framework.SharedIndexInformer, kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int, garbageCollectorEnabled bool) *ReplicationManager { if kubeClient != nil && kubeClient.Core().GetRESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("replication_controller", kubeClient.Core().GetRESTClient().GetRateLimiter()) } @@ -132,6 +144,7 @@ func newReplicationManagerInternal(eventRecorder record.EventRecorder, podInform burstReplicas: burstReplicas, expectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()), queue: workqueue.New(), + garbageCollectorEnabled: garbageCollectorEnabled, } rm.rcStore.Indexer, rm.rcController = framework.NewIndexerInformer( @@ -147,43 +160,8 @@ func newReplicationManagerInternal(eventRecorder record.EventRecorder, podInform // TODO: Can we have much longer period here? FullControllerResyncPeriod, framework.ResourceEventHandlerFuncs{ - AddFunc: rm.enqueueController, - UpdateFunc: func(old, cur interface{}) { - oldRC := old.(*api.ReplicationController) - curRC := cur.(*api.ReplicationController) - - // We should invalidate the whole lookup cache if a RC's selector has been updated. - // - // Imagine that you have two RCs: - // * old RC1 - // * new RC2 - // You also have a pod that is attached to RC2 (because it doesn't match RC1 selector). - // Now imagine that you are changing RC1 selector so that it is now matching that pod, - // in such case, we must invalidate the whole cache so that pod could be adopted by RC1 - // - // This makes the lookup cache less helpful, but selector update does not happen often, - // so it's not a big problem - if !reflect.DeepEqual(oldRC.Spec.Selector, curRC.Spec.Selector) { - rm.lookupCache.InvalidateAll() - } - - // You might imagine that we only really need to enqueue the - // controller when Spec changes, but it is safer to sync any - // time this function is triggered. That way a full informer - // resync can requeue any controllers that don't yet have pods - // but whose last attempts at creating a pod have failed (since - // we don't block on creation of pods) instead of those - // controllers stalling indefinitely. Enqueueing every time - // does result in some spurious syncs (like when Status.Replica - // is updated and the watch notification from it retriggers - // this function), but in general extra resyncs shouldn't be - // that bad as rcs that haven't met expectations yet won't - // sync, and all the listing is done using local stores. - if oldRC.Status.Replicas != curRC.Status.Replicas { - glog.V(4).Infof("Observed updated replica count for rc: %v, %d->%d", curRC.Name, oldRC.Status.Replicas, curRC.Status.Replicas) - } - rm.enqueueController(cur) - }, + AddFunc: rm.enqueueController, + UpdateFunc: rm.updateRC, // This will enter the sync loop and no-op, because the controller has been deleted from the store. // Note that deleting a controller immediately after scaling it to 0 will not work. The recommended // way of achieving this is by performing a `stop` operation on the controller. @@ -212,7 +190,8 @@ func newReplicationManagerInternal(eventRecorder record.EventRecorder, podInform // NewReplicationManagerFromClientForIntegration creates a new ReplicationManager that runs its own informer. It disables event recording for use in integration tests. func NewReplicationManagerFromClientForIntegration(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicationManager { podInformer := informers.CreateSharedPodIndexInformer(kubeClient, resyncPeriod()) - rm := newReplicationManagerInternal(&record.FakeRecorder{}, podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize) + garbageCollectorEnabled := false + rm := newReplicationManager(&record.FakeRecorder{}, podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) rm.internalPodInformer = podInformer return rm } @@ -220,7 +199,8 @@ func NewReplicationManagerFromClientForIntegration(kubeClient clientset.Interfac // NewReplicationManagerFromClient creates a new ReplicationManager that runs its own informer. func NewReplicationManagerFromClient(kubeClient clientset.Interface, resyncPeriod controller.ResyncPeriodFunc, burstReplicas int, lookupCacheSize int) *ReplicationManager { podInformer := informers.CreateSharedPodIndexInformer(kubeClient, resyncPeriod()) - rm := NewReplicationManager(podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize) + garbageCollectorEnabled := false + rm := NewReplicationManager(podInformer, kubeClient, resyncPeriod, burstReplicas, lookupCacheSize, garbageCollectorEnabled) rm.internalPodInformer = podInformer return rm @@ -255,13 +235,14 @@ func (rm *ReplicationManager) Run(workers int, stopCh <-chan struct{}) { // getPodController returns the controller managing the given pod. // TODO: Surface that we are ignoring multiple controllers for a single pod. +// TODO: use ownerReference.Controller to determine if the rc controls the pod. func (rm *ReplicationManager) getPodController(pod *api.Pod) *api.ReplicationController { // look up in the cache, if cached and the cache is valid, just return cached value if obj, cached := rm.lookupCache.GetMatchingObject(pod); cached { controller, ok := obj.(*api.ReplicationController) if !ok { // This should not happen - glog.Errorf("lookup cache does not retuen a ReplicationController object") + glog.Errorf("lookup cache does not return a ReplicationController object") return nil } if cached && rm.isCacheValid(pod, controller) { @@ -320,6 +301,44 @@ func isControllerMatch(pod *api.Pod, rc *api.ReplicationController) bool { return true } +// callback when RC is updated +func (rm *ReplicationManager) updateRC(old, cur interface{}) { + oldRC := old.(*api.ReplicationController) + curRC := cur.(*api.ReplicationController) + + // We should invalidate the whole lookup cache if a RC's selector has been updated. + // + // Imagine that you have two RCs: + // * old RC1 + // * new RC2 + // You also have a pod that is attached to RC2 (because it doesn't match RC1 selector). + // Now imagine that you are changing RC1 selector so that it is now matching that pod, + // in such case, we must invalidate the whole cache so that pod could be adopted by RC1 + // + // This makes the lookup cache less helpful, but selector update does not happen often, + // so it's not a big problem + if !reflect.DeepEqual(oldRC.Spec.Selector, curRC.Spec.Selector) { + rm.lookupCache.InvalidateAll() + } + + // You might imagine that we only really need to enqueue the + // controller when Spec changes, but it is safer to sync any + // time this function is triggered. That way a full informer + // resync can requeue any controllers that don't yet have pods + // but whose last attempts at creating a pod have failed (since + // we don't block on creation of pods) instead of those + // controllers stalling indefinitely. Enqueueing every time + // does result in some spurious syncs (like when Status.Replica + // is updated and the watch notification from it retriggers + // this function), but in general extra resyncs shouldn't be + // that bad as rcs that haven't met expectations yet won't + // sync, and all the listing is done using local stores. + if oldRC.Status.Replicas != curRC.Status.Replicas { + glog.V(4).Infof("Observed updated replica count for rc: %v, %d->%d", curRC.Name, oldRC.Status.Replicas, curRC.Status.Replicas) + } + rm.enqueueController(cur) +} + // When a pod is created, enqueue the controller that manages it and update it's expectations. func (rm *ReplicationManager) addPod(obj interface{}) { pod := obj.(*api.Pod) @@ -370,10 +389,8 @@ func (rm *ReplicationManager) updatePod(old, cur interface{}) { return } - if rc := rm.getPodController(curPod); rc != nil { - rm.enqueueController(rc) - } // Only need to get the old controller if the labels changed. + // Enqueue the oldRC before the curRC to give curRC a chance to adopt the oldPod. if labelChanged { // If the old and new rc are the same, the first one that syncs // will set expectations preventing any damage from the second. @@ -381,6 +398,10 @@ func (rm *ReplicationManager) updatePod(old, cur interface{}) { rm.enqueueController(oldRC) } } + + if curRC := rm.getPodController(curPod); curRC != nil { + rm.enqueueController(curRC) + } } // When a pod is deleted, enqueue the controller that manages the pod and update its expectations. @@ -475,13 +496,27 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re // into a performance bottleneck. We should generate a UID for the pod // beforehand and store it via ExpectCreations. rm.expectations.ExpectCreations(rcKey, diff) - wait := sync.WaitGroup{} - wait.Add(diff) + var wg sync.WaitGroup + wg.Add(diff) glog.V(2).Infof("Too few %q/%q replicas, need %d, creating %d", rc.Namespace, rc.Name, rc.Spec.Replicas, diff) for i := 0; i < diff; i++ { go func() { - defer wait.Done() - if err := rm.podControl.CreatePods(rc.Namespace, rc.Spec.Template, rc); err != nil { + defer wg.Done() + var err error + if rm.garbageCollectorEnabled { + var trueVar = true + controllerRef := &api.OwnerReference{ + APIVersion: getRCKind().GroupVersion().String(), + Kind: getRCKind().Kind, + Name: rc.Name, + UID: rc.UID, + Controller: &trueVar, + } + err = rm.podControl.CreatePodsWithControllerRef(rc.Namespace, rc.Spec.Template, rc, controllerRef) + } else { + err = rm.podControl.CreatePods(rc.Namespace, rc.Spec.Template, rc) + } + if err != nil { // Decrement the expected number of creates because the informer won't observe this pod glog.V(2).Infof("Failed creation, decrementing expectations for controller %q/%q", rc.Namespace, rc.Name) rm.expectations.CreationObserved(rcKey) @@ -490,7 +525,7 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re } }() } - wait.Wait() + wg.Wait() } else if diff > 0 { if diff > rm.burstReplicas { diff = rm.burstReplicas @@ -517,11 +552,11 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re // labels on a pod/rc change in a way that the pod gets orphaned, the // rc will only wake up after the expectation has expired. rm.expectations.ExpectDeletions(rcKey, deletedPodKeys) - wait := sync.WaitGroup{} - wait.Add(diff) + var wg sync.WaitGroup + wg.Add(diff) for i := 0; i < diff; i++ { go func(ix int) { - defer wait.Done() + defer wg.Done() if err := rm.podControl.DeletePod(rc.Namespace, filteredPods[ix].Name, rc); err != nil { // Decrement the expected number of deletes because the informer won't observe this deletion podKey := controller.PodKey(filteredPods[ix]) @@ -532,7 +567,7 @@ func (rm *ReplicationManager) manageReplicas(filteredPods []*api.Pod, rc *api.Re } }(i) } - wait.Wait() + wg.Wait() } } @@ -580,17 +615,60 @@ func (rm *ReplicationManager) syncReplicationController(key string) error { trace.Step("ReplicationController restored") rcNeedsSync := rm.expectations.SatisfiedExpectations(rcKey) trace.Step("Expectations restored") - podList, err := rm.podStore.Pods(rc.Namespace).List(labels.Set(rc.Spec.Selector).AsSelector()) - if err != nil { - glog.Errorf("Error getting pods for rc %q: %v", key, err) - rm.queue.Add(key) - return err + + // TODO: Do the List and Filter in a single pass, or use an index. + var filteredPods []*api.Pod + if rm.garbageCollectorEnabled { + // list all pods to include the pods that don't match the rc's selector + // anymore but has the stale controller ref. + podList, err := rm.podStore.Pods(rc.Namespace).List(labels.Everything()) + if err != nil { + glog.Errorf("Error getting pods for rc %q: %v", key, err) + rm.queue.Add(key) + return err + } + cm := controller.NewPodControllerRefManager(rm.podControl, rc.ObjectMeta, labels.Set(rc.Spec.Selector).AsSelector(), getRCKind()) + matchesAndControlled, matchesNeedsController, controlledDoesNotMatch := cm.Classify(podList.Items) + for _, pod := range matchesNeedsController { + err := cm.AdoptPod(pod) + // continue to next pod if adoption fails. + if err != nil { + // If the pod no longer exists, don't even log the error. + if !errors.IsNotFound(err) { + utilruntime.HandleError(err) + } + } else { + matchesAndControlled = append(matchesAndControlled, pod) + } + } + filteredPods = matchesAndControlled + // remove the controllerRef for the pods that no longer have matching labels + var errlist []error + for _, pod := range controlledDoesNotMatch { + err := cm.ReleasePod(pod) + if err != nil { + errlist = append(errlist, err) + } + } + if len(errlist) != 0 { + aggregate := utilerrors.NewAggregate(errlist) + // push the RC into work queue again. We need to try to free the + // pods again otherwise they will stuck with the stale + // controllerRef. + rm.queue.Add(key) + return aggregate + } + } else { + podList, err := rm.podStore.Pods(rc.Namespace).List(labels.Set(rc.Spec.Selector).AsSelector()) + if err != nil { + glog.Errorf("Error getting pods for rc %q: %v", key, err) + rm.queue.Add(key) + return err + } + filteredPods = controller.FilterActivePods(podList.Items) } - trace.Step("Pods listed") - // TODO: Do this in a single pass, or use an index. - filteredPods := controller.FilterActivePods(podList.Items) - if rcNeedsSync { + if rcNeedsSync && rc.DeletionTimestamp == nil { rm.manageReplicas(filteredPods, &rc) } trace.Step("manageReplicas done") diff --git a/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller_utils.go b/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller_utils.go index 0383fa94649a..25f2a0c4c7d0 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/replication/replication_controller_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/doc.go index a83ad10dd665..bb2035d2bb31 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/replenishment_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/replenishment_controller.go index a344bec8709c..25a84a02e0b9 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/replenishment_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/replenishment_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/resource_quota_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/resource_quota_controller.go index a64781c012e0..f75017e1ba4f 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/resource_quota_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/resourcequota/resource_quota_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -63,6 +63,8 @@ type ResourceQuotaController struct { rqController *framework.Controller // ResourceQuota objects that need to be synchronized queue workqueue.RateLimitingInterface + // missingUsageQueue holds objects that are missing the initial usage informatino + missingUsageQueue workqueue.RateLimitingInterface // To allow injection of syncUsage for testing. syncHandler func(key string) error // function that controls full recalculation of quota usage @@ -78,6 +80,7 @@ func NewResourceQuotaController(options *ResourceQuotaControllerOptions) *Resour rq := &ResourceQuotaController{ kubeClient: options.KubeClient, queue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), + missingUsageQueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), resyncPeriod: options.ResyncPeriod, registry: options.Registry, replenishmentControllers: []framework.ControllerInterface{}, @@ -101,7 +104,7 @@ func NewResourceQuotaController(options *ResourceQuotaControllerOptions) *Resour &api.ResourceQuota{}, rq.resyncPeriod(), framework.ResourceEventHandlerFuncs{ - AddFunc: rq.enqueueResourceQuota, + AddFunc: rq.addQuota, UpdateFunc: func(old, cur interface{}) { // We are only interested in observing updates to quota.spec to drive updates to quota.status. // We ignore all updates to quota.Status because they are all driven by this controller. @@ -116,7 +119,7 @@ func NewResourceQuotaController(options *ResourceQuotaControllerOptions) *Resour if quota.Equals(curResourceQuota.Spec.Hard, oldResourceQuota.Spec.Hard) { return } - rq.enqueueResourceQuota(curResourceQuota) + rq.addQuota(curResourceQuota) }, // This will enter the sync loop and no-op, because the controller has been deleted from the store. // Note that deleting a controller immediately after scaling it to 0 will not work. The recommended @@ -160,28 +163,63 @@ func (rq *ResourceQuotaController) enqueueResourceQuota(obj interface{}) { rq.queue.Add(key) } +func (rq *ResourceQuotaController) addQuota(obj interface{}) { + key, err := controller.KeyFunc(obj) + if err != nil { + glog.Errorf("Couldn't get key for object %+v: %v", obj, err) + return + } + + resourceQuota := obj.(*api.ResourceQuota) + + // if we declared an intent that is not yet captured in status (prioritize it) + if !api.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard) { + rq.missingUsageQueue.Add(key) + return + } + + // if we declared a constraint that has no usage (which this controller can calculate, prioritize it) + for constraint := range resourceQuota.Status.Hard { + if _, usageFound := resourceQuota.Status.Used[constraint]; !usageFound { + matchedResources := []api.ResourceName{constraint} + + for _, evaluator := range rq.registry.Evaluators() { + if intersection := quota.Intersection(evaluator.MatchesResources(), matchedResources); len(intersection) != 0 { + rq.missingUsageQueue.Add(key) + return + } + } + } + } + + // no special priority, go in normal recalc queue + rq.queue.Add(key) +} + // worker runs a worker thread that just dequeues items, processes them, and marks them done. -// It enforces that the syncHandler is never invoked concurrently with the same key. -func (rq *ResourceQuotaController) worker() { +func (rq *ResourceQuotaController) worker(queue workqueue.RateLimitingInterface) func() { workFunc := func() bool { - key, quit := rq.queue.Get() + key, quit := queue.Get() if quit { return true } - defer rq.queue.Done(key) + defer queue.Done(key) err := rq.syncHandler(key.(string)) if err == nil { - rq.queue.Forget(key) + queue.Forget(key) return false } utilruntime.HandleError(err) - rq.queue.AddRateLimited(key) + queue.AddRateLimited(key) return false } - for { - if quit := workFunc(); quit { - glog.Infof("resource quota controller worker shutting down") - return + + return func() { + for { + if quit := workFunc(); quit { + glog.Infof("resource quota controller worker shutting down") + return + } } } } @@ -196,7 +234,8 @@ func (rq *ResourceQuotaController) Run(workers int, stopCh <-chan struct{}) { } // the workers that chug through the quota calculation backlog for i := 0; i < workers; i++ { - go wait.Until(rq.worker, time.Second, stopCh) + go wait.Until(rq.worker(rq.queue), time.Second, stopCh) + go wait.Until(rq.worker(rq.missingUsageQueue), time.Second, stopCh) } // the timer for how often we do a full recalculation across all quotas go wait.Until(func() { rq.enqueueAll() }, rq.resyncPeriod(), stopCh) @@ -270,6 +309,10 @@ func (rq *ResourceQuotaController) syncResourceQuota(resourceQuota api.ResourceQ newUsage := api.ResourceList{} usageStatsOptions := quota.UsageStatsOptions{Namespace: resourceQuota.Namespace, Scopes: resourceQuota.Spec.Scopes} for _, evaluator := range evaluators { + // only trigger the evaluator if it matches a resource in the quota, otherwise, skip calculating anything + if intersection := quota.Intersection(evaluator.MatchesResources(), matchedResources); len(intersection) == 0 { + continue + } stats, err := evaluator.UsageStats(usageStatsOptions) if err != nil { return err diff --git a/vendor/k8s.io/kubernetes/pkg/controller/route/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/route/doc.go index bc4ae60a27ae..7208f5b4984d 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/route/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/route/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/route/routecontroller.go b/vendor/k8s.io/kubernetes/pkg/controller/route/routecontroller.go index 96a99101e179..179de8e9173c 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/route/routecontroller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/route/routecontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,10 +24,12 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/util/metrics" + nodeutil "k8s.io/kubernetes/pkg/util/node" "k8s.io/kubernetes/pkg/util/wait" ) @@ -162,32 +164,22 @@ func (rc *RouteController) reconcile(nodes []api.Node, routes []*cloudprovider.R return nil } -func updateNetworkingCondition(node *api.Node, routeCreated bool) { - _, networkingCondition := api.GetNodeCondition(&node.Status, api.NodeNetworkUnavailable) - currentTime := unversioned.Now() - if routeCreated { - if networkingCondition != nil && networkingCondition.Status != api.ConditionFalse { - networkingCondition.Status = api.ConditionFalse - networkingCondition.Reason = "RouteCreated" - networkingCondition.Message = "RouteController created a route" - networkingCondition.LastTransitionTime = currentTime - } else if networkingCondition == nil { - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ +func (rc *RouteController) updateNetworkingCondition(nodeName string, routeCreated bool) error { + var err error + for i := 0; i < updateNodeStatusMaxRetries; i++ { + // Patch could also fail, even though the chance is very slim. So we still do + // patch in the retry loop. + currentTime := unversioned.Now() + if routeCreated { + err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, api.NodeCondition{ Type: api.NodeNetworkUnavailable, Status: api.ConditionFalse, Reason: "RouteCreated", Message: "RouteController created a route", LastTransitionTime: currentTime, }) - } - } else { - if networkingCondition != nil && networkingCondition.Status != api.ConditionTrue { - networkingCondition.Status = api.ConditionTrue - networkingCondition.Reason = "NoRouteCreated" - networkingCondition.Message = "RouteController failed to create a route" - networkingCondition.LastTransitionTime = currentTime - } else if networkingCondition == nil { - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ + } else { + err = nodeutil.SetNodeCondition(rc.kubeClient, nodeName, api.NodeCondition{ Type: api.NodeNetworkUnavailable, Status: api.ConditionTrue, Reason: "NoRouteCreated", @@ -195,28 +187,14 @@ func updateNetworkingCondition(node *api.Node, routeCreated bool) { LastTransitionTime: currentTime, }) } - } -} - -func (rc *RouteController) updateNetworkingCondition(nodeName string, routeCreated bool) error { - var err error - for i := 0; i < updateNodeStatusMaxRetries; i++ { - node, err := rc.kubeClient.Core().Nodes().Get(nodeName) - if err != nil { - glog.Errorf("Error geting node: %v", err) - continue - } - updateNetworkingCondition(node, routeCreated) - // TODO: Use Patch instead once #26381 is merged. - // See kubernetes/node-problem-detector#9 for details. - if _, err = rc.kubeClient.Core().Nodes().UpdateStatus(node); err == nil { + if err == nil { return nil } - if i+1 < updateNodeStatusMaxRetries { - glog.Errorf("Error updating node %s, retrying: %v", node.Name, err) - } else { - glog.Errorf("Error updating node %s: %v", node.Name, err) + if i == updateNodeStatusMaxRetries || !errors.IsConflict(err) { + glog.Errorf("Error updating node %s: %v", nodeName, err) + return err } + glog.Errorf("Error updating node %s, retrying: %v", nodeName, err) } return err } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/service/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/service/doc.go index 78c20eb96507..42b9d1f174f7 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/service/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/service/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/service/servicecontroller.go b/vendor/k8s.io/kubernetes/pkg/controller/service/servicecontroller.go index 30ebe0954972..5e09c421d191 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/service/servicecontroller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/service/servicecontroller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -57,14 +57,14 @@ const ( ) type cachedService struct { + // Ensures only one goroutine can operate on this service at any given time. + mu sync.Mutex + // The last-known state of the service lastState *api.Service // The state as successfully applied to the load balancer appliedState *api.Service - // Ensures only one goroutine can operate on this service at any given time. - mu sync.Mutex - // Controls error back-off lastRetryDelay time.Duration } @@ -125,7 +125,7 @@ func (s *ServiceController) Run(serviceSyncPeriod, nodeSyncPeriod time.Duration) return err } - // We have to make this check beecause the ListWatch that we use in + // We have to make this check because the ListWatch that we use in // WatchServices requires Client functions that aren't in the interface // for some reason. if _, ok := s.kubeClient.(*clientset.Clientset); !ok { @@ -160,7 +160,7 @@ func (s *ServiceController) Run(serviceSyncPeriod, nodeSyncPeriod time.Duration) func (s *ServiceController) init() error { if s.cloud == nil { - return fmt.Errorf("ServiceController should not be run without a cloudprovider.") + return fmt.Errorf("WARNING: no cloud provider provided, services of type LoadBalancer will fail.") } balancer, ok := s.cloud.LoadBalancer() @@ -217,28 +217,31 @@ func (s *ServiceController) watchServices(serviceQueue *cache.DeltaFIFO) { // indicating whether processing should be retried; zero means no-retry; otherwise // we should retry in that Duration. func (s *ServiceController) processDelta(delta *cache.Delta) (error, time.Duration) { + var ( + namespacedName types.NamespacedName + cachedService *cachedService + ) + deltaService, ok := delta.Object.(*api.Service) - var namespacedName types.NamespacedName - var cachedService *cachedService - if !ok { + if ok { + namespacedName.Namespace = deltaService.Namespace + namespacedName.Name = deltaService.Name + cachedService = s.cache.getOrCreate(namespacedName.String()) + } else { // If the DeltaFIFO saw a key in our cache that it didn't know about, it // can send a deletion with an unknown state. Grab the service from our // cache for deleting. key, ok := delta.Object.(cache.DeletedFinalStateUnknown) if !ok { - return fmt.Errorf("Delta contained object that wasn't a service or a deleted key: %+v", delta), doNotRetry + return fmt.Errorf("delta contained object that wasn't a service or a deleted key: %+v", delta), doNotRetry } cachedService, ok = s.cache.get(key.Key) if !ok { - return fmt.Errorf("Service %s not in cache even though the watcher thought it was. Ignoring the deletion.", key), doNotRetry + return fmt.Errorf("service %s not in cache even though the watcher thought it was. Ignoring the deletion.", key), doNotRetry } deltaService = cachedService.lastState delta.Object = deltaService namespacedName = types.NamespacedName{Namespace: deltaService.Namespace, Name: deltaService.Name} - } else { - namespacedName.Namespace = deltaService.Namespace - namespacedName.Name = deltaService.Name - cachedService = s.cache.getOrCreate(namespacedName.String()) } glog.V(2).Infof("Got new %s delta for service: %v", delta.Type, namespacedName) @@ -255,10 +258,11 @@ func (s *ServiceController) processDelta(delta *cache.Delta) (error, time.Durati if err != nil && !errors.IsNotFound(err) { glog.Warningf("Failed to get most recent state of service %v from API (will retry): %v", namespacedName, err) return err, cachedService.nextRetryDelay() - } else if errors.IsNotFound(err) { + } + if errors.IsNotFound(err) { glog.V(2).Infof("Service %v not found, ensuring load balancer is deleted", namespacedName) s.eventRecorder.Event(deltaService, api.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") - err := s.balancer.EnsureLoadBalancerDeleted(deltaService) + err := s.balancer.EnsureLoadBalancerDeleted(s.clusterName, deltaService) if err != nil { message := "Error deleting load balancer (will retry): " + err.Error() s.eventRecorder.Event(deltaService, api.EventTypeWarning, "DeletingLoadBalancerFailed", message) @@ -312,7 +316,19 @@ func (s *ServiceController) createLoadBalancerIfNeeded(namespacedName types.Name // Save the state so we can avoid a write if it doesn't change previousState := api.LoadBalancerStatusDeepCopy(&service.Status.LoadBalancer) - if !wantsLoadBalancer(service) { + if wantsLoadBalancer(service) { + glog.V(2).Infof("Ensuring LB for service %s", namespacedName) + + // TODO: We could do a dry-run here if wanted to avoid the spurious cloud-calls & events when we restart + + // The load balancer doesn't exist yet, so create it. + s.eventRecorder.Event(service, api.EventTypeNormal, "CreatingLoadBalancer", "Creating load balancer") + err := s.createLoadBalancer(service) + if err != nil { + return fmt.Errorf("failed to create load balancer for service %s: %v", namespacedName, err), retryable + } + s.eventRecorder.Event(service, api.EventTypeNormal, "CreatedLoadBalancer", "Created load balancer") + } else { needDelete := true if appliedState != nil { if !wantsLoadBalancer(appliedState) { @@ -322,9 +338,9 @@ func (s *ServiceController) createLoadBalancerIfNeeded(namespacedName types.Name // If we don't have any cached memory of the load balancer, we have to ask // the cloud provider for what it knows about it. // Technically EnsureLoadBalancerDeleted can cope, but we want to post meaningful events - _, exists, err := s.balancer.GetLoadBalancer(service) + _, exists, err := s.balancer.GetLoadBalancer(s.clusterName, service) if err != nil { - return fmt.Errorf("Error getting LB for service %s: %v", namespacedName, err), retryable + return fmt.Errorf("error getting LB for service %s: %v", namespacedName, err), retryable } if !exists { needDelete = false @@ -334,35 +350,23 @@ func (s *ServiceController) createLoadBalancerIfNeeded(namespacedName types.Name if needDelete { glog.Infof("Deleting existing load balancer for service %s that no longer needs a load balancer.", namespacedName) s.eventRecorder.Event(service, api.EventTypeNormal, "DeletingLoadBalancer", "Deleting load balancer") - if err := s.balancer.EnsureLoadBalancerDeleted(service); err != nil { + if err := s.balancer.EnsureLoadBalancerDeleted(s.clusterName, service); err != nil { return err, retryable } s.eventRecorder.Event(service, api.EventTypeNormal, "DeletedLoadBalancer", "Deleted load balancer") } service.Status.LoadBalancer = api.LoadBalancerStatus{} - } else { - glog.V(2).Infof("Ensuring LB for service %s", namespacedName) - - // TODO: We could do a dry-run here if wanted to avoid the spurious cloud-calls & events when we restart - - // The load balancer doesn't exist yet, so create it. - s.eventRecorder.Event(service, api.EventTypeNormal, "CreatingLoadBalancer", "Creating load balancer") - err := s.createLoadBalancer(service) - if err != nil { - return fmt.Errorf("Failed to create load balancer for service %s: %v", namespacedName, err), retryable - } - s.eventRecorder.Event(service, api.EventTypeNormal, "CreatedLoadBalancer", "Created load balancer") } // Write the state if changed // TODO: Be careful here ... what if there were other changes to the service? - if !api.LoadBalancerStatusEqual(previousState, &service.Status.LoadBalancer) { + if api.LoadBalancerStatusEqual(previousState, &service.Status.LoadBalancer) { + glog.V(2).Infof("Not persisting unchanged LoadBalancerStatus to registry.") + } else { if err := s.persistUpdate(service); err != nil { - return fmt.Errorf("Failed to persist updated status to apiserver, even after retries. Giving up: %v", err), notRetryable + return fmt.Errorf("failed to persist updated status to apiserver, even after retries. Giving up: %v", err), notRetryable } - } else { - glog.V(2).Infof("Not persisting unchanged LoadBalancerStatus to registry.") } return nil, notRetryable @@ -372,25 +376,26 @@ func (s *ServiceController) persistUpdate(service *api.Service) error { var err error for i := 0; i < clientRetryCount; i++ { _, err = s.kubeClient.Core().Services(service.Namespace).UpdateStatus(service) - if err == nil { + + switch { + case err == nil: return nil - } - // If the object no longer exists, we don't want to recreate it. Just bail - // out so that we can process the delete, which we should soon be receiving - // if we haven't already. - if errors.IsNotFound(err) { + case errors.IsNotFound(err): + // If the object no longer exists, we don't want to recreate it. Just bail + // out so that we can process the delete, which we should soon be receiving + // if we haven't already. glog.Infof("Not persisting update to service '%s/%s' that no longer exists: %v", service.Namespace, service.Name, err) return nil - } - // TODO: Try to resolve the conflict if the change was unrelated to load - // balancer status. For now, just rely on the fact that we'll - // also process the update that caused the resource version to change. - if errors.IsConflict(err) { + case errors.IsConflict(err): + // TODO: Try to resolve the conflict if the change was unrelated to load + // balancer status. For now, just rely on the fact that we'll + // also process the update that caused the resource version to change. glog.V(4).Infof("Not persisting update to service '%s/%s' that has been changed since we received it: %v", service.Namespace, service.Name, err) return nil } + glog.Warningf("Failed to persist updated LoadBalancerStatus to service '%s/%s' after creating its load balancer: %v", service.Namespace, service.Name, err) time.Sleep(clientRetryInterval) @@ -407,13 +412,12 @@ func (s *ServiceController) createLoadBalancer(service *api.Service) error { // - Only one protocol supported per service // - Not all cloud providers support all protocols and the next step is expected to return // an error for unsupported protocols - status, err := s.balancer.EnsureLoadBalancer(service, hostsFromNodeList(&nodes)) + status, err := s.balancer.EnsureLoadBalancer(s.clusterName, service, hostsFromNodeList(&nodes)) if err != nil { return err - } else { - service.Status.LoadBalancer = *status } + service.Status.LoadBalancer = *status return nil } @@ -439,8 +443,6 @@ func (s *serviceCache) GetByKey(key string) (interface{}, bool, error) { return nil, false, nil } -// ListKeys implements the interface required by DeltaFIFO to list the keys we -// already know about. func (s *serviceCache) allServices() []*cachedService { s.mu.Lock() defer s.mu.Unlock() @@ -629,19 +631,32 @@ func stringSlicesEqual(x, y []string) bool { return true } +func includeNodeFromNodeList(node *api.Node) bool { + return !node.Spec.Unschedulable +} + func hostsFromNodeList(list *api.NodeList) []string { result := []string{} for ix := range list.Items { - if list.Items[ix].Spec.Unschedulable { - continue + if includeNodeFromNodeList(&list.Items[ix]) { + result = append(result, list.Items[ix].Name) + } + } + return result +} + +func hostsFromNodeSlice(nodes []*api.Node) []string { + result := []string{} + for _, node := range nodes { + if includeNodeFromNodeList(node) { + result = append(result, node.Name) } - result = append(result, list.Items[ix].Name) } return result } func getNodeConditionPredicate() cache.NodeConditionPredicate { - return func(node api.Node) bool { + return func(node *api.Node) bool { // We add the master to the node list, but its unschedulable. So we use this to filter // the master. // TODO: Use a node annotation to indicate the master @@ -675,7 +690,7 @@ func (s *ServiceController) nodeSyncLoop(period time.Duration) { glog.Errorf("Failed to retrieve current set of nodes from node lister: %v", err) continue } - newHosts := hostsFromNodeList(&nodes) + newHosts := hostsFromNodeSlice(nodes) if stringSlicesEqual(newHosts, prevHosts) { // The set of nodes in the cluster hasn't changed, but we can retry // updating any services that we failed to update last time around. @@ -728,14 +743,14 @@ func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *api.Service, } // This operation doesn't normally take very long (and happens pretty often), so we only record the final event - err := s.balancer.UpdateLoadBalancer(service, hosts) + err := s.balancer.UpdateLoadBalancer(s.clusterName, service, hosts) if err == nil { s.eventRecorder.Event(service, api.EventTypeNormal, "UpdatedLoadBalancer", "Updated load balancer with new hosts") return nil } // It's only an actual error if the load balancer still exists. - if _, exists, err := s.balancer.GetLoadBalancer(service); err != nil { + if _, exists, err := s.balancer.GetLoadBalancer(s.clusterName, service); err != nil { glog.Errorf("External error while checking if load balancer %q exists: name, %v", cloudprovider.GetLoadBalancerName(service), err) } else if !exists { return nil diff --git a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/doc.go b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/doc.go index b69d1a12151a..211796b12354 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/serviceaccounts_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/serviceaccounts_controller.go index 084ddae500a0..5062305e5a76 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/serviceaccounts_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/serviceaccounts_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokengetter.go b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokengetter.go index bd7fc827b254..dd0c66ef346e 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokengetter.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokengetter.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -69,9 +69,9 @@ func (r *registryGetter) GetSecret(namespace, name string) (*api.Secret, error) // NewGetterFromStorageInterface returns a ServiceAccountTokenGetter that // uses the specified storage to retrieve service accounts and secrets. -func NewGetterFromStorageInterface(s storage.Interface) serviceaccount.ServiceAccountTokenGetter { +func NewGetterFromStorageInterface(s storage.Interface, saPrefix, secretPrefix string) serviceaccount.ServiceAccountTokenGetter { return NewGetterFromRegistries( - serviceaccountregistry.NewRegistry(serviceaccountetcd.NewREST(generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage})), - secret.NewRegistry(secretetcd.NewREST(generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage})), + serviceaccountregistry.NewRegistry(serviceaccountetcd.NewREST(generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage, ResourcePrefix: saPrefix})), + secret.NewRegistry(secretetcd.NewREST(generic.RESTOptions{Storage: s, Decorator: generic.UndecoratedStorage, ResourcePrefix: secretPrefix})), ) } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokens_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokens_controller.go index b660afc963de..4c3f4fba0d77 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokens_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/serviceaccount/tokens_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,10 +32,13 @@ import ( "k8s.io/kubernetes/pkg/registry/secret" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/serviceaccount" + "k8s.io/kubernetes/pkg/types" + utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/metrics" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" + "k8s.io/kubernetes/pkg/util/workqueue" "k8s.io/kubernetes/pkg/watch" ) @@ -58,21 +61,36 @@ type TokensControllerOptions struct { // SecretResync is the time.Duration at which to fully re-list secrets. // If zero, re-list will be delayed as long as possible SecretResync time.Duration - // This CA will be added in the secretes of service accounts + // This CA will be added in the secrets of service accounts RootCA []byte + + // MaxRetries controls the maximum number of times a particular key is retried before giving up + // If zero, a default max is used + MaxRetries int } // NewTokensController returns a new *TokensController. func NewTokensController(cl clientset.Interface, options TokensControllerOptions) *TokensController { + maxRetries := options.MaxRetries + if maxRetries == 0 { + maxRetries = 10 + } + e := &TokensController{ client: cl, token: options.TokenGenerator, rootCA: options.RootCA, + + syncServiceAccountQueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), + syncSecretQueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), + + maxRetries: maxRetries, } if cl != nil && cl.Core().GetRESTClient().GetRateLimiter() != nil { metrics.RegisterMetricAndTrackRateLimiterUsage("serviceaccount_controller", cl.Core().GetRESTClient().GetRateLimiter()) } - e.serviceAccounts, e.serviceAccountController = framework.NewIndexerInformer( + + e.serviceAccounts, e.serviceAccountController = framework.NewInformer( &cache.ListWatch{ ListFunc: func(options api.ListOptions) (runtime.Object, error) { return e.client.Core().ServiceAccounts(api.NamespaceAll).List(options) @@ -84,11 +102,10 @@ func NewTokensController(cl clientset.Interface, options TokensControllerOptions &api.ServiceAccount{}, options.ServiceAccountResync, framework.ResourceEventHandlerFuncs{ - AddFunc: e.serviceAccountAdded, - UpdateFunc: e.serviceAccountUpdated, - DeleteFunc: e.serviceAccountDeleted, + AddFunc: e.queueServiceAccountSync, + UpdateFunc: e.queueServiceAccountUpdateSync, + DeleteFunc: e.queueServiceAccountSync, }, - cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc}, ) tokenSelector := fields.SelectorFromSet(map[string]string{api.SecretTypeField: string(api.SecretTypeServiceAccountToken)}) @@ -106,206 +123,277 @@ func NewTokensController(cl clientset.Interface, options TokensControllerOptions &api.Secret{}, options.SecretResync, framework.ResourceEventHandlerFuncs{ - AddFunc: e.secretAdded, - UpdateFunc: e.secretUpdated, - DeleteFunc: e.secretDeleted, + AddFunc: e.queueSecretSync, + UpdateFunc: e.queueSecretUpdateSync, + DeleteFunc: e.queueSecretSync, }, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc}, ) - e.serviceAccountsSynced = e.serviceAccountController.HasSynced - e.secretsSynced = e.secretController.HasSynced - return e } // TokensController manages ServiceAccountToken secrets for ServiceAccount objects type TokensController struct { - stopChan chan struct{} - client clientset.Interface token serviceaccount.TokenGenerator rootCA []byte - serviceAccounts cache.Indexer + serviceAccounts cache.Store secrets cache.Indexer // Since we join two objects, we'll watch both of them with controllers. serviceAccountController *framework.Controller secretController *framework.Controller - // These are here so tests can inject a 'return true'. - serviceAccountsSynced func() bool - secretsSynced func() bool + // syncServiceAccountQueue handles service account events: + // * ensures a referenced token exists for service accounts which still exist + // * ensures tokens are removed for service accounts which no longer exist + // key is "//" + syncServiceAccountQueue workqueue.RateLimitingInterface + + // syncSecretQueue handles secret events: + // * deletes tokens whose service account no longer exists + // * updates tokens with missing token or namespace data, or mismatched ca data + // * ensures service account secret references are removed for tokens which are deleted + // key is a secretQueueKey{} + syncSecretQueue workqueue.RateLimitingInterface + + maxRetries int } -// Runs controller loops and returns immediately -func (e *TokensController) Run() { - if e.stopChan == nil { - e.stopChan = make(chan struct{}) - go e.serviceAccountController.Run(e.stopChan) - go e.secretController.Run(e.stopChan) +// Runs controller blocks until stopCh is closed +func (e *TokensController) Run(workers int, stopCh <-chan struct{}) { + defer utilruntime.HandleCrash() + + // Start controllers (to fill stores, call informers, fill work queues) + go e.serviceAccountController.Run(stopCh) + go e.secretController.Run(stopCh) + + // Wait for stores to fill + for !e.serviceAccountController.HasSynced() || !e.secretController.HasSynced() { + time.Sleep(100 * time.Millisecond) } -} -// Stop gracefully shuts down this controller -func (e *TokensController) Stop() { - if e.stopChan != nil { - close(e.stopChan) - e.stopChan = nil + // Spawn workers to process work queues + for i := 0; i < workers; i++ { + go wait.Until(e.syncServiceAccount, 0, stopCh) + go wait.Until(e.syncSecret, 0, stopCh) } + + // Block until stop channel is closed + <-stopCh + + // Shut down queues + e.syncServiceAccountQueue.ShutDown() + e.syncSecretQueue.ShutDown() } -// serviceAccountAdded reacts to a ServiceAccount creation by creating a corresponding ServiceAccountToken Secret -func (e *TokensController) serviceAccountAdded(obj interface{}) { - serviceAccount := obj.(*api.ServiceAccount) - err := e.createSecretIfNeeded(serviceAccount) - if err != nil { - glog.Error(err) +func (e *TokensController) queueServiceAccountSync(obj interface{}) { + if serviceAccount, ok := obj.(*api.ServiceAccount); ok { + e.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount)) } } -// serviceAccountUpdated reacts to a ServiceAccount update (or re-list) by ensuring a corresponding ServiceAccountToken Secret exists -func (e *TokensController) serviceAccountUpdated(oldObj interface{}, newObj interface{}) { - newServiceAccount := newObj.(*api.ServiceAccount) - err := e.createSecretIfNeeded(newServiceAccount) - if err != nil { - glog.Error(err) +func (e *TokensController) queueServiceAccountUpdateSync(oldObj interface{}, newObj interface{}) { + if serviceAccount, ok := newObj.(*api.ServiceAccount); ok { + e.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount)) } } -// serviceAccountDeleted reacts to a ServiceAccount deletion by deleting all corresponding ServiceAccountToken Secrets -func (e *TokensController) serviceAccountDeleted(obj interface{}) { - serviceAccount, ok := obj.(*api.ServiceAccount) - if !ok { - // Unknown type. If we missed a ServiceAccount deletion, the - // corresponding secrets will be cleaned up during the Secret re-list +// complete optionally requeues key, then calls queue.Done(key) +func (e *TokensController) retryOrForget(queue workqueue.RateLimitingInterface, key interface{}, requeue bool) { + if !requeue { + queue.Forget(key) return } - secrets, err := e.listTokenSecrets(serviceAccount) - if err != nil { - glog.Error(err) + + requeueCount := queue.NumRequeues(key) + if requeueCount < e.maxRetries { + queue.AddRateLimited(key) return } - for _, secret := range secrets { - glog.V(4).Infof("Deleting secret %s/%s because service account %s was deleted", secret.Namespace, secret.Name, serviceAccount.Name) - if err := e.deleteSecret(secret); err != nil { - glog.Errorf("Error deleting secret %s/%s: %v", secret.Namespace, secret.Name, err) - } - } + + glog.V(4).Infof("retried %d times: %#v", requeueCount, key) + queue.Forget(key) } -// secretAdded reacts to a Secret create by ensuring the referenced ServiceAccount exists, and by adding a token to the secret if needed -func (e *TokensController) secretAdded(obj interface{}) { - secret := obj.(*api.Secret) - serviceAccount, err := e.getServiceAccount(secret, true) - if err != nil { - glog.Error(err) - return +func (e *TokensController) queueSecretSync(obj interface{}) { + if secret, ok := obj.(*api.Secret); ok { + e.syncSecretQueue.Add(makeSecretQueueKey(secret)) } - if serviceAccount == nil { - glog.V(2).Infof( - "Deleting new secret %s/%s because service account %s (uid=%s) was not found", - secret.Namespace, secret.Name, - secret.Annotations[api.ServiceAccountNameKey], secret.Annotations[api.ServiceAccountUIDKey]) - if err := e.deleteSecret(secret); err != nil { - glog.Errorf("Error deleting secret %s/%s: %v", secret.Namespace, secret.Name, err) - } - } else { - e.generateTokenIfNeeded(serviceAccount, secret) +} + +func (e *TokensController) queueSecretUpdateSync(oldObj interface{}, newObj interface{}) { + if secret, ok := newObj.(*api.Secret); ok { + e.syncSecretQueue.Add(makeSecretQueueKey(secret)) } } -// secretUpdated reacts to a Secret update (or re-list) by deleting the secret (if the referenced ServiceAccount does not exist) -func (e *TokensController) secretUpdated(oldObj interface{}, newObj interface{}) { - newSecret := newObj.(*api.Secret) - newServiceAccount, err := e.getServiceAccount(newSecret, true) +func (e *TokensController) syncServiceAccount() { + key, quit := e.syncServiceAccountQueue.Get() + if quit { + return + } + defer e.syncServiceAccountQueue.Done(key) + + retry := false + defer func() { + e.retryOrForget(e.syncServiceAccountQueue, key, retry) + }() + + saInfo, err := parseServiceAccountKey(key) if err != nil { glog.Error(err) return } - if newServiceAccount == nil { - glog.V(2).Infof( - "Deleting updated secret %s/%s because service account %s (uid=%s) was not found", - newSecret.Namespace, newSecret.Name, - newSecret.Annotations[api.ServiceAccountNameKey], newSecret.Annotations[api.ServiceAccountUIDKey]) - if err := e.deleteSecret(newSecret); err != nil { - glog.Errorf("Error deleting secret %s/%s: %v", newSecret.Namespace, newSecret.Name, err) + + sa, err := e.getServiceAccount(saInfo.namespace, saInfo.name, saInfo.uid, false) + switch { + case err != nil: + glog.Error(err) + retry = true + case sa == nil: + // service account no longer exists, so delete related tokens + glog.V(4).Infof("syncServiceAccount(%s/%s), service account deleted, removing tokens", saInfo.namespace, saInfo.name) + sa = &api.ServiceAccount{ObjectMeta: api.ObjectMeta{Namespace: saInfo.namespace, Name: saInfo.name, UID: saInfo.uid}} + if retriable, err := e.deleteTokens(sa); err != nil { + glog.Errorf("error deleting serviceaccount tokens for %s/%s: %v", saInfo.namespace, saInfo.name, err) + retry = retriable + } + default: + // ensure a token exists and is referenced by this service account + if retriable, err := e.ensureReferencedToken(sa); err != nil { + glog.Errorf("error synchronizing serviceaccount %s/%s: %v", saInfo.namespace, saInfo.name, err) + retry = retriable } - } else { - e.generateTokenIfNeeded(newServiceAccount, newSecret) } } -// secretDeleted reacts to a Secret being deleted by removing a reference from the corresponding ServiceAccount if needed -func (e *TokensController) secretDeleted(obj interface{}) { - secret, ok := obj.(*api.Secret) - if !ok { - // Unknown type. If we missed a Secret deletion, the corresponding ServiceAccount (if it exists) - // will get a secret recreated (if needed) during the ServiceAccount re-list +func (e *TokensController) syncSecret() { + key, quit := e.syncSecretQueue.Get() + if quit { return } + defer e.syncSecretQueue.Done(key) - serviceAccount, err := e.getServiceAccount(secret, false) + // Track whether or not we should retry this sync + retry := false + defer func() { + e.retryOrForget(e.syncSecretQueue, key, retry) + }() + + secretInfo, err := parseSecretQueueKey(key) if err != nil { glog.Error(err) return } - if serviceAccount == nil { - return - } - if err := client.RetryOnConflict(RemoveTokenBackoff, func() error { - return e.removeSecretReferenceIfNeeded(serviceAccount, secret.Name) - }); err != nil { - utilruntime.HandleError(err) + secret, err := e.getSecret(secretInfo.namespace, secretInfo.name, secretInfo.uid, false) + switch { + case err != nil: + glog.Error(err) + retry = true + case secret == nil: + // If the service account exists + if sa, saErr := e.getServiceAccount(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, false); saErr == nil && sa != nil { + // secret no longer exists, so delete references to this secret from the service account + if err := client.RetryOnConflict(RemoveTokenBackoff, func() error { + return e.removeSecretReference(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, secretInfo.name) + }); err != nil { + glog.Error(err) + } + } + default: + // Ensure service account exists + sa, saErr := e.getServiceAccount(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, true) + switch { + case saErr != nil: + glog.Error(saErr) + retry = true + case sa == nil: + // Delete token + glog.V(4).Infof("syncSecret(%s/%s), service account does not exist, deleting token", secretInfo.namespace, secretInfo.name) + if retriable, err := e.deleteToken(secretInfo.namespace, secretInfo.name, secretInfo.uid); err != nil { + glog.Errorf("error deleting serviceaccount token %s/%s for service account %s: %v", secretInfo.namespace, secretInfo.name, secretInfo.saName, err) + retry = retriable + } + default: + // Update token if needed + if retriable, err := e.generateTokenIfNeeded(sa, secret); err != nil { + glog.Errorf("error populating serviceaccount token %s/%s for service account %s: %v", secretInfo.namespace, secretInfo.name, secretInfo.saName, err) + retry = retriable + } + } } } -// createSecretIfNeeded makes sure at least one ServiceAccountToken secret exists, and is included in the serviceAccount's Secrets list -func (e *TokensController) createSecretIfNeeded(serviceAccount *api.ServiceAccount) error { - // If the service account references no secrets, short-circuit and create a new one - if len(serviceAccount.Secrets) == 0 { - return e.createSecret(serviceAccount) - } - - // We shouldn't try to validate secret references until the secrets store is synced - if !e.secretsSynced() { - return nil - } - - // If any existing token secrets are referenced by the service account, return - allSecrets, err := e.listTokenSecrets(serviceAccount) +func (e *TokensController) deleteTokens(serviceAccount *api.ServiceAccount) ( /*retry*/ bool, error) { + tokens, err := e.listTokenSecrets(serviceAccount) if err != nil { - return err + // don't retry on cache lookup errors + return false, err } - referencedSecrets := getSecretReferences(serviceAccount) - for _, secret := range allSecrets { - if referencedSecrets.Has(secret.Name) { - return nil + retry := false + errs := []error{} + for _, token := range tokens { + r, err := e.deleteToken(token.Namespace, token.Name, token.UID) + if err != nil { + errs = append(errs, err) + } + if r { + retry = true } } + return retry, utilerrors.NewAggregate(errs) +} - // Otherwise create a new token secret - return e.createSecret(serviceAccount) +func (e *TokensController) deleteToken(ns, name string, uid types.UID) ( /*retry*/ bool, error) { + var opts *api.DeleteOptions + if len(uid) > 0 { + opts = &api.DeleteOptions{Preconditions: &api.Preconditions{UID: &uid}} + } + err := e.client.Core().Secrets(ns).Delete(name, opts) + // NotFound doesn't need a retry (it's already been deleted) + // Conflict doesn't need a retry (the UID precondition failed) + if err == nil || apierrors.IsNotFound(err) || apierrors.IsConflict(err) { + return false, nil + } + // Retry for any other error + return true, err } -// createSecret creates a secret of type ServiceAccountToken for the given ServiceAccount -func (e *TokensController) createSecret(serviceAccount *api.ServiceAccount) error { +// ensureReferencedToken makes sure at least one ServiceAccountToken secret exists, and is included in the serviceAccount's Secrets list +func (e *TokensController) ensureReferencedToken(serviceAccount *api.ServiceAccount) ( /* retry */ bool, error) { + if len(serviceAccount.Secrets) > 0 { + allSecrets, err := e.listTokenSecrets(serviceAccount) + if err != nil { + // Don't retry cache lookup errors + return false, err + } + referencedSecrets := getSecretReferences(serviceAccount) + for _, secret := range allSecrets { + if referencedSecrets.Has(secret.Name) { + // A service account token already exists, and is referenced, short-circuit + return false, nil + } + } + } + // We don't want to update the cache's copy of the service account // so add the secret to a freshly retrieved copy of the service account serviceAccounts := e.client.Core().ServiceAccounts(serviceAccount.Namespace) liveServiceAccount, err := serviceAccounts.Get(serviceAccount.Name) if err != nil { - return err + // Retry for any error other than a NotFound + return !apierrors.IsNotFound(err), err } if liveServiceAccount.ResourceVersion != serviceAccount.ResourceVersion { // our view of the service account is not up to date // we'll get notified of an update event later and get to try again - // this only prevent interactions between successive runs of this controller's event handlers, but that is useful - glog.V(2).Infof("View of ServiceAccount %s/%s is not up to date, skipping token creation", serviceAccount.Namespace, serviceAccount.Name) - return nil + glog.V(2).Infof("serviceaccount %s/%s is not up to date, skipping token creation", serviceAccount.Namespace, serviceAccount.Name) + return false, nil } // Build the secret @@ -325,7 +413,8 @@ func (e *TokensController) createSecret(serviceAccount *api.ServiceAccount) erro // Generate the token token, err := e.token.GenerateToken(*serviceAccount, *secret) if err != nil { - return err + // retriable error + return true, err } secret.Data[api.ServiceAccountTokenKey] = []byte(token) secret.Data[api.ServiceAccountNamespaceKey] = []byte(serviceAccount.Namespace) @@ -334,41 +423,39 @@ func (e *TokensController) createSecret(serviceAccount *api.ServiceAccount) erro } // Save the secret - if createdToken, err := e.client.Core().Secrets(serviceAccount.Namespace).Create(secret); err != nil { - return err - } else { - // Manually add the new token to the cache store. - // This prevents the service account update (below) triggering another token creation, if the referenced token couldn't be found in the store - e.secrets.Add(createdToken) + createdToken, err := e.client.Core().Secrets(serviceAccount.Namespace).Create(secret) + if err != nil { + // retriable error + return true, err } + // Manually add the new token to the cache store. + // This prevents the service account update (below) triggering another token creation, if the referenced token couldn't be found in the store + e.secrets.Add(createdToken) liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, api.ObjectReference{Name: secret.Name}) - _, err = serviceAccounts.Update(liveServiceAccount) - if err != nil { + if _, err = serviceAccounts.Update(liveServiceAccount); err != nil { // we weren't able to use the token, try to clean it up. - glog.V(2).Infof("Deleting secret %s/%s because reference couldn't be added (%v)", secret.Namespace, secret.Name, err) - if err := e.client.Core().Secrets(secret.Namespace).Delete(secret.Name, nil); err != nil { - glog.Error(err) // if we fail, just log it + glog.V(2).Infof("deleting secret %s/%s because reference couldn't be added (%v)", secret.Namespace, secret.Name, err) + deleteOpts := &api.DeleteOptions{Preconditions: &api.Preconditions{UID: &createdToken.UID}} + if deleteErr := e.client.Core().Secrets(createdToken.Namespace).Delete(createdToken.Name, deleteOpts); deleteErr != nil { + glog.Error(deleteErr) // if we fail, just log it } - } - if apierrors.IsConflict(err) { - // nothing to do. We got a conflict, that means that the service account was updated. We simply need to return because we'll get an update notification later - return nil + + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + // if we got a Conflict error, the service account was updated by someone else, and we'll get an update notification later + // if we got a NotFound error, the service account no longer exists, and we don't need to create a token for it + return false, nil + } + // retry in all other cases + return true, err } - return err + // success! + return false, nil } -// generateTokenIfNeeded populates the token data for the given Secret if not already set -func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAccount, secret *api.Secret) error { - if secret.Annotations == nil { - secret.Annotations = map[string]string{} - } - if secret.Data == nil { - secret.Data = map[string][]byte{} - } - +func (e *TokensController) secretUpdateNeeded(secret *api.Secret) (bool, bool, bool) { caData := secret.Data[api.ServiceAccountRootCAKey] needsCA := len(e.rootCA) > 0 && bytes.Compare(caData, e.rootCA) != 0 @@ -377,60 +464,103 @@ func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAcco tokenData := secret.Data[api.ServiceAccountTokenKey] needsToken := len(tokenData) == 0 + return needsCA, needsNamespace, needsToken +} + +// generateTokenIfNeeded populates the token data for the given Secret if not already set +func (e *TokensController) generateTokenIfNeeded(serviceAccount *api.ServiceAccount, cachedSecret *api.Secret) ( /* retry */ bool, error) { + // Check the cached secret to see if changes are needed + if needsCA, needsNamespace, needsToken := e.secretUpdateNeeded(cachedSecret); !needsCA && !needsToken && !needsNamespace { + return false, nil + } + + // We don't want to update the cache's copy of the secret + // so add the token to a freshly retrieved copy of the secret + secrets := e.client.Core().Secrets(cachedSecret.Namespace) + liveSecret, err := secrets.Get(cachedSecret.Name) + if err != nil { + // Retry for any error other than a NotFound + return !apierrors.IsNotFound(err), err + } + if liveSecret.ResourceVersion != cachedSecret.ResourceVersion { + // our view of the secret is not up to date + // we'll get notified of an update event later and get to try again + glog.V(2).Infof("secret %s/%s is not up to date, skipping token population", liveSecret.Namespace, liveSecret.Name) + return false, nil + } + + needsCA, needsNamespace, needsToken := e.secretUpdateNeeded(liveSecret) if !needsCA && !needsToken && !needsNamespace { - return nil + return false, nil + } + + if liveSecret.Annotations == nil { + liveSecret.Annotations = map[string]string{} + } + if liveSecret.Data == nil { + liveSecret.Data = map[string][]byte{} } // Set the CA if needsCA { - secret.Data[api.ServiceAccountRootCAKey] = e.rootCA + liveSecret.Data[api.ServiceAccountRootCAKey] = e.rootCA } // Set the namespace if needsNamespace { - secret.Data[api.ServiceAccountNamespaceKey] = []byte(secret.Namespace) + liveSecret.Data[api.ServiceAccountNamespaceKey] = []byte(liveSecret.Namespace) } // Generate the token if needsToken { - token, err := e.token.GenerateToken(*serviceAccount, *secret) + token, err := e.token.GenerateToken(*serviceAccount, *liveSecret) if err != nil { - return err + return false, err } - secret.Data[api.ServiceAccountTokenKey] = []byte(token) + liveSecret.Data[api.ServiceAccountTokenKey] = []byte(token) } // Set annotations - secret.Annotations[api.ServiceAccountNameKey] = serviceAccount.Name - secret.Annotations[api.ServiceAccountUIDKey] = string(serviceAccount.UID) + liveSecret.Annotations[api.ServiceAccountNameKey] = serviceAccount.Name + liveSecret.Annotations[api.ServiceAccountUIDKey] = string(serviceAccount.UID) // Save the secret - if _, err := e.client.Core().Secrets(secret.Namespace).Update(secret); err != nil { - return err + _, err = secrets.Update(liveSecret) + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + // if we got a Conflict error, the secret was updated by someone else, and we'll get an update notification later + // if we got a NotFound error, the secret no longer exists, and we don't need to populate a token + return false, nil } - return nil -} - -// deleteSecret deletes the given secret -func (e *TokensController) deleteSecret(secret *api.Secret) error { - return e.client.Core().Secrets(secret.Namespace).Delete(secret.Name, nil) + if err != nil { + return true, err + } + return false, nil } -// removeSecretReferenceIfNeeded updates the given ServiceAccount to remove a reference to the given secretName if needed. -// Returns whether an update was performed, and any error that occurred -func (e *TokensController) removeSecretReferenceIfNeeded(serviceAccount *api.ServiceAccount, secretName string) error { +// removeSecretReference updates the given ServiceAccount to remove a reference to the given secretName if needed. +func (e *TokensController) removeSecretReference(saNamespace string, saName string, saUID types.UID, secretName string) error { // We don't want to update the cache's copy of the service account // so remove the secret from a freshly retrieved copy of the service account - serviceAccounts := e.client.Core().ServiceAccounts(serviceAccount.Namespace) - serviceAccount, err := serviceAccounts.Get(serviceAccount.Name) + serviceAccounts := e.client.Core().ServiceAccounts(saNamespace) + serviceAccount, err := serviceAccounts.Get(saName) + // Ignore NotFound errors when attempting to remove a reference + if apierrors.IsNotFound(err) { + return nil + } if err != nil { return err } - // Double-check to see if the account still references the secret + // Short-circuit if the UID doesn't match + if len(saUID) > 0 && saUID != serviceAccount.UID { + return nil + } + + // Short-circuit if the secret is no longer referenced if !getSecretReferences(serviceAccount).Has(secretName) { return nil } + // Remove the secret secrets := []api.ObjectReference{} for _, s := range serviceAccount.Secrets { if s.Name != secretName { @@ -438,59 +568,90 @@ func (e *TokensController) removeSecretReferenceIfNeeded(serviceAccount *api.Ser } } serviceAccount.Secrets = secrets - _, err = serviceAccounts.Update(serviceAccount) - if err != nil { - return err + // Ignore NotFound errors when attempting to remove a reference + if apierrors.IsNotFound(err) { + return nil } - - return nil + return err } -// getServiceAccount returns the ServiceAccount referenced by the given secret. If the secret is not -// of type ServiceAccountToken, or if the referenced ServiceAccount does not exist, nil is returned -func (e *TokensController) getServiceAccount(secret *api.Secret, fetchOnCacheMiss bool) (*api.ServiceAccount, error) { - name, _ := serviceAccountNameAndUID(secret) - if len(name) == 0 { +func (e *TokensController) getServiceAccount(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*api.ServiceAccount, error) { + // Look up in cache + obj, exists, err := e.serviceAccounts.GetByKey(makeCacheKey(ns, name)) + if err != nil { + return nil, err + } + if exists { + sa, ok := obj.(*api.ServiceAccount) + if !ok { + return nil, fmt.Errorf("expected *api.ServiceAccount, got %#v", sa) + } + // Ensure UID matches if given + if len(uid) == 0 || uid == sa.UID { + return sa, nil + } + } + + if !fetchOnCacheMiss { return nil, nil } - key := &api.ServiceAccount{ObjectMeta: api.ObjectMeta{Namespace: secret.Namespace}} - namespaceAccounts, err := e.serviceAccounts.Index("namespace", key) + // Live lookup + sa, err := e.client.Core().ServiceAccounts(ns).Get(name) + if apierrors.IsNotFound(err) { + return nil, nil + } if err != nil { return nil, err } - - for _, obj := range namespaceAccounts { - serviceAccount := obj.(*api.ServiceAccount) - - if serviceaccount.IsServiceAccountToken(secret, serviceAccount) { - return serviceAccount, nil - } + // Ensure UID matches if given + if len(uid) == 0 || uid == sa.UID { + return sa, nil } + return nil, nil +} - if fetchOnCacheMiss { - serviceAccount, err := e.client.Core().ServiceAccounts(secret.Namespace).Get(name) - if apierrors.IsNotFound(err) { - return nil, nil +func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*api.Secret, error) { + // Look up in cache + obj, exists, err := e.secrets.GetByKey(makeCacheKey(ns, name)) + if err != nil { + return nil, err + } + if exists { + secret, ok := obj.(*api.Secret) + if !ok { + return nil, fmt.Errorf("expected *api.Secret, got %#v", secret) } - if err != nil { - return nil, err + // Ensure UID matches if given + if len(uid) == 0 || uid == secret.UID { + return secret, nil } + } - if serviceaccount.IsServiceAccountToken(secret, serviceAccount) { - return serviceAccount, nil - } + if !fetchOnCacheMiss { + return nil, nil } + // Live lookup + secret, err := e.client.Core().Secrets(ns).Get(name) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + // Ensure UID matches if given + if len(uid) == 0 || uid == secret.UID { + return secret, nil + } return nil, nil } // listTokenSecrets returns a list of all of the ServiceAccountToken secrets that // reference the given service account's name and uid func (e *TokensController) listTokenSecrets(serviceAccount *api.ServiceAccount) ([]*api.Secret, error) { - key := &api.Secret{ObjectMeta: api.ObjectMeta{Namespace: serviceAccount.Namespace}} - namespaceSecrets, err := e.secrets.Index("namespace", key) + namespaceSecrets, err := e.secrets.ByIndex("namespace", serviceAccount.Namespace) if err != nil { return nil, err } @@ -523,3 +684,63 @@ func getSecretReferences(serviceAccount *api.ServiceAccount) sets.String { } return references } + +// serviceAccountQueueKey holds information we need to sync a service account. +// It contains enough information to look up the cached service account, +// or delete owned tokens if the service account no longer exists. +type serviceAccountQueueKey struct { + namespace string + name string + uid types.UID +} + +func makeServiceAccountKey(sa *api.ServiceAccount) interface{} { + return serviceAccountQueueKey{ + namespace: sa.Namespace, + name: sa.Name, + uid: sa.UID, + } +} + +func parseServiceAccountKey(key interface{}) (serviceAccountQueueKey, error) { + queueKey, ok := key.(serviceAccountQueueKey) + if !ok || len(queueKey.namespace) == 0 || len(queueKey.name) == 0 || len(queueKey.uid) == 0 { + return serviceAccountQueueKey{}, fmt.Errorf("invalid serviceaccount key: %#v", key) + } + return queueKey, nil +} + +// secretQueueKey holds information we need to sync a service account token secret. +// It contains enough information to look up the cached service account, +// or delete the secret reference if the secret no longer exists. +type secretQueueKey struct { + namespace string + name string + uid types.UID + saName string + // optional, will be blank when syncing tokens missing the service account uid annotation + saUID types.UID +} + +func makeSecretQueueKey(secret *api.Secret) interface{} { + return secretQueueKey{ + namespace: secret.Namespace, + name: secret.Name, + uid: secret.UID, + saName: secret.Annotations[api.ServiceAccountNameKey], + saUID: types.UID(secret.Annotations[api.ServiceAccountUIDKey]), + } +} + +func parseSecretQueueKey(key interface{}) (secretQueueKey, error) { + queueKey, ok := key.(secretQueueKey) + if !ok || len(queueKey.namespace) == 0 || len(queueKey.name) == 0 || len(queueKey.uid) == 0 || len(queueKey.saName) == 0 { + return secretQueueKey{}, fmt.Errorf("invalid secret key: %#v", key) + } + return queueKey, nil +} + +// produce the same key format as cache.MetaNamespaceKeyFunc +func makeCacheKey(namespace, name string) string { + return namespace + "/" + name +} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/attach_detach_controller.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/attach_detach_controller.go index d6f042ce65a0..de28234fa832 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/attach_detach_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/attach_detach_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go index acdd75f53399..52df9cb36c6f 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/actual_state_of_world.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go index 2543ecfed38e..d53a44236807 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache/desired_state_of_world.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go index ab9cbac3156c..f1abbb0a4c96 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/reconciler/reconciler.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/reconciler/reconciler.go index e27fa8c326d0..ab39f5b8a1ce 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/reconciler/reconciler.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/reconciler/reconciler.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -127,7 +127,7 @@ func (rc *reconciler) reconciliationLoopFunc() func() { err) } } else { - // If volume is not safe to detach (is mounted) wait a max amount of time before detaching any way. + // If volume is not safe to detach (is mounted) wait a max amount of time before detaching anyway. if timeElapsed > rc.maxWaitForUnmountDuration { glog.V(5).Infof("Attempting to start DetachVolume for volume %q from node %q. Volume is not safe to detach, but maxWaitForUnmountDuration expired.", attachedVolume.VolumeName, attachedVolume.NodeName) err := rc.attacherDetacher.DetachVolume(attachedVolume.AttachedVolume, false /* verifySafeToDetach */, rc.actualStateOfWorld) diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/fake_node_status_updater.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/fake_node_status_updater.go index dc734e2ff0d7..b78e80e38634 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/fake_node_status_updater.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/fake_node_status_updater.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go index 27c3a25b8302..a9d5cc61d1eb 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller.go index cabfcdddd633..0241ac36ed30 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package persistentvolume import ( "fmt" - "reflect" "time" "k8s.io/kubernetes/pkg/api" @@ -151,9 +150,8 @@ func (ctrl *PersistentVolumeController) syncClaim(claim *api.PersistentVolumeCla if !hasAnnotation(claim.ObjectMeta, annBindCompleted) { return ctrl.syncUnboundClaim(claim) - } else { - return ctrl.syncBoundClaim(claim) } + return ctrl.syncBoundClaim(claim) } // syncUnboundClaim is the main controller method to decide what to do with an @@ -169,98 +167,86 @@ func (ctrl *PersistentVolumeController) syncUnboundClaim(claim *api.PersistentVo glog.V(2).Infof("synchronizing unbound PersistentVolumeClaim[%s]: Error finding PV for claim: %v", claimToClaimKey(claim), err) return fmt.Errorf("Error finding PV for claim %q: %v", claimToClaimKey(claim), err) } - if volume == nil { - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: no volume found", claimToClaimKey(claim)) - // No PV could be found - // OBSERVATION: pvc is "Pending", will retry - if hasAnnotation(claim.ObjectMeta, annClass) { - if err = ctrl.provisionClaim(claim); err != nil { - return err - } - return nil - } - // Mark the claim as Pending and try to find a match in the next - // periodic syncClaim - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { - return err - } - return nil - } else /* pv != nil */ { + + if volume != nil { // Found a PV for this claim // OBSERVATION: pvc is "Pending", pv is "Available" glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q found: %s", claimToClaimKey(claim), volume.Name, getVolumeStatusForLogging(volume)) - if err = ctrl.bind(volume, claim); err != nil { - // On any error saving the volume or the claim, subsequent - // syncClaim will finish the binding. - return err - } - // OBSERVATION: claim is "Bound", pv is "Bound" - return nil - } - } else /* pvc.Spec.VolumeName != nil */ { - // [Unit test set 2] - // User asked for a specific PV. - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested", claimToClaimKey(claim), claim.Spec.VolumeName) - obj, found, err := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName) - if err != nil { - return err + + // On any error saving the volume or the claim, subsequent + // syncClaim will finish the binding. + // OBSERVATION: claim is "Bound", pv is "Bound" when no error + return ctrl.bind(volume, claim) } - if !found { - // User asked for a PV that does not exist. - // OBSERVATION: pvc is "Pending" - // Retry later. - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested and not found, will try again next time", claimToClaimKey(claim), claim.Spec.VolumeName) - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { - return err - } - return nil - } else { - volume, ok := obj.(*api.PersistentVolume) - if !ok { - return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %+v", claim.Spec.VolumeName, obj) - } - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested and found: %s", claimToClaimKey(claim), claim.Spec.VolumeName, getVolumeStatusForLogging(volume)) - if volume.Spec.ClaimRef == nil { - // User asked for a PV that is not claimed - // OBSERVATION: pvc is "Pending", pv is "Available" - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume is unbound, binding", claimToClaimKey(claim)) - if err = ctrl.bind(volume, claim); err != nil { - // On any error saving the volume or the claim, subsequent - // syncClaim will finish the binding. - return err - } - // OBSERVATION: pvc is "Bound", pv is "Bound" - return nil - } else if isVolumeBoundToClaim(volume, claim) { - // User asked for a PV that is claimed by this PVC - // OBSERVATION: pvc is "Pending", pv is "Bound" - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound, finishing the binding", claimToClaimKey(claim)) - // Finish the volume binding by adding claim UID. - if err = ctrl.bind(volume, claim); err != nil { - return err - } - // OBSERVATION: pvc is "Bound", pv is "Bound" - return nil - } else { - // User asked for a PV that is claimed by someone else - // OBSERVATION: pvc is "Pending", pv is "Bound" - if !hasAnnotation(claim.ObjectMeta, annBoundByController) { - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound to different claim by user, will retry later", claimToClaimKey(claim)) - // User asked for a specific PV, retry later - if _, err = ctrl.updateClaimStatus(claim, api.ClaimPending, nil); err != nil { - return err - } - return nil - } else { - // This should never happen because someone had to remove - // annBindCompleted annotation on the claim. - glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound to different claim %q by controller, THIS SHOULD NEVER HAPPEN", claimToClaimKey(claim), claimrefToClaimKey(volume.Spec.ClaimRef)) - return fmt.Errorf("Invalid binding of claim %q to volume %q: volume already claimed by %q", claimToClaimKey(claim), claim.Spec.VolumeName, claimrefToClaimKey(volume.Spec.ClaimRef)) - } - } + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: no volume found", claimToClaimKey(claim)) + // No PV could be found + // OBSERVATION: pvc is "Pending", will retry + if hasAnnotation(claim.ObjectMeta, annClass) { + return ctrl.provisionClaim(claim) } + // Mark the claim as Pending and try to find a match in the next periodic syncClaim + _, err = ctrl.updateClaimPhase(claim, api.ClaimPending) + return err + } + + /* pvc.Spec.VolumeName != nil */ + // [Unit test set 2] + // User asked for a specific PV. + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested", claimToClaimKey(claim), claim.Spec.VolumeName) + obj, found, err := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName) + if err != nil { + return err } + if !found { + // User asked for a PV that does not exist. + // OBSERVATION: pvc is "Pending" + // Retry later. + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested and not found, will try again next time", claimToClaimKey(claim), claim.Spec.VolumeName) + _, err = ctrl.updateClaimPhase(claim, api.ClaimPending) + return err + } + + volume, ok := obj.(*api.PersistentVolume) + if !ok { + return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %+v", claim.Spec.VolumeName, obj) + } + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume %q requested and found: %s", claimToClaimKey(claim), claim.Spec.VolumeName, getVolumeStatusForLogging(volume)) + + if volume.Spec.ClaimRef == nil { + // User asked for a PV that is not claimed + // OBSERVATION: pvc is "Pending", pv is "Available" + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume is unbound, binding", claimToClaimKey(claim)) + + // On any error saving the volume or the claim, subsequent + // syncClaim will finish the binding. + // OBSERVATION: pvc is "Bound", pv is "Bound" when no error + return ctrl.bind(volume, claim) + } + + if isVolumeBoundToClaim(volume, claim) { + // User asked for a PV that is claimed by this PVC + // OBSERVATION: pvc is "Pending", pv is "Bound" + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound, finishing the binding", claimToClaimKey(claim)) + + // Finish the volume binding by adding claim UID. + // OBSERVATION: pvc is "Bound", pv is "Bound" when no error + return ctrl.bind(volume, claim) + } + + // User asked for a PV that is claimed by someone else + // OBSERVATION: pvc is "Pending", pv is "Bound" + if !hasAnnotation(claim.ObjectMeta, annBoundByController) { + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound to different claim by user, will retry later", claimToClaimKey(claim)) + // User asked for a specific PV, retry later + _, err = ctrl.updateClaimPhase(claim, api.ClaimPending) + return err + } + + // This should never happen because someone had to remove + // annBindCompleted annotation on the claim. + glog.V(4).Infof("synchronizing unbound PersistentVolumeClaim[%s]: volume already bound to different claim %q by controller, THIS SHOULD NEVER HAPPEN", claimToClaimKey(claim), claimrefToClaimKey(volume.Spec.ClaimRef)) + return fmt.Errorf("Invalid binding of claim %q to volume %q: volume already claimed by %q", claimToClaimKey(claim), claim.Spec.VolumeName, claimrefToClaimKey(volume.Spec.ClaimRef)) } // syncBoundClaim is the main controller method to decide what to do with a @@ -272,60 +258,55 @@ func (ctrl *PersistentVolumeController) syncBoundClaim(claim *api.PersistentVolu // [Unit test set 3] if claim.Spec.VolumeName == "" { // Claim was bound before but not any more. - if _, err := ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimLost", "Bound claim has lost reference to PersistentVolume. Data on the volume is lost!"); err != nil { - return err - } - return nil + _, err := ctrl.updateClaimPhaseWithEvent(claim, api.ClaimLost, api.EventTypeWarning, "ClaimLost", "Bound claim has lost reference to PersistentVolume. Data on the volume is lost!") + return err } + obj, found, err := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName) if err != nil { return err } if !found { // Claim is bound to a non-existing volume. - if _, err = ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimLost", "Bound claim has lost its PersistentVolume. Data on the volume is lost!"); err != nil { + _, err = ctrl.updateClaimPhaseWithEvent(claim, api.ClaimLost, api.EventTypeWarning, "ClaimLost", "Bound claim has lost its PersistentVolume. Data on the volume is lost!") + return err + } + volume, ok := obj.(*api.PersistentVolume) + if !ok { + return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %+v", claim.Spec.VolumeName, obj) + } + + glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: volume %q found: %s", claimToClaimKey(claim), claim.Spec.VolumeName, getVolumeStatusForLogging(volume)) + if volume.Spec.ClaimRef == nil { + // Claim is bound but volume has come unbound. + // Or, a claim was bound and the controller has not received updated + // volume yet. We can't distinguish these cases. + // Bind the volume again and set all states to Bound. + glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: volume is unbound, fixing", claimToClaimKey(claim)) + if err = ctrl.bind(volume, claim); err != nil { + // Objects not saved, next syncPV or syncClaim will try again return err } return nil - } else { - volume, ok := obj.(*api.PersistentVolume) - if !ok { - return fmt.Errorf("Cannot convert object from volume cache to volume %q!?: %+v", claim.Spec.VolumeName, obj) - } - - glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: volume %q found: %s", claimToClaimKey(claim), claim.Spec.VolumeName, getVolumeStatusForLogging(volume)) - if volume.Spec.ClaimRef == nil { - // Claim is bound but volume has come unbound. - // Or, a claim was bound and the controller has not received updated - // volume yet. We can't distinguish these cases. - // Bind the volume again and set all states to Bound. - glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: volume is unbound, fixing", claimToClaimKey(claim)) - if err = ctrl.bind(volume, claim); err != nil { - // Objects not saved, next syncPV or syncClaim will try again - return err - } - return nil - } else if volume.Spec.ClaimRef.UID == claim.UID { - // All is well - // NOTE: syncPV can handle this so it can be left out. - // NOTE: bind() call here will do nothing in most cases as - // everything should be already set. - glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: claim is already correctly bound", claimToClaimKey(claim)) - if err = ctrl.bind(volume, claim); err != nil { - // Objects not saved, next syncPV or syncClaim will try again - return err - } - return nil - } else { - // Claim is bound but volume has a different claimant. - // Set the claim phase to 'Lost', which is a terminal - // phase. - if _, err = ctrl.updateClaimStatusWithEvent(claim, api.ClaimLost, nil, api.EventTypeWarning, "ClaimMisbound", "Two claims are bound to the same volume, this one is bound incorrectly"); err != nil { - return err - } - return nil + } + if volume.Spec.ClaimRef.UID == claim.UID { + // All is well + // NOTE: syncPV can handle this so it can be left out. + // NOTE: bind() call here will do nothing in most cases as + // everything should be already set. + glog.V(4).Infof("synchronizing bound PersistentVolumeClaim[%s]: claim is already correctly bound", claimToClaimKey(claim)) + if err = ctrl.bind(volume, claim); err != nil { + // Objects not saved, next syncPV or syncClaim will try again + return err } + return nil } + + // Claim is bound but volume has a different claimant. + // Set the claim phase to 'Lost', which is a terminal + // phase. + _, err = ctrl.updateClaimPhaseWithEvent(claim, api.ClaimLost, api.EventTypeWarning, "ClaimMisbound", "Two claims are bound to the same volume, this one is bound incorrectly") + return err } // syncVolume is the main controller method to decide what to do with a volume. @@ -483,15 +464,14 @@ func (ctrl *PersistentVolumeController) syncVolume(volume *api.PersistentVolume) } } -// updateClaimStatus saves new claim.Status to API server. -// Parameters: -// claim - claim to update -// phasephase - phase to set -// volume - volume which Capacity is set into claim.Status.Capacity -func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase, volume *api.PersistentVolume) (*api.PersistentVolumeClaim, error) { - glog.V(4).Infof("updating PersistentVolumeClaim[%s] status: set phase %s", claimToClaimKey(claim), phase) - - dirty := false +// updateClaimPhase saves new claim phase to API server. +func (ctrl *PersistentVolumeController) updateClaimPhase(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase) (*api.PersistentVolumeClaim, error) { + glog.V(4).Infof("updating PersistentVolumeClaim[%s]: set phase %s", claimToClaimKey(claim), phase) + if claim.Status.Phase == phase { + // Nothing to do. + glog.V(4).Infof("updating PersistentVolumeClaim[%s]: phase %s already set", claimToClaimKey(claim), phase) + return claim, nil + } clone, err := conversion.NewCloner().DeepCopy(claim) if err != nil { @@ -502,76 +482,33 @@ func (ctrl *PersistentVolumeController) updateClaimStatus(claim *api.PersistentV return nil, fmt.Errorf("Unexpected claim cast error : %v", claimClone) } - if claim.Status.Phase != phase { - claimClone.Status.Phase = phase - dirty = true - } - - if volume == nil { - // Need to reset AccessModes and Capacity - if claim.Status.AccessModes != nil { - claimClone.Status.AccessModes = nil - dirty = true - } - if claim.Status.Capacity != nil { - claimClone.Status.Capacity = nil - dirty = true - } - } else { - // Need to update AccessModes and Capacity - if !reflect.DeepEqual(claim.Status.AccessModes, volume.Spec.AccessModes) { - claimClone.Status.AccessModes = volume.Spec.AccessModes - dirty = true - } - - volumeCap, ok := volume.Spec.Capacity[api.ResourceStorage] - if !ok { - return nil, fmt.Errorf("PersistentVolume %q is without a storage capacity", volume.Name) - } - claimCap, ok := claim.Status.Capacity[api.ResourceStorage] - if !ok || volumeCap.Cmp(claimCap) != 0 { - claimClone.Status.Capacity = volume.Spec.Capacity - dirty = true - } - } - - if !dirty { - // Nothing to do. - glog.V(4).Infof("updating PersistentVolumeClaim[%s] status: phase %s already set", claimToClaimKey(claim), phase) - return claim, nil - } - + claimClone.Status.Phase = phase newClaim, err := ctrl.kubeClient.Core().PersistentVolumeClaims(claimClone.Namespace).UpdateStatus(claimClone) if err != nil { - glog.V(4).Infof("updating PersistentVolumeClaim[%s] status: set phase %s failed: %v", claimToClaimKey(claim), phase, err) + glog.V(4).Infof("updating PersistentVolumeClaim[%s]: set phase %s failed: %v", claimToClaimKey(claim), phase, err) return newClaim, err } _, err = ctrl.storeClaimUpdate(newClaim) if err != nil { - glog.V(4).Infof("updating PersistentVolumeClaim[%s] status: cannot update internal cache: %v", claimToClaimKey(claim), err) + glog.V(4).Infof("updating PersistentVolumeClaim[%s]: cannot update internal cache: %v", claimToClaimKey(claim), err) return newClaim, err } glog.V(2).Infof("claim %q entered phase %q", claimToClaimKey(claim), phase) return newClaim, nil } -// updateClaimStatusWithEvent saves new claim.Status to API server and emits -// given event on the claim. It saves the status and emits the event only when -// the status has actually changed from the version saved in API server. -// Parameters: -// claim - claim to update -// phasephase - phase to set -// volume - volume which Capacity is set into claim.Status.Capacity -// eventtype, reason, message - event to send, see EventRecorder.Event() -func (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase, volume *api.PersistentVolume, eventtype, reason, message string) (*api.PersistentVolumeClaim, error) { - glog.V(4).Infof("updating updateClaimStatusWithEvent[%s]: set phase %s", claimToClaimKey(claim), phase) +// updateClaimPhaseWithEvent saves new claim phase to API server and emits given +// event on the claim. It saves the phase and emits the event only when the +// phase has actually changed from the version saved in API server. +func (ctrl *PersistentVolumeController) updateClaimPhaseWithEvent(claim *api.PersistentVolumeClaim, phase api.PersistentVolumeClaimPhase, eventtype, reason, message string) (*api.PersistentVolumeClaim, error) { + glog.V(4).Infof("updating updateClaimPhaseWithEvent[%s]: set phase %s", claimToClaimKey(claim), phase) if claim.Status.Phase == phase { // Nothing to do. - glog.V(4).Infof("updating updateClaimStatusWithEvent[%s]: phase %s already set", claimToClaimKey(claim), phase) + glog.V(4).Infof("updating updateClaimPhaseWithEvent[%s]: phase %s already set", claimToClaimKey(claim), phase) return claim, nil } - newClaim, err := ctrl.updateClaimStatus(claim, phase, volume) + newClaim, err := ctrl.updateClaimPhase(claim, phase) if err != nil { return nil, err } @@ -801,7 +738,7 @@ func (ctrl *PersistentVolumeController) bind(volume *api.PersistentVolume, claim } claim = updatedClaim - if updatedClaim, err = ctrl.updateClaimStatus(claim, api.ClaimBound, volume); err != nil { + if updatedClaim, err = ctrl.updateClaimPhase(claim, api.ClaimBound); err != nil { glog.V(3).Infof("error binding volume %q to claim %q: failed saving the claim status: %v", volume.Name, claimToClaimKey(claim), err) return err } diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller_base.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller_base.go index 67a70b2f39e8..88b5b139ac10 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller_base.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/controller_base.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/index.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/index.go index 1d4df66e4f30..60699e6e653e 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/index.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/index.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/volume_host.go b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/volume_host.go index 28bef72bf5b5..23915c22d42e 100644 --- a/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/volume_host.go +++ b/vendor/k8s.io/kubernetes/pkg/controller/volume/persistentvolume/volume_host.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/cloner.go b/vendor/k8s.io/kubernetes/pkg/conversion/cloner.go index a8c574713275..c5dec1f31e41 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/cloner.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/cloner.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,14 +25,14 @@ import ( type Cloner struct { // Map from the type to a function which can do the deep copy. deepCopyFuncs map[reflect.Type]reflect.Value - generatedDeepCopyFuncs map[reflect.Type]reflect.Value + generatedDeepCopyFuncs map[reflect.Type]func(in interface{}, out interface{}, c *Cloner) error } // NewCloner creates a new Cloner object. func NewCloner() *Cloner { c := &Cloner{ deepCopyFuncs: map[reflect.Type]reflect.Value{}, - generatedDeepCopyFuncs: map[reflect.Type]reflect.Value{}, + generatedDeepCopyFuncs: map[reflect.Type]func(in interface{}, out interface{}, c *Cloner) error{}, } if err := c.RegisterDeepCopyFunc(byteSliceDeepCopy); err != nil { // If one of the deep-copy functions is malformed, detect it immediately. @@ -42,10 +42,10 @@ func NewCloner() *Cloner { } // Prevent recursing into every byte... -func byteSliceDeepCopy(in []byte, out *[]byte, c *Cloner) error { - if in != nil { - *out = make([]byte, len(in)) - copy(*out, in) +func byteSliceDeepCopy(in *[]byte, out *[]byte, c *Cloner) error { + if *in != nil { + *out = make([]byte, len(*in)) + copy(*out, *in) } else { *out = nil } @@ -63,10 +63,10 @@ func verifyDeepCopyFunctionSignature(ft reflect.Type) error { if ft.NumOut() != 1 { return fmt.Errorf("expected one 'out' param, got %v", ft) } - if ft.In(1).Kind() != reflect.Ptr { - return fmt.Errorf("expected pointer arg for 'in' param 1, got: %v", ft) + if ft.In(0).Kind() != reflect.Ptr { + return fmt.Errorf("expected pointer arg for 'in' param 0, got: %v", ft) } - if ft.In(1).Elem() != ft.In(0) { + if ft.In(1) != ft.In(0) { return fmt.Errorf("expected 'in' param 0 the same as param 1, got: %v", ft) } var forClonerType Cloner @@ -103,15 +103,17 @@ func (c *Cloner) RegisterDeepCopyFunc(deepCopyFunc interface{}) error { return nil } +// GeneratedDeepCopyFunc bundles an untyped generated deep-copy function of a type +// with a reflection type object used as a key to lookup the deep-copy function. +type GeneratedDeepCopyFunc struct { + Fn func(in interface{}, out interface{}, c *Cloner) error + InType reflect.Type +} + // Similar to RegisterDeepCopyFunc, but registers deep copy function that were // automatically generated. -func (c *Cloner) RegisterGeneratedDeepCopyFunc(deepCopyFunc interface{}) error { - fv := reflect.ValueOf(deepCopyFunc) - ft := fv.Type() - if err := verifyDeepCopyFunctionSignature(ft); err != nil { - return err - } - c.generatedDeepCopyFuncs[ft.In(0)] = fv +func (c *Cloner) RegisterGeneratedDeepCopyFunc(fn GeneratedDeepCopyFunc) error { + c.generatedDeepCopyFuncs[fn.InType] = fn.Fn return nil } @@ -135,25 +137,35 @@ func (c *Cloner) DeepCopy(in interface{}) (interface{}, error) { func (c *Cloner) deepCopy(src reflect.Value) (reflect.Value, error) { inType := src.Type() + switch src.Kind() { + case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + if src.IsNil() { + return src, nil + } + } + if fv, ok := c.deepCopyFuncs[inType]; ok { return c.customDeepCopy(src, fv) } if fv, ok := c.generatedDeepCopyFuncs[inType]; ok { - return c.customDeepCopy(src, fv) + var outValue reflect.Value + outValue = reflect.New(inType.Elem()) + err := fv(src.Interface(), outValue.Interface(), c) + return outValue, err } return c.defaultDeepCopy(src) } func (c *Cloner) customDeepCopy(src, fv reflect.Value) (reflect.Value, error) { - outValue := reflect.New(src.Type()) + outValue := reflect.New(src.Type().Elem()) args := []reflect.Value{src, outValue, reflect.ValueOf(c)} result := fv.Call(args)[0].Interface() // This convolution is necessary because nil interfaces won't convert // to error. if result == nil { - return outValue.Elem(), nil + return outValue, nil } - return outValue.Elem(), result.(error) + return outValue, result.(error) } func (c *Cloner) defaultDeepCopy(src reflect.Value) (reflect.Value, error) { diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/converter.go b/vendor/k8s.io/kubernetes/pkg/conversion/converter.go index e045dcd2f77c..7a18d6360f53 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/converter.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/converter.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/deep_equal.go b/vendor/k8s.io/kubernetes/pkg/conversion/deep_equal.go index 7c3ed7cda130..6bfc870a3703 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/deep_equal.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/deep_equal.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ limitations under the License. package conversion import ( - "k8s.io/kubernetes/third_party/forked/reflect" + "k8s.io/kubernetes/third_party/forked/golang/reflect" ) // The code for this type must be located in third_party, since it forks from @@ -26,7 +26,7 @@ type Equalities struct { reflect.Equalities } -// For convenience, panics on errrors +// For convenience, panics on errors func EqualitiesOrDie(funcs ...interface{}) Equalities { e := Equalities{reflect.Equalities{}} if err := e.AddFuncs(funcs...); err != nil { diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/doc.go b/vendor/k8s.io/kubernetes/pkg/conversion/doc.go index 3ef2eaba4576..0c46ef2d169e 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/helper.go b/vendor/k8s.io/kubernetes/pkg/conversion/helper.go index 39f78265959b..4ebc1ebc511f 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/helper.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/helper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go b/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go index 63c5456976e7..30f717b2cecb 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/convert.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/doc.go b/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/doc.go index 0e9127a18996..4c1002a4c1d8 100644 --- a/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/conversion/queryparams/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go index 3b9b5c9820d2..d218f71c613d 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/aws/aws_credentials.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ var AWSRegions = [...]string{ "us-west-2", "eu-west-1", "eu-central-1", + "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go index b80fa5945ca6..582c1ef277f8 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go index f071c0c8935e..41c12410f05e 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go index e6f2beba8041..09a0b9d5bb66 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go index e4c16afa85fe..b34c0fcaaf05 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/jwt.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go index c1d80163f57c..0767e1c60401 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/gcp/metadata.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/credentialprovider" + utilnet "k8s.io/kubernetes/pkg/util/net" ) const ( @@ -82,10 +83,16 @@ type containerRegistryProvider struct { // init registers the various means by which credentials may // be resolved on GCP. func init() { + tr := utilnet.SetTransportDefaults(&http.Transport{}) + metadataHTTPClientTimeout := time.Second * 10 + httpClient := &http.Client{ + Transport: tr, + Timeout: metadataHTTPClientTimeout, + } credentialprovider.RegisterCredentialProvider("google-dockercfg", &credentialprovider.CachingDockerConfigProvider{ Provider: &dockerConfigKeyProvider{ - metadataProvider{Client: http.DefaultClient}, + metadataProvider{Client: httpClient}, }, Lifetime: 60 * time.Second, }) @@ -93,7 +100,7 @@ func init() { credentialprovider.RegisterCredentialProvider("google-dockercfg-url", &credentialprovider.CachingDockerConfigProvider{ Provider: &dockerConfigUrlKeyProvider{ - metadataProvider{Client: http.DefaultClient}, + metadataProvider{Client: httpClient}, }, Lifetime: 60 * time.Second, }) @@ -102,7 +109,7 @@ func init() { // Never cache this. The access token is already // cached by the metadata service. &containerRegistryProvider{ - metadataProvider{Client: http.DefaultClient}, + metadataProvider{Client: httpClient}, }) } diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go index eedbee5ad8f7..ed712ccfdc7b 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/plugins.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/plugins.go index a871cc02bcd9..76c2e724901c 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go b/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go index 8df116314b61..cb93bd7fb21c 100644 --- a/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go +++ b/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/fieldpath/doc.go b/vendor/k8s.io/kubernetes/pkg/fieldpath/doc.go index c91ff6ecaba5..83cbdce0c84e 100644 --- a/vendor/k8s.io/kubernetes/pkg/fieldpath/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/fieldpath/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath.go b/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath.go index bede9b2c0bfa..4de70460bc67 100644 --- a/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath.go +++ b/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/fields/doc.go b/vendor/k8s.io/kubernetes/pkg/fields/doc.go index 767615c9f7bd..49059e263526 100644 --- a/vendor/k8s.io/kubernetes/pkg/fields/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/fields/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/fields/fields.go b/vendor/k8s.io/kubernetes/pkg/fields/fields.go index 50fef14a8171..623b27e95715 100644 --- a/vendor/k8s.io/kubernetes/pkg/fields/fields.go +++ b/vendor/k8s.io/kubernetes/pkg/fields/fields.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/fields/selector.go b/vendor/k8s.io/kubernetes/pkg/fields/selector.go index c0a6385818aa..eef44d356307 100644 --- a/vendor/k8s.io/kubernetes/pkg/fields/selector.go +++ b/vendor/k8s.io/kubernetes/pkg/fields/selector.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/default_storage_factory_builder.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/default_storage_factory_builder.go index ef727662a86d..db9d07e9c7dd 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/default_storage_factory_builder.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/default_storage_factory_builder.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/doc.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/doc.go index 12238d568ebf..c4abd9097c12 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/genericapiserver.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/genericapiserver.go index 9d7fe36068d2..9b0cc5baf23a 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/genericapiserver.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/genericapiserver.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -372,16 +372,14 @@ func New(c *Config) (*GenericAPIServer, error) { apiGroupsForDiscovery: map[string]unversioned.APIGroup{}, } - var handlerContainer *restful.Container if c.RestfulContainer != nil { s.mux = c.RestfulContainer.ServeMux - handlerContainer = c.RestfulContainer + s.HandlerContainer = c.RestfulContainer } else { mux := http.NewServeMux() s.mux = mux - handlerContainer = NewHandlerContainer(mux, c.Serializer) + s.HandlerContainer = NewHandlerContainer(mux, c.Serializer) } - s.HandlerContainer = handlerContainer // Use CurlyRouter to be able to use regular expressions in paths. Regular expressions are required in paths for example for proxy (where the path is proxy/{kind}/{name}/{*}) s.HandlerContainer.Router(restful.CurlyRouter{}) s.MuxHelper = &apiserver.MuxHelper{Mux: s.mux, RegisteredPaths: []string{}} @@ -491,13 +489,13 @@ func (s *GenericAPIServer) init(c *Config) { // After all wrapping is done, put a context filter around both handlers if handler, err := api.NewRequestContextFilter(s.RequestContextMapper, s.Handler); err != nil { - glog.Fatalf("Could not initialize request context filter: %v", err) + glog.Fatalf("Could not initialize request context filter for s.Handler: %v", err) } else { s.Handler = handler } if handler, err := api.NewRequestContextFilter(s.RequestContextMapper, s.InsecureHandler); err != nil { - glog.Fatalf("Could not initialize request context filter: %v", err) + glog.Fatalf("Could not initialize request context filter for s.InsecureHandler: %v", err) } else { s.InsecureHandler = handler } @@ -572,6 +570,10 @@ func NewConfig(options *options.ServerRunOptions) *Config { } func verifyServiceNodePort(options *options.ServerRunOptions) { + if options.KubernetesServiceNodePort < 0 || options.KubernetesServiceNodePort > 65535 { + glog.Fatalf("--kubernetes-service-node-port %v must be between 0 and 65535, inclusive. If 0, the Kubernetes master service will be of type ClusterIP.", options.KubernetesServiceNodePort) + } + if options.KubernetesServiceNodePort > 0 && !options.ServiceNodePortRange.Contains(options.KubernetesServiceNodePort) { glog.Fatalf("Kubernetes service port range %v doesn't contain %v", options.ServiceNodePortRange, (options.KubernetesServiceNodePort)) } @@ -583,10 +585,25 @@ func verifyEtcdServersList(options *options.ServerRunOptions) { } } +func verifySecurePort(options *options.ServerRunOptions) { + if options.SecurePort < 0 || options.SecurePort > 65535 { + glog.Fatalf("--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port.", options.SecurePort) + } +} + +// TODO: Allow 0 to turn off insecure port. +func verifyInsecurePort(options *options.ServerRunOptions) { + if options.InsecurePort < 1 || options.InsecurePort > 65535 { + glog.Fatalf("--insecure-port %v must be between 1 and 65535, inclusive.", options.InsecurePort) + } +} + func ValidateRunOptions(options *options.ServerRunOptions) { verifyClusterIPFlags(options) verifyServiceNodePort(options) verifyEtcdServersList(options) + verifySecurePort(options) + verifyInsecurePort(options) } func DefaultAndValidateRunOptions(options *options.ServerRunOptions) { @@ -639,7 +656,7 @@ func (s *GenericAPIServer) Run(options *options.ServerRunOptions) { if s.enableSwaggerSupport { s.InstallSwaggerAPI() } - // We serve on 2 ports. See docs/accessing_the_api.md + // We serve on 2 ports. See docs/admin/accessing-the-api.md secureLocation := "" if options.SecurePort != 0 { secureLocation = net.JoinHostPort(options.BindAddress.String(), strconv.Itoa(options.SecurePort)) @@ -731,8 +748,18 @@ func (s *GenericAPIServer) Run(options *options.ServerRunOptions) { Handler: apiserver.RecoverPanics(handler), MaxHeaderBytes: 1 << 20, } + glog.Infof("Serving insecurely on %s", insecureLocation) - glog.Fatal(http.ListenAndServe()) + go func() { + defer utilruntime.HandleCrash() + for { + if err := http.ListenAndServe(); err != nil { + glog.Errorf("Unable to listen for insecure (%v); will try again.", err) + } + time.Sleep(15 * time.Second) + } + }() + select {} } // Exposes the given group version in API. @@ -837,30 +864,30 @@ func (s *GenericAPIServer) getAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupV for k, v := range apiGroupInfo.VersionedResourcesStorageMap[groupVersion.Version] { storage[strings.ToLower(k)] = v } - version, err := s.newAPIGroupVersion(apiGroupInfo.GroupMeta, groupVersion) + version, err := s.newAPIGroupVersion(apiGroupInfo, groupVersion) version.Root = apiPrefix version.Storage = storage - version.ParameterCodec = apiGroupInfo.ParameterCodec - version.Serializer = apiGroupInfo.NegotiatedSerializer - version.Creater = apiGroupInfo.Scheme - version.Convertor = apiGroupInfo.Scheme - version.Copier = apiGroupInfo.Scheme - version.Typer = apiGroupInfo.Scheme - version.SubresourceGroupVersionKind = apiGroupInfo.SubresourceGroupVersionKind return version, err } -func (s *GenericAPIServer) newAPIGroupVersion(groupMeta apimachinery.GroupMeta, groupVersion unversioned.GroupVersion) (*apiserver.APIGroupVersion, error) { +func (s *GenericAPIServer) newAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion unversioned.GroupVersion) (*apiserver.APIGroupVersion, error) { return &apiserver.APIGroupVersion{ RequestInfoResolver: s.NewRequestInfoResolver(), GroupVersion: groupVersion, - Linker: groupMeta.SelfLinker, - Mapper: groupMeta.RESTMapper, - - Admit: s.AdmissionControl, - Context: s.RequestContextMapper, + ParameterCodec: apiGroupInfo.ParameterCodec, + Serializer: apiGroupInfo.NegotiatedSerializer, + Creater: apiGroupInfo.Scheme, + Convertor: apiGroupInfo.Scheme, + Copier: apiGroupInfo.Scheme, + Typer: apiGroupInfo.Scheme, + SubresourceGroupVersionKind: apiGroupInfo.SubresourceGroupVersionKind, + Linker: apiGroupInfo.GroupMeta.SelfLinker, + Mapper: apiGroupInfo.GroupMeta.RESTMapper, + + Admit: s.AdmissionControl, + Context: s.RequestContextMapper, MinRequestTimeout: s.MinRequestTimeout, }, nil } @@ -881,6 +908,13 @@ func (s *GenericAPIServer) InstallSwaggerAPI() { ApiPath: "/swaggerapi/", SwaggerPath: "/swaggerui/", SwaggerFilePath: "/swagger-ui/", + SchemaFormatHandler: func(typeName string) string { + switch typeName { + case "unversioned.Time", "*unversioned.Time": + return "date-time" + } + return "" + }, } swagger.RegisterSwaggerService(swaggerConfig, s.HandlerContainer) } diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/doc.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/doc.go index c90eb8b8d1b2..a7167a419e9a 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/server_run_options.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/server_run_options.go index a1c6b26111f5..ea42f53489da 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/server_run_options.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/options/server_run_options.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -133,6 +133,7 @@ func NewServerRunOptions() *ServerRunOptions { MinRequestTimeout: 1800, RuntimeConfig: make(config.ConfigurationMap), SecurePort: 6443, + ServiceNodePortRange: utilnet.PortRange{Base: 30000, Size: 2768}, StorageVersions: registered.AllPreferredGroupVersions(), } } @@ -212,8 +213,12 @@ func (s *ServerRunOptions) AddFlags(fs *pflag.FlagSet) { // Note: the weird ""+ in below lines seems to be the only way to get gofmt to // arrange these text blocks sensibly. Grrr. - fs.StringVar(&s.AdmissionControl, "admission-control", s.AdmissionControl, "Ordered list of plug-ins to do admission control of resources into cluster. Comma-delimited list of: "+strings.Join(admission.GetPlugins(), ", ")) - fs.StringVar(&s.AdmissionControlConfigFile, "admission-control-config-file", s.AdmissionControlConfigFile, "File with admission control configuration.") + fs.StringVar(&s.AdmissionControl, "admission-control", s.AdmissionControl, ""+ + "Ordered list of plug-ins to do admission control of resources into cluster. "+ + "Comma-delimited list of: "+strings.Join(admission.GetPlugins(), ", ")+".") + + fs.StringVar(&s.AdmissionControlConfigFile, "admission-control-config-file", s.AdmissionControlConfigFile, + "File with admission control configuration.") fs.IPVar(&s.AdvertiseAddress, "advertise-address", s.AdvertiseAddress, ""+ "The IP address on which to advertise the apiserver to members of the cluster. This "+ @@ -221,124 +226,229 @@ func (s *ServerRunOptions) AddFlags(fs *pflag.FlagSet) { "will be used. If --bind-address is unspecified, the host's default interface will "+ "be used.") - fs.StringVar(&s.AuthorizationMode, "authorization-mode", s.AuthorizationMode, "Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: "+strings.Join(apiserver.AuthorizationModeChoices, ",")) + fs.StringVar(&s.AuthorizationMode, "authorization-mode", s.AuthorizationMode, ""+ + "Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: "+ + strings.Join(apiserver.AuthorizationModeChoices, ",")+".") + + fs.StringVar(&s.AuthorizationConfig.PolicyFile, "authorization-policy-file", s.AuthorizationConfig.PolicyFile, ""+ + "File with authorization policy in csv format, used with --authorization-mode=ABAC, on the secure port.") + + fs.StringVar(&s.AuthorizationConfig.WebhookConfigFile, "authorization-webhook-config-file", s.AuthorizationConfig.WebhookConfigFile, ""+ + "File with webhook configuration in kubeconfig format, used with --authorization-mode=Webhook. "+ + "The API server will query the remote service to determine access on the API server's secure port.") + + fs.DurationVar(&s.AuthorizationConfig.WebhookCacheAuthorizedTTL, "authorization-webhook-cache-authorized-ttl", + s.AuthorizationConfig.WebhookCacheAuthorizedTTL, + "The duration to cache 'authorized' responses from the webhook authorizer. Default is 5m.") - fs.StringVar(&s.AuthorizationConfig.PolicyFile, "authorization-policy-file", s.AuthorizationConfig.PolicyFile, "File with authorization policy in csv format, used with --authorization-mode=ABAC, on the secure port.") - fs.StringVar(&s.AuthorizationConfig.WebhookConfigFile, "authorization-webhook-config-file", s.AuthorizationConfig.WebhookConfigFile, "File with webhook configuration in kubeconfig format, used with --authorization-mode=Webhook. The API server will query the remote service to determine access on the API server's secure port.") - fs.DurationVar(&s.AuthorizationConfig.WebhookCacheAuthorizedTTL, "authorization-webhook-cache-authorized-ttl", s.AuthorizationConfig.WebhookCacheAuthorizedTTL, "The duration to cache 'authorized' responses from the webhook authorizer. Default is 5m.") - fs.DurationVar(&s.AuthorizationConfig.WebhookCacheUnauthorizedTTL, "authorization-webhook-cache-unauthorized-ttl", s.AuthorizationConfig.WebhookCacheUnauthorizedTTL, "The duration to cache 'unauthorized' responses from the webhook authorizer. Default is 30s.") - fs.StringVar(&s.AuthorizationConfig.RBACSuperUser, "authorization-rbac-super-user", s.AuthorizationConfig.RBACSuperUser, "If specified, a username which avoids RBAC authorization checks and role binding privilege escalation checks, to be used with --authorization-mode=RBAC.") + fs.DurationVar(&s.AuthorizationConfig.WebhookCacheUnauthorizedTTL, + "authorization-webhook-cache-unauthorized-ttl", s.AuthorizationConfig.WebhookCacheUnauthorizedTTL, + "The duration to cache 'unauthorized' responses from the webhook authorizer. Default is 30s.") - fs.StringVar(&s.BasicAuthFile, "basic-auth-file", s.BasicAuthFile, "If set, the file that will be used to admit requests to the secure port of the API server via http basic authentication.") + fs.StringVar(&s.AuthorizationConfig.RBACSuperUser, "authorization-rbac-super-user", s.AuthorizationConfig.RBACSuperUser, ""+ + "If specified, a username which avoids RBAC authorization checks and role binding "+ + "privilege escalation checks, to be used with --authorization-mode=RBAC.") + + fs.StringVar(&s.BasicAuthFile, "basic-auth-file", s.BasicAuthFile, ""+ + "If set, the file that will be used to admit requests to the secure port of the API server "+ + "via http basic authentication.") + + fs.IPVar(&s.BindAddress, "public-address-override", s.BindAddress, + "DEPRECATED: see --bind-address instead.") + fs.MarkDeprecated("public-address-override", "see --bind-address instead.") - fs.IPVar(&s.BindAddress, "public-address-override", s.BindAddress, "DEPRECATED: see --bind-address instead") - fs.MarkDeprecated("public-address-override", "see --bind-address instead") fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, ""+ "The IP address on which to listen for the --secure-port port. The "+ "associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+ "clients. If blank, all interfaces will be used (0.0.0.0).") - fs.StringVar(&s.CertDirectory, "cert-dir", s.CertDirectory, "The directory where the TLS certs are located (by default /var/run/kubernetes). "+ + fs.StringVar(&s.CertDirectory, "cert-dir", s.CertDirectory, ""+ + "The directory where the TLS certs are located (by default /var/run/kubernetes). "+ "If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.") - fs.StringVar(&s.ClientCAFile, "client-ca-file", s.ClientCAFile, "If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file is authenticated with an identity corresponding to the CommonName of the client certificate.") + fs.StringVar(&s.ClientCAFile, "client-ca-file", s.ClientCAFile, ""+ + "If set, any request presenting a client certificate signed by one of "+ + "the authorities in the client-ca-file is authenticated with an identity "+ + "corresponding to the CommonName of the client certificate.") + + fs.StringVar(&s.CloudProvider, "cloud-provider", s.CloudProvider, + "The provider for cloud services. Empty string for no provider.") - fs.StringVar(&s.CloudProvider, "cloud-provider", s.CloudProvider, "The provider for cloud services. Empty string for no provider.") - fs.StringVar(&s.CloudConfigFile, "cloud-config", s.CloudConfigFile, "The path to the cloud provider configuration file. Empty string for no configuration file.") + fs.StringVar(&s.CloudConfigFile, "cloud-config", s.CloudConfigFile, + "The path to the cloud provider configuration file. Empty string for no configuration file.") - fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, "List of allowed origins for CORS, comma separated. An allowed origin can be a regular expression to support subdomain matching. If this list is empty CORS will not be enabled.") + fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, ""+ + "List of allowed origins for CORS, comma separated. An allowed origin can be a regular "+ + "expression to support subdomain matching. If this list is empty CORS will not be enabled.") - fs.StringVar(&s.DefaultStorageMediaType, "storage-media-type", s.DefaultStorageMediaType, "The media type to use to store objects in storage. Defaults to application/json. Some resources may only support a specific media type and will ignore this setting.") + fs.StringVar(&s.DefaultStorageMediaType, "storage-media-type", s.DefaultStorageMediaType, ""+ + "The media type to use to store objects in storage. Defaults to application/json. "+ + "Some resources may only support a specific media type and will ignore this setting.") - fs.IntVar(&s.DeleteCollectionWorkers, "delete-collection-workers", s.DeleteCollectionWorkers, "Number of workers spawned for DeleteCollection call. These are used to speed up namespace cleanup.") + fs.IntVar(&s.DeleteCollectionWorkers, "delete-collection-workers", s.DeleteCollectionWorkers, + "Number of workers spawned for DeleteCollection call. These are used to speed up namespace cleanup.") - fs.BoolVar(&s.EnableProfiling, "profiling", s.EnableProfiling, "Enable profiling via web interface host:port/debug/pprof/") + fs.BoolVar(&s.EnableProfiling, "profiling", s.EnableProfiling, + "Enable profiling via web interface host:port/debug/pprof/") - fs.BoolVar(&s.EnableSwaggerUI, "enable-swagger-ui", s.EnableSwaggerUI, "Enables swagger ui on the apiserver at /swagger-ui") + fs.BoolVar(&s.EnableSwaggerUI, "enable-swagger-ui", s.EnableSwaggerUI, + "Enables swagger ui on the apiserver at /swagger-ui") // TODO: enable cache in integration tests. - fs.BoolVar(&s.EnableWatchCache, "watch-cache", s.EnableWatchCache, "Enable watch caching in the apiserver") + fs.BoolVar(&s.EnableWatchCache, "watch-cache", s.EnableWatchCache, + "Enable watch caching in the apiserver") - fs.StringSliceVar(&s.EtcdServersOverrides, "etcd-servers-overrides", s.EtcdServersOverrides, "Per-resource etcd servers overrides, comma separated. The individual override format: group/resource#servers, where servers are http://ip:port, semicolon separated.") + fs.StringSliceVar(&s.EtcdServersOverrides, "etcd-servers-overrides", s.EtcdServersOverrides, ""+ + "Per-resource etcd servers overrides, comma separated. The individual override "+ + "format: group/resource#servers, where servers are http://ip:port, semicolon separated.") - fs.StringVar(&s.ExternalHost, "external-hostname", s.ExternalHost, "The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs.)") + fs.StringVar(&s.ExternalHost, "external-hostname", s.ExternalHost, + "The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs).") fs.IPVar(&s.InsecureBindAddress, "insecure-bind-address", s.InsecureBindAddress, ""+ "The IP address on which to serve the --insecure-port (set to 0.0.0.0 for all interfaces). "+ "Defaults to localhost.") - fs.IPVar(&s.InsecureBindAddress, "address", s.InsecureBindAddress, "DEPRECATED: see --insecure-bind-address instead") - fs.MarkDeprecated("address", "see --insecure-bind-address instead") + fs.IPVar(&s.InsecureBindAddress, "address", s.InsecureBindAddress, + "DEPRECATED: see --insecure-bind-address instead.") + fs.MarkDeprecated("address", "see --insecure-bind-address instead.") fs.IntVar(&s.InsecurePort, "insecure-port", s.InsecurePort, ""+ "The port on which to serve unsecured, unauthenticated access. Default 8080. It is assumed "+ "that firewall rules are set up such that this port is not reachable from outside of "+ "the cluster and that port 443 on the cluster's public address is proxied to this "+ "port. This is performed by nginx in the default setup.") - fs.IntVar(&s.InsecurePort, "port", s.InsecurePort, "DEPRECATED: see --insecure-port instead") - fs.MarkDeprecated("port", "see --insecure-port instead") - fs.StringVar(&s.KeystoneURL, "experimental-keystone-url", s.KeystoneURL, "If passed, activates the keystone authentication plugin") + fs.IntVar(&s.InsecurePort, "port", s.InsecurePort, "DEPRECATED: see --insecure-port instead.") + fs.MarkDeprecated("port", "see --insecure-port instead.") - // See #14282 for details on how to test/try this option out. TODO remove this comment once this option is tested in CI. - fs.IntVar(&s.KubernetesServiceNodePort, "kubernetes-service-node-port", s.KubernetesServiceNodePort, "If non-zero, the Kubernetes master service (which apiserver creates/maintains) will be of type NodePort, using this as the value of the port. If zero, the Kubernetes master service will be of type ClusterIP.") + fs.StringVar(&s.KeystoneURL, "experimental-keystone-url", s.KeystoneURL, + "If passed, activates the keystone authentication plugin.") - fs.StringVar(&s.LongRunningRequestRE, "long-running-request-regexp", s.LongRunningRequestRE, "A regular expression matching long running requests which should be excluded from maximum inflight request handling.") + // See #14282 for details on how to test/try this option out. + // TODO: remove this comment once this option is tested in CI. + fs.IntVar(&s.KubernetesServiceNodePort, "kubernetes-service-node-port", s.KubernetesServiceNodePort, ""+ + "If non-zero, the Kubernetes master service (which apiserver creates/maintains) will be "+ + "of type NodePort, using this as the value of the port. If zero, the Kubernetes master "+ + "service will be of type ClusterIP.") - fs.IntVar(&s.MasterCount, "apiserver-count", s.MasterCount, "The number of apiservers running in the cluster") + fs.StringVar(&s.LongRunningRequestRE, "long-running-request-regexp", s.LongRunningRequestRE, ""+ + "A regular expression matching long running requests which should "+ + "be excluded from maximum inflight request handling.") - fs.StringVar(&s.MasterServiceNamespace, "master-service-namespace", s.MasterServiceNamespace, "The namespace from which the kubernetes master services should be injected into pods") + fs.IntVar(&s.MasterCount, "apiserver-count", s.MasterCount, + "The number of apiservers running in the cluster.") - fs.IntVar(&s.MaxRequestsInFlight, "max-requests-inflight", s.MaxRequestsInFlight, "The maximum number of requests in flight at a given time. When the server exceeds this, it rejects requests. Zero for no limit.") + fs.StringVar(&s.MasterServiceNamespace, "master-service-namespace", s.MasterServiceNamespace, ""+ + "The namespace from which the kubernetes master services should be injected into pods.") - fs.IntVar(&s.MinRequestTimeout, "min-request-timeout", s.MinRequestTimeout, "An optional field indicating the minimum number of seconds a handler must keep a request open before timing it out. Currently only honored by the watch request handler, which picks a randomized value above this number as the connection timeout, to spread out load.") + fs.IntVar(&s.MaxRequestsInFlight, "max-requests-inflight", s.MaxRequestsInFlight, ""+ + "The maximum number of requests in flight at a given time. When the server exceeds this, "+ + "it rejects requests. Zero for no limit.") + + fs.IntVar(&s.MinRequestTimeout, "min-request-timeout", s.MinRequestTimeout, ""+ + "An optional field indicating the minimum number of seconds a handler must keep "+ + "a request open before timing it out. Currently only honored by the watch request "+ + "handler, which picks a randomized value above this number as the connection timeout, "+ + "to spread out load.") + + fs.StringVar(&s.OIDCIssuerURL, "oidc-issuer-url", s.OIDCIssuerURL, ""+ + "The URL of the OpenID issuer, only HTTPS scheme will be accepted. "+ + "If set, it will be used to verify the OIDC JSON Web Token (JWT).") + + fs.StringVar(&s.OIDCClientID, "oidc-client-id", s.OIDCClientID, + "The client ID for the OpenID Connect client, must be set if oidc-issuer-url is set.") + + fs.StringVar(&s.OIDCCAFile, "oidc-ca-file", s.OIDCCAFile, ""+ + "If set, the OpenID server's certificate will be verified by one of the authorities "+ + "in the oidc-ca-file, otherwise the host's root CA set will be used.") - fs.StringVar(&s.OIDCIssuerURL, "oidc-issuer-url", s.OIDCIssuerURL, "The URL of the OpenID issuer, only HTTPS scheme will be accepted. If set, it will be used to verify the OIDC JSON Web Token (JWT)") - fs.StringVar(&s.OIDCClientID, "oidc-client-id", s.OIDCClientID, "The client ID for the OpenID Connect client, must be set if oidc-issuer-url is set") - fs.StringVar(&s.OIDCCAFile, "oidc-ca-file", s.OIDCCAFile, "If set, the OpenID server's certificate will be verified by one of the authorities in the oidc-ca-file, otherwise the host's root CA set will be used") fs.StringVar(&s.OIDCUsernameClaim, "oidc-username-claim", "sub", ""+ - "The OpenID claim to use as the user name. Note that claims other than the default ('sub') is not "+ - "guaranteed to be unique and immutable. This flag is experimental, please see the authentication documentation for further details.") - fs.StringVar(&s.OIDCGroupsClaim, "oidc-groups-claim", "", "If provided, the name of a custom OpenID Connect claim for specifying user groups. The claim value is expected to be an array of strings. This flag is experimental, please see the authentication documentation for further details.") + "The OpenID claim to use as the user name. Note that claims other than the default ('sub') "+ + "is not guaranteed to be unique and immutable. This flag is experimental, please see "+ + "the authentication documentation for further details.") - fs.Var(&s.RuntimeConfig, "runtime-config", "A set of key=value pairs that describe runtime configuration that may be passed to apiserver. apis/ key can be used to turn on/off specific api versions. apis// can be used to turn on/off specific resources. api/all and api/legacy are special keys to control all and legacy api versions respectively.") + fs.StringVar(&s.OIDCGroupsClaim, "oidc-groups-claim", "", ""+ + "If provided, the name of a custom OpenID Connect claim for specifying user groups. "+ + "The claim value is expected to be an array of strings. This flag is experimental, "+ + "please see the authentication documentation for further details.") + + fs.Var(&s.RuntimeConfig, "runtime-config", ""+ + "A set of key=value pairs that describe runtime configuration that may be passed "+ + "to apiserver. apis/ key can be used to turn on/off specific api versions. "+ + "apis// can be used to turn on/off specific resources. api/all and "+ + "api/legacy are special keys to control all and legacy api versions respectively.") fs.IntVar(&s.SecurePort, "secure-port", s.SecurePort, ""+ "The port on which to serve HTTPS with authentication and authorization. If 0, "+ "don't serve HTTPS at all.") - fs.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, "A CIDR notation IP range from which to assign service cluster IPs. This must not overlap with any IP ranges assigned to nodes for pods.") - fs.IPNetVar(&s.ServiceClusterIPRange, "portal-net", s.ServiceClusterIPRange, "Deprecated: see --service-cluster-ip-range instead.") - fs.MarkDeprecated("portal-net", "see --service-cluster-ip-range instead.") - - fs.Var(&s.ServiceNodePortRange, "service-node-port-range", "A port range to reserve for services with NodePort visibility. Example: '30000-32767'. Inclusive at both ends of the range.") - fs.Var(&s.ServiceNodePortRange, "service-node-ports", "Deprecated: see --service-node-port-range instead.") - fs.MarkDeprecated("service-node-ports", "see --service-node-port-range instead.") - - fs.StringVar(&s.StorageConfig.Type, "storage-backend", s.StorageConfig.Type, "The storage backend for persistence. Options: 'etcd2' (default), 'etcd3'.") - fs.StringSliceVar(&s.StorageConfig.ServerList, "etcd-servers", s.StorageConfig.ServerList, "List of etcd servers to connect with (http://ip:port), comma separated.") - fs.StringVar(&s.StorageConfig.Prefix, "etcd-prefix", s.StorageConfig.Prefix, "The prefix for all resource paths in etcd.") - fs.StringVar(&s.StorageConfig.KeyFile, "etcd-keyfile", s.StorageConfig.KeyFile, "SSL key file used to secure etcd communication") - fs.StringVar(&s.StorageConfig.CertFile, "etcd-certfile", s.StorageConfig.CertFile, "SSL certification file used to secure etcd communication") - fs.StringVar(&s.StorageConfig.CAFile, "etcd-cafile", s.StorageConfig.CAFile, "SSL Certificate Authority file used to secure etcd communication") - fs.BoolVar(&s.StorageConfig.Quorum, "etcd-quorum-read", s.StorageConfig.Quorum, "If true, enable quorum read") - fs.IntVar(&s.StorageConfig.DeserializationCacheSize, "deserialization-cache-size", s.StorageConfig.DeserializationCacheSize, "Number of deserialized json objects to cache in memory.") - - fs.StringVar(&s.DeprecatedStorageVersion, "storage-version", s.DeprecatedStorageVersion, "The version to store the legacy v1 resources with. Defaults to server preferred") - fs.MarkDeprecated("storage-version", "--storage-version is deprecated and will be removed when the v1 API is retired. See --storage-versions instead.") - fs.StringVar(&s.StorageVersions, "storage-versions", s.StorageVersions, "The per-group version to store resources in. "+ - "Specified in the format \"group1/version1,group2/version2,...\". "+ - "In the case where objects are moved from one group to the other, you may specify the format \"group1=group2/v1beta1,group3/v1beta1,...\". "+ - "You only need to pass the groups you wish to change from the defaults. "+ - "It defaults to a list of preferred versions of all registered groups, which is derived from the KUBE_API_VERSIONS environment variable.") + fs.IPNetVar(&s.ServiceClusterIPRange, "service-cluster-ip-range", s.ServiceClusterIPRange, ""+ + "A CIDR notation IP range from which to assign service cluster IPs. This must not "+ + "overlap with any IP ranges assigned to nodes for pods.") - fs.StringVar(&s.TLSCertFile, "tls-cert-file", s.TLSCertFile, ""+ - "File containing x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). "+ - "If HTTPS serving is enabled, and --tls-cert-file and --tls-private-key-file are not provided, "+ - "a self-signed certificate and key are generated for the public address and saved to /var/run/kubernetes.") + fs.IPNetVar(&s.ServiceClusterIPRange, "portal-net", s.ServiceClusterIPRange, + "DEPRECATED: see --service-cluster-ip-range instead.") + fs.MarkDeprecated("portal-net", "see --service-cluster-ip-range instead") + + fs.Var(&s.ServiceNodePortRange, "service-node-port-range", ""+ + "A port range to reserve for services with NodePort visibility. "+ + "Example: '30000-32767'. Inclusive at both ends of the range.") + fs.Var(&s.ServiceNodePortRange, "service-node-ports", "DEPRECATED: see --service-node-port-range instead") + fs.MarkDeprecated("service-node-ports", "see --service-node-port-range instead") + + fs.StringVar(&s.StorageConfig.Type, "storage-backend", s.StorageConfig.Type, + "The storage backend for persistence. Options: 'etcd2' (default), 'etcd3'.") + + fs.StringSliceVar(&s.StorageConfig.ServerList, "etcd-servers", s.StorageConfig.ServerList, + "List of etcd servers to connect with (http://ip:port), comma separated.") + + fs.StringVar(&s.StorageConfig.Prefix, "etcd-prefix", s.StorageConfig.Prefix, + "The prefix for all resource paths in etcd.") + + fs.StringVar(&s.StorageConfig.KeyFile, "etcd-keyfile", s.StorageConfig.KeyFile, + "SSL key file used to secure etcd communication.") + + fs.StringVar(&s.StorageConfig.CertFile, "etcd-certfile", s.StorageConfig.CertFile, + "SSL certification file used to secure etcd communication.") - fs.StringVar(&s.TLSPrivateKeyFile, "tls-private-key-file", s.TLSPrivateKeyFile, "File containing x509 private key matching --tls-cert-file.") + fs.StringVar(&s.StorageConfig.CAFile, "etcd-cafile", s.StorageConfig.CAFile, + "SSL Certificate Authority file used to secure etcd communication.") - fs.StringVar(&s.TokenAuthFile, "token-auth-file", s.TokenAuthFile, "If set, the file that will be used to secure the secure port of the API server via token authentication.") + fs.BoolVar(&s.StorageConfig.Quorum, "etcd-quorum-read", s.StorageConfig.Quorum, + "If true, enable quorum read.") - fs.StringSliceVar(&s.WatchCacheSizes, "watch-cache-sizes", s.WatchCacheSizes, "List of watch cache sizes for every resource (pods, nodes, etc.), comma separated. The individual override format: resource#size, where size is a number. It takes effect when watch-cache is enabled.") + fs.IntVar(&s.StorageConfig.DeserializationCacheSize, "deserialization-cache-size", s.StorageConfig.DeserializationCacheSize, + "Number of deserialized json objects to cache in memory.") + + fs.StringVar(&s.DeprecatedStorageVersion, "storage-version", s.DeprecatedStorageVersion, + "DEPRECATED: the version to store the legacy v1 resources with. Defaults to server preferred.") + fs.MarkDeprecated("storage-version", "--storage-version is deprecated and will be removed when the v1 API "+ + "is retired. See --storage-versions instead.") + + fs.StringVar(&s.StorageVersions, "storage-versions", s.StorageVersions, ""+ + "The per-group version to store resources in. "+ + "Specified in the format \"group1/version1,group2/version2,...\". "+ + "In the case where objects are moved from one group to the other, "+ + "you may specify the format \"group1=group2/v1beta1,group3/v1beta1,...\". "+ + "You only need to pass the groups you wish to change from the defaults. "+ + "It defaults to a list of preferred versions of all registered groups, "+ + "which is derived from the KUBE_API_VERSIONS environment variable.") + + fs.StringVar(&s.TLSCertFile, "tls-cert-file", s.TLSCertFile, ""+ + "File containing x509 Certificate for HTTPS. (CA cert, if any, concatenated "+ + "after server cert). If HTTPS serving is enabled, and --tls-cert-file and "+ + "--tls-private-key-file are not provided, a self-signed certificate and key "+ + "are generated for the public address and saved to /var/run/kubernetes.") + + fs.StringVar(&s.TLSPrivateKeyFile, "tls-private-key-file", s.TLSPrivateKeyFile, + "File containing x509 private key matching --tls-cert-file.") + + fs.StringVar(&s.TokenAuthFile, "token-auth-file", s.TokenAuthFile, ""+ + "If set, the file that will be used to secure the secure port of the API server "+ + "via token authentication.") + + fs.StringSliceVar(&s.WatchCacheSizes, "watch-cache-sizes", s.WatchCacheSizes, ""+ + "List of watch cache sizes for every resource (pods, nodes, etc.), comma separated. "+ + "The individual override format: resource#size, where size is a number. It takes effect "+ + "when watch-cache is enabled.") } diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_config.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_config.go index 0f40e3774f10..4d8ee7a90359 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_config.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_config.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ type APIResourceConfigSource interface { ResourceEnabled(resource unversioned.GroupVersionResource) bool AllResourcesForVersionEnabled(version unversioned.GroupVersion) bool AnyResourcesForVersionEnabled(version unversioned.GroupVersion) bool + AnyResourcesForGroupEnabled(group string) bool } // Specifies the overrides for various API group versions. @@ -170,3 +171,15 @@ func (o *ResourceConfig) AnyResourcesForVersionEnabled(version unversioned.Group return versionOverride.Enable } + +func (o *ResourceConfig) AnyResourcesForGroupEnabled(group string) bool { + for version := range o.GroupVersionResourceConfigs { + if version.Group == group { + if o.AnyResourcesForVersionEnabled(version) { + return true + } + } + } + + return false +} diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_encoding_config.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_encoding_config.go index 04a25d45fba4..3682e8a128c4 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_encoding_config.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/resource_encoding_config.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/storage_factory.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/storage_factory.go index fb25cb0b06a9..58117eda74b9 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/storage_factory.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/storage_factory.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package genericapiserver import ( "fmt" "mime" + "strings" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" @@ -37,6 +38,12 @@ type StorageFactory interface { // New finds the storage destination for the given group and resource. It will // return an error if the group has no storage destination configured. New(groupResource unversioned.GroupResource) (storage.Interface, error) + + // ResourcePrefix returns the overridden resource prefix for the GroupResource + // This allows for cohabitation of resources with different native types and provides + // centralized control over the shape of etcd directories + ResourcePrefix(groupResource unversioned.GroupResource) string + // Backends gets all backends for all registered storage destinations. // Used for getting all instances for health validations. Backends() []string @@ -78,8 +85,12 @@ type groupResourceOverrides struct { // etcdLocation contains the list of "special" locations that are used for particular GroupResources // These are merged on top of the StorageConfig when requesting the storage.Interface for a given GroupResource etcdLocation []string - // etcdPrefix contains the list of "special" prefixes for a GroupResource. Resource=* means for the entire group + // etcdPrefix is the base location for a GroupResource. etcdPrefix string + // etcdResourcePrefix is the location to use to store a particular type under the `etcdPrefix` location + // If empty, the default mapping is used. If the default mapping doesn't contain an entry, it will use + // the ToLowered name of the resource, not including the group. + etcdResourcePrefix string // mediaType is the desired serializer to choose. If empty, the default is chosen. mediaType string // serializer contains the list of "special" serializers for a GroupResource. Resource=* means for the entire group @@ -123,6 +134,13 @@ func (s *DefaultStorageFactory) SetEtcdPrefix(groupResource unversioned.GroupRes s.Overrides[groupResource] = overrides } +// SetResourceEtcdPrefix sets the prefix for a resource, but not the base-dir. You'll end up in `etcdPrefix/resourceEtcdPrefix`. +func (s *DefaultStorageFactory) SetResourceEtcdPrefix(groupResource unversioned.GroupResource, prefix string) { + overrides := s.Overrides[groupResource] + overrides.etcdResourcePrefix = prefix + s.Overrides[groupResource] = overrides +} + func (s *DefaultStorageFactory) SetSerializer(groupResource unversioned.GroupResource, mediaType string, serializer runtime.StorageSerializer) { overrides := s.Overrides[groupResource] overrides.mediaType = mediaType @@ -268,3 +286,30 @@ func NewStorageCodec(storageMediaType string, ns runtime.StorageSerializer, stor } return runtime.NewCodec(encoder, decoder), nil } + +var specialDefaultResourcePrefixes = map[unversioned.GroupResource]string{ + unversioned.GroupResource{Group: "", Resource: "replicationControllers"}: "controllers", + unversioned.GroupResource{Group: "", Resource: "replicationcontrollers"}: "controllers", + unversioned.GroupResource{Group: "", Resource: "endpoints"}: "services/endpoints", + unversioned.GroupResource{Group: "", Resource: "nodes"}: "minions", + unversioned.GroupResource{Group: "", Resource: "services"}: "services/specs", +} + +func (s *DefaultStorageFactory) ResourcePrefix(groupResource unversioned.GroupResource) string { + chosenStorageResource := s.getStorageGroupResource(groupResource) + groupOverride := s.Overrides[getAllResourcesAlias(chosenStorageResource)] + exactResourceOverride := s.Overrides[chosenStorageResource] + + etcdResourcePrefix := specialDefaultResourcePrefixes[chosenStorageResource] + if len(groupOverride.etcdResourcePrefix) > 0 { + etcdResourcePrefix = groupOverride.etcdResourcePrefix + } + if len(exactResourceOverride.etcdResourcePrefix) > 0 { + etcdResourcePrefix = exactResourceOverride.etcdResourcePrefix + } + if len(etcdResourcePrefix) == 0 { + etcdResourcePrefix = strings.ToLower(chosenStorageResource.Resource) + } + + return etcdResourcePrefix +} diff --git a/vendor/k8s.io/kubernetes/pkg/genericapiserver/tunneler.go b/vendor/k8s.io/kubernetes/pkg/genericapiserver/tunneler.go index 1d452c210f0a..a239bc901383 100644 --- a/vendor/k8s.io/kubernetes/pkg/genericapiserver/tunneler.go +++ b/vendor/k8s.io/kubernetes/pkg/genericapiserver/tunneler.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( "k8s.io/kubernetes/pkg/ssh" "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/wait" "github.com/golang/glog" @@ -54,7 +55,7 @@ type SSHTunneler struct { lastSync int64 // Seconds since Epoch lastSSHKeySync int64 // Seconds since Epoch lastSyncMetric prometheus.GaugeFunc - clock util.Clock + clock clock.Clock getAddresses AddressFunc stopChan chan struct{} @@ -66,7 +67,7 @@ func NewSSHTunneler(sshUser, sshKeyfile string, healthCheckURL *url.URL, install SSHKeyfile: sshKeyfile, InstallSSHKey: installSSHKey, HealthCheckURL: healthCheckURL, - clock: util.RealClock{}, + clock: clock.RealClock{}, } } diff --git a/vendor/k8s.io/kubernetes/pkg/healthz/doc.go b/vendor/k8s.io/kubernetes/pkg/healthz/doc.go index 37a95b806e4e..28980e5d96ca 100644 --- a/vendor/k8s.io/kubernetes/pkg/healthz/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/healthz/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,5 +16,6 @@ limitations under the License. // Package healthz implements basic http server health checking. // Usage: -// import _ "healthz" registers a handler on the path '/healthz', that serves 200s +// import "k8s.io/kubernetes/pkg/healthz" +// healthz.DefaultHealthz() package healthz diff --git a/vendor/k8s.io/kubernetes/pkg/healthz/healthz.go b/vendor/k8s.io/kubernetes/pkg/healthz/healthz.go index 5a9af7aa1003..b71797d75310 100644 --- a/vendor/k8s.io/kubernetes/pkg/healthz/healthz.go +++ b/vendor/k8s.io/kubernetes/pkg/healthz/healthz.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/httplog/doc.go b/vendor/k8s.io/kubernetes/pkg/httplog/doc.go index 99973e2d7ef0..57aa55ab91ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/httplog/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/httplog/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/httplog/log.go b/vendor/k8s.io/kubernetes/pkg/httplog/log.go index d4530dbd8b8d..2c42bd781b80 100644 --- a/vendor/k8s.io/kubernetes/pkg/httplog/log.go +++ b/vendor/k8s.io/kubernetes/pkg/httplog/log.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ type passthroughLogger struct{} // Addf logs info immediately. func (passthroughLogger) Addf(format string, data ...interface{}) { - glog.InfoDepth(1, fmt.Sprintf(format, data...)) + glog.V(2).Info(fmt.Sprintf(format, data...)) } // DefaultStacktracePred is the default implementation of StacktracePred. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline.go b/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline.go new file mode 100644 index 000000000000..154bbd3bad18 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline.go @@ -0,0 +1,98 @@ +/* +Copyright 2016 The Kubernetes 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 kubelet + +import ( + "fmt" + "time" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/record" + "k8s.io/kubernetes/pkg/kubelet/lifecycle" + "k8s.io/kubernetes/pkg/kubelet/status" + "k8s.io/kubernetes/pkg/util/clock" +) + +const ( + reason = "DeadlineExceeded" + message = "Pod was active on the node longer than the specified deadline" +) + +// activeDeadlineHandler knows how to enforce active deadlines on pods. +type activeDeadlineHandler struct { + // the clock to use for deadline enforcement + clock clock.Clock + // the provider of pod status + podStatusProvider status.PodStatusProvider + // the recorder to dispatch events when we identify a pod has exceeded active deadline + recorder record.EventRecorder +} + +// newActiveDeadlineHandler returns an active deadline handler that can enforce pod active deadline +func newActiveDeadlineHandler( + podStatusProvider status.PodStatusProvider, + recorder record.EventRecorder, + clock clock.Clock, +) (*activeDeadlineHandler, error) { + + // check for all required fields + if clock == nil || podStatusProvider == nil || recorder == nil { + return nil, fmt.Errorf("Required arguments must not be nil: %v, %v, %v", clock, podStatusProvider, recorder) + } + return &activeDeadlineHandler{ + clock: clock, + podStatusProvider: podStatusProvider, + recorder: recorder, + }, nil +} + +// ShouldSync returns true if the pod is past its active deadline. +func (m *activeDeadlineHandler) ShouldSync(pod *api.Pod) bool { + return m.pastActiveDeadline(pod) +} + +// ShouldEvict returns true if the pod is past its active deadline. +// It dispatches an event that the pod should be evicted if it is past its deadline. +func (m *activeDeadlineHandler) ShouldEvict(pod *api.Pod) lifecycle.ShouldEvictResponse { + if !m.pastActiveDeadline(pod) { + return lifecycle.ShouldEvictResponse{Evict: false} + } + m.recorder.Eventf(pod, api.EventTypeNormal, reason, message) + return lifecycle.ShouldEvictResponse{Evict: true, Reason: reason, Message: message} +} + +// pastActiveDeadline returns true if the pod has been active for more than its ActiveDeadlineSeconds +func (m *activeDeadlineHandler) pastActiveDeadline(pod *api.Pod) bool { + // no active deadline was specified + if pod.Spec.ActiveDeadlineSeconds == nil { + return false + } + // get the latest status to determine if it was started + podStatus, ok := m.podStatusProvider.GetPodStatus(pod.UID) + if !ok { + podStatus = pod.Status + } + // we have no start time so just return + if podStatus.StartTime.IsZero() { + return false + } + // determine if the deadline was exceeded + start := podStatus.StartTime.Time + duration := m.clock.Since(start) + allowedDuration := time.Duration(*pod.Spec.ActiveDeadlineSeconds) * time.Second + return duration >= allowedDuration +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.pb.go b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.pb.go new file mode 100644 index 000000000000..0b9a3746ba93 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.pb.go @@ -0,0 +1,2913 @@ +/* +Copyright 2016 The Kubernetes 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. +*/ + +// Code generated by protoc-gen-gogo. +// source: api.proto +// DO NOT EDIT! + +/* +Package runtime is a generated protocol buffer package. + +It is generated from these files: + api.proto + +It has these top-level messages: + VersionRequest + VersionResponse + DNSOption + PortMapping + Mount + ResourceRequirements + PodSandboxResources + NamespaceOption + LinuxPodSandboxConfig + PodSandboxConfig + CreatePodSandboxRequest + CreatePodSandboxResponse + StopPodSandboxRequest + StopPodSandboxResponse + DeletePodSandboxRequest + DeletePodSandboxResponse + PodSandboxStatusRequest + PodSandboxNetworkStatus + Namespace + LinuxPodSandboxStatus + PodSandboxStatus + PodSandboxStatusResponse + PodSandboxFilter + ListPodSandboxRequest + PodSandbox + ListPodSandboxResponse + ImageSpec + KeyValue + LinuxContainerResources + SELinuxOption + Capability + LinuxContainerConfig + LinuxUser + ContainerConfig + CreateContainerRequest + CreateContainerResponse + StartContainerRequest + StartContainerResponse + StopContainerRequest + StopContainerResponse + RemoveContainerRequest + RemoveContainerResponse + ContainerFilter + ListContainersRequest + Container + ListContainersResponse + ContainerStatusRequest + ContainerStatus + ContainerStatusResponse + ExecRequest + ExecResponse + ImageFilter + ListImagesRequest + Image + ListImagesResponse + ImageStatusRequest + ImageStatusResponse + AuthConfig + PullImageRequest + PullImageResponse + RemoveImageRequest + RemoveImageResponse +*/ +package runtime + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +import ( + context "golang.org/x/net/context" + grpc "google.golang.org/grpc" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +type Protocol int32 + +const ( + Protocol_TCP Protocol = 0 + Protocol_UDP Protocol = 1 +) + +var Protocol_name = map[int32]string{ + 0: "TCP", + 1: "UDP", +} +var Protocol_value = map[string]int32{ + "TCP": 0, + "UDP": 1, +} + +func (x Protocol) Enum() *Protocol { + p := new(Protocol) + *p = x + return p +} +func (x Protocol) String() string { + return proto.EnumName(Protocol_name, int32(x)) +} +func (x *Protocol) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(Protocol_value, data, "Protocol") + if err != nil { + return err + } + *x = Protocol(value) + return nil +} + +type PodSandBoxState int32 + +const ( + PodSandBoxState_READY PodSandBoxState = 0 + PodSandBoxState_NOTREADY PodSandBoxState = 1 +) + +var PodSandBoxState_name = map[int32]string{ + 0: "READY", + 1: "NOTREADY", +} +var PodSandBoxState_value = map[string]int32{ + "READY": 0, + "NOTREADY": 1, +} + +func (x PodSandBoxState) Enum() *PodSandBoxState { + p := new(PodSandBoxState) + *p = x + return p +} +func (x PodSandBoxState) String() string { + return proto.EnumName(PodSandBoxState_name, int32(x)) +} +func (x *PodSandBoxState) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(PodSandBoxState_value, data, "PodSandBoxState") + if err != nil { + return err + } + *x = PodSandBoxState(value) + return nil +} + +type ContainerState int32 + +const ( + ContainerState_CREATED ContainerState = 0 + ContainerState_RUNNING ContainerState = 1 + ContainerState_EXITED ContainerState = 2 + ContainerState_UNKNOWN ContainerState = 3 +) + +var ContainerState_name = map[int32]string{ + 0: "CREATED", + 1: "RUNNING", + 2: "EXITED", + 3: "UNKNOWN", +} +var ContainerState_value = map[string]int32{ + "CREATED": 0, + "RUNNING": 1, + "EXITED": 2, + "UNKNOWN": 3, +} + +func (x ContainerState) Enum() *ContainerState { + p := new(ContainerState) + *p = x + return p +} +func (x ContainerState) String() string { + return proto.EnumName(ContainerState_name, int32(x)) +} +func (x *ContainerState) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(ContainerState_value, data, "ContainerState") + if err != nil { + return err + } + *x = ContainerState(value) + return nil +} + +type VersionRequest struct { + // The version of kubelet runtime API. + Version *string `protobuf:"bytes,1,opt,name=version" json:"version,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *VersionRequest) Reset() { *m = VersionRequest{} } +func (m *VersionRequest) String() string { return proto.CompactTextString(m) } +func (*VersionRequest) ProtoMessage() {} + +func (m *VersionRequest) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +type VersionResponse struct { + // The version of the kubelet runtime API. + Version *string `protobuf:"bytes,1,opt,name=version" json:"version,omitempty"` + // The name of the container runtime. + RuntimeName *string `protobuf:"bytes,2,opt,name=runtime_name" json:"runtime_name,omitempty"` + // The version of the container runtime. + RuntimeVersion *string `protobuf:"bytes,3,opt,name=runtime_version" json:"runtime_version,omitempty"` + // The API version of the container runtime. + RuntimeApiVersion *string `protobuf:"bytes,4,opt,name=runtime_api_version" json:"runtime_api_version,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *VersionResponse) Reset() { *m = VersionResponse{} } +func (m *VersionResponse) String() string { return proto.CompactTextString(m) } +func (*VersionResponse) ProtoMessage() {} + +func (m *VersionResponse) GetVersion() string { + if m != nil && m.Version != nil { + return *m.Version + } + return "" +} + +func (m *VersionResponse) GetRuntimeName() string { + if m != nil && m.RuntimeName != nil { + return *m.RuntimeName + } + return "" +} + +func (m *VersionResponse) GetRuntimeVersion() string { + if m != nil && m.RuntimeVersion != nil { + return *m.RuntimeVersion + } + return "" +} + +func (m *VersionResponse) GetRuntimeApiVersion() string { + if m != nil && m.RuntimeApiVersion != nil { + return *m.RuntimeApiVersion + } + return "" +} + +// DNSOption specifies the DNS servers and search domains. +type DNSOption struct { + // List of DNS servers of the cluster. + Servers []string `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` + // List of DNS search domains of the cluster. + Searches []string `protobuf:"bytes,2,rep,name=searches" json:"searches,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *DNSOption) Reset() { *m = DNSOption{} } +func (m *DNSOption) String() string { return proto.CompactTextString(m) } +func (*DNSOption) ProtoMessage() {} + +func (m *DNSOption) GetServers() []string { + if m != nil { + return m.Servers + } + return nil +} + +func (m *DNSOption) GetSearches() []string { + if m != nil { + return m.Searches + } + return nil +} + +// PortMapping specifies the port mapping configurations of sandbox +type PortMapping struct { + // The name of the port mapping + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // The protocol of the port mapping. + Protocol *Protocol `protobuf:"varint,2,opt,name=protocol,enum=runtime.Protocol" json:"protocol,omitempty"` + // The port number within the container. + ContainerPort *int32 `protobuf:"varint,3,opt,name=container_port" json:"container_port,omitempty"` + // The port number on the host. + HostPort *int32 `protobuf:"varint,4,opt,name=host_port" json:"host_port,omitempty"` + // The host IP. + HostIp *string `protobuf:"bytes,5,opt,name=host_ip" json:"host_ip,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PortMapping) Reset() { *m = PortMapping{} } +func (m *PortMapping) String() string { return proto.CompactTextString(m) } +func (*PortMapping) ProtoMessage() {} + +func (m *PortMapping) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *PortMapping) GetProtocol() Protocol { + if m != nil && m.Protocol != nil { + return *m.Protocol + } + return Protocol_TCP +} + +func (m *PortMapping) GetContainerPort() int32 { + if m != nil && m.ContainerPort != nil { + return *m.ContainerPort + } + return 0 +} + +func (m *PortMapping) GetHostPort() int32 { + if m != nil && m.HostPort != nil { + return *m.HostPort + } + return 0 +} + +func (m *PortMapping) GetHostIp() string { + if m != nil && m.HostIp != nil { + return *m.HostIp + } + return "" +} + +// Mount specifies the volume mount for the sandbox +type Mount struct { + // The name of the volume mount. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // The path of the mount within the container. + ContainerPath *string `protobuf:"bytes,2,opt,name=container_path" json:"container_path,omitempty"` + // The path of the mount on the host. + HostPath *string `protobuf:"bytes,3,opt,name=host_path" json:"host_path,omitempty"` + // If set, the mount is read-only. + Readonly *bool `protobuf:"varint,4,opt,name=readonly" json:"readonly,omitempty"` + // If set, the mount needs SELinux relabeling + SelinuxRelabel *bool `protobuf:"varint,5,opt,name=selinux_relabel" json:"selinux_relabel,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Mount) Reset() { *m = Mount{} } +func (m *Mount) String() string { return proto.CompactTextString(m) } +func (*Mount) ProtoMessage() {} + +func (m *Mount) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *Mount) GetContainerPath() string { + if m != nil && m.ContainerPath != nil { + return *m.ContainerPath + } + return "" +} + +func (m *Mount) GetHostPath() string { + if m != nil && m.HostPath != nil { + return *m.HostPath + } + return "" +} + +func (m *Mount) GetReadonly() bool { + if m != nil && m.Readonly != nil { + return *m.Readonly + } + return false +} + +func (m *Mount) GetSelinuxRelabel() bool { + if m != nil && m.SelinuxRelabel != nil { + return *m.SelinuxRelabel + } + return false +} + +// ResourceRequirements contains a set of resources +// Valid resources are: +// - cpu, in cores. (500m = .5 cores) +// - memory, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) +type ResourceRequirements struct { + // The maximum amount of compute resources allowed. + Limits *float64 `protobuf:"fixed64,1,opt,name=limits" json:"limits,omitempty"` + // The minimum amount of compute resources required. + // If Request is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value + Requests *float64 `protobuf:"fixed64,2,opt,name=requests" json:"requests,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ResourceRequirements) Reset() { *m = ResourceRequirements{} } +func (m *ResourceRequirements) String() string { return proto.CompactTextString(m) } +func (*ResourceRequirements) ProtoMessage() {} + +func (m *ResourceRequirements) GetLimits() float64 { + if m != nil && m.Limits != nil { + return *m.Limits + } + return 0 +} + +func (m *ResourceRequirements) GetRequests() float64 { + if m != nil && m.Requests != nil { + return *m.Requests + } + return 0 +} + +// PodSandboxResources contains the CPU/memory resource requirements. +type PodSandboxResources struct { + // CPU resource requirement. + Cpu *ResourceRequirements `protobuf:"bytes,1,opt,name=cpu" json:"cpu,omitempty"` + // Memory resource requirement. + Memory *ResourceRequirements `protobuf:"bytes,2,opt,name=memory" json:"memory,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxResources) Reset() { *m = PodSandboxResources{} } +func (m *PodSandboxResources) String() string { return proto.CompactTextString(m) } +func (*PodSandboxResources) ProtoMessage() {} + +func (m *PodSandboxResources) GetCpu() *ResourceRequirements { + if m != nil { + return m.Cpu + } + return nil +} + +func (m *PodSandboxResources) GetMemory() *ResourceRequirements { + if m != nil { + return m.Memory + } + return nil +} + +// NamespaceOption provides options for Linux namespaces. +type NamespaceOption struct { + // If set, use the host's network namespace. + HostNetwork *bool `protobuf:"varint,1,opt,name=host_network" json:"host_network,omitempty"` + // If set, use the host's pid namesapce. + HostPid *bool `protobuf:"varint,2,opt,name=host_pid" json:"host_pid,omitempty"` + // If set, use the host's ipc namespace. + HostIpc *bool `protobuf:"varint,3,opt,name=host_ipc" json:"host_ipc,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *NamespaceOption) Reset() { *m = NamespaceOption{} } +func (m *NamespaceOption) String() string { return proto.CompactTextString(m) } +func (*NamespaceOption) ProtoMessage() {} + +func (m *NamespaceOption) GetHostNetwork() bool { + if m != nil && m.HostNetwork != nil { + return *m.HostNetwork + } + return false +} + +func (m *NamespaceOption) GetHostPid() bool { + if m != nil && m.HostPid != nil { + return *m.HostPid + } + return false +} + +func (m *NamespaceOption) GetHostIpc() bool { + if m != nil && m.HostIpc != nil { + return *m.HostIpc + } + return false +} + +// LinuxPodSandboxConfig holds platform-specific configuraions for Linux +// host platforms and Linux-based containers. +type LinuxPodSandboxConfig struct { + // The parent cgroup of the pod sandbox. + // The cgroupfs style syntax will be used, but the container runtime can + // convert it to systemd semantices if needed. + CgroupParent *string `protobuf:"bytes,1,opt,name=cgroup_parent" json:"cgroup_parent,omitempty"` + // The configurations for the sandbox's namespaces. + // This will be used only if the PodSandbox uses namespace for isolation. + NamespaceOptions *NamespaceOption `protobuf:"bytes,2,opt,name=namespace_options" json:"namespace_options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *LinuxPodSandboxConfig) Reset() { *m = LinuxPodSandboxConfig{} } +func (m *LinuxPodSandboxConfig) String() string { return proto.CompactTextString(m) } +func (*LinuxPodSandboxConfig) ProtoMessage() {} + +func (m *LinuxPodSandboxConfig) GetCgroupParent() string { + if m != nil && m.CgroupParent != nil { + return *m.CgroupParent + } + return "" +} + +func (m *LinuxPodSandboxConfig) GetNamespaceOptions() *NamespaceOption { + if m != nil { + return m.NamespaceOptions + } + return nil +} + +// PodSandboxConfig holds all the required and optional fields for creating a +// sandbox. +type PodSandboxConfig struct { + // The name of the sandbox. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // The hostname of the sandbox. + Hostname *string `protobuf:"bytes,2,opt,name=hostname" json:"hostname,omitempty"` + // Path to the directory on the host in which container log files are + // stored. + // By default the log of a container going into the LogDirectory will be + // hooked up to STDOUT and STDERR. However, the LogDirectory may contain + // binary log files with structured logging data from the individual + // containers. For example the files might be newline seperated JSON + // structured logs, systemd-journald journal files, gRPC trace files, etc. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + LogDirectory *string `protobuf:"bytes,3,opt,name=log_directory" json:"log_directory,omitempty"` + // The DNS options for the sandbox. + DnsOptions *DNSOption `protobuf:"bytes,4,opt,name=dns_options" json:"dns_options,omitempty"` + // The port mappings for the sandbox. + PortMappings []*PortMapping `protobuf:"bytes,5,rep,name=port_mappings" json:"port_mappings,omitempty"` + // Resources specifies the resource limits for the sandbox (i.e., the + // aggregate cpu/memory resources limits of all containers). + // Note: On a Linux host, kubelet will create a pod-level cgroup and pass + // it as the cgroup parent for the PodSandbox. For some runtimes, this is + // sufficent. For others, e.g., hypervisor-based runtimes, explicit + // resource limits for the sandbox are needed at creation time. + Resources *PodSandboxResources `protobuf:"bytes,6,opt,name=resources" json:"resources,omitempty"` + // Labels are key value pairs that may be used to scope and select individual resources. + Labels map[string]string `protobuf:"bytes,7,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + Annotations map[string]string `protobuf:"bytes,8,rep,name=annotations" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Optional configurations specific to Linux hosts. + Linux *LinuxPodSandboxConfig `protobuf:"bytes,9,opt,name=linux" json:"linux,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxConfig) Reset() { *m = PodSandboxConfig{} } +func (m *PodSandboxConfig) String() string { return proto.CompactTextString(m) } +func (*PodSandboxConfig) ProtoMessage() {} + +func (m *PodSandboxConfig) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *PodSandboxConfig) GetHostname() string { + if m != nil && m.Hostname != nil { + return *m.Hostname + } + return "" +} + +func (m *PodSandboxConfig) GetLogDirectory() string { + if m != nil && m.LogDirectory != nil { + return *m.LogDirectory + } + return "" +} + +func (m *PodSandboxConfig) GetDnsOptions() *DNSOption { + if m != nil { + return m.DnsOptions + } + return nil +} + +func (m *PodSandboxConfig) GetPortMappings() []*PortMapping { + if m != nil { + return m.PortMappings + } + return nil +} + +func (m *PodSandboxConfig) GetResources() *PodSandboxResources { + if m != nil { + return m.Resources + } + return nil +} + +func (m *PodSandboxConfig) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +func (m *PodSandboxConfig) GetAnnotations() map[string]string { + if m != nil { + return m.Annotations + } + return nil +} + +func (m *PodSandboxConfig) GetLinux() *LinuxPodSandboxConfig { + if m != nil { + return m.Linux + } + return nil +} + +type CreatePodSandboxRequest struct { + // The configuration for creating a PodSandBox. + Config *PodSandboxConfig `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CreatePodSandboxRequest) Reset() { *m = CreatePodSandboxRequest{} } +func (m *CreatePodSandboxRequest) String() string { return proto.CompactTextString(m) } +func (*CreatePodSandboxRequest) ProtoMessage() {} + +func (m *CreatePodSandboxRequest) GetConfig() *PodSandboxConfig { + if m != nil { + return m.Config + } + return nil +} + +type CreatePodSandboxResponse struct { + // The id of the PodSandBox + PodSandboxId *string `protobuf:"bytes,1,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CreatePodSandboxResponse) Reset() { *m = CreatePodSandboxResponse{} } +func (m *CreatePodSandboxResponse) String() string { return proto.CompactTextString(m) } +func (*CreatePodSandboxResponse) ProtoMessage() {} + +func (m *CreatePodSandboxResponse) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +type StopPodSandboxRequest struct { + // The id of the PodSandBox + PodSandboxId *string `protobuf:"bytes,1,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *StopPodSandboxRequest) Reset() { *m = StopPodSandboxRequest{} } +func (m *StopPodSandboxRequest) String() string { return proto.CompactTextString(m) } +func (*StopPodSandboxRequest) ProtoMessage() {} + +func (m *StopPodSandboxRequest) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +type StopPodSandboxResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *StopPodSandboxResponse) Reset() { *m = StopPodSandboxResponse{} } +func (m *StopPodSandboxResponse) String() string { return proto.CompactTextString(m) } +func (*StopPodSandboxResponse) ProtoMessage() {} + +type DeletePodSandboxRequest struct { + // The id of the PodSandBox + PodSandboxId *string `protobuf:"bytes,1,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *DeletePodSandboxRequest) Reset() { *m = DeletePodSandboxRequest{} } +func (m *DeletePodSandboxRequest) String() string { return proto.CompactTextString(m) } +func (*DeletePodSandboxRequest) ProtoMessage() {} + +func (m *DeletePodSandboxRequest) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +type DeletePodSandboxResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *DeletePodSandboxResponse) Reset() { *m = DeletePodSandboxResponse{} } +func (m *DeletePodSandboxResponse) String() string { return proto.CompactTextString(m) } +func (*DeletePodSandboxResponse) ProtoMessage() {} + +type PodSandboxStatusRequest struct { + // The id of the PodSandBox + PodSandboxId *string `protobuf:"bytes,1,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxStatusRequest) Reset() { *m = PodSandboxStatusRequest{} } +func (m *PodSandboxStatusRequest) String() string { return proto.CompactTextString(m) } +func (*PodSandboxStatusRequest) ProtoMessage() {} + +func (m *PodSandboxStatusRequest) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +// PodSandboxNetworkStatus is the status of the network for a PodSandbox. +type PodSandboxNetworkStatus struct { + // The IP address of the PodSandbox + Ip *string `protobuf:"bytes,1,opt,name=ip" json:"ip,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxNetworkStatus) Reset() { *m = PodSandboxNetworkStatus{} } +func (m *PodSandboxNetworkStatus) String() string { return proto.CompactTextString(m) } +func (*PodSandboxNetworkStatus) ProtoMessage() {} + +func (m *PodSandboxNetworkStatus) GetIp() string { + if m != nil && m.Ip != nil { + return *m.Ip + } + return "" +} + +// Namespace contains paths to the namespaces. +type Namespace struct { + // Network is the path to the network namespace. + Network *string `protobuf:"bytes,1,opt,name=network" json:"network,omitempty"` + // Options is the namespace options for linux namespaces + Options *NamespaceOption `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Namespace) Reset() { *m = Namespace{} } +func (m *Namespace) String() string { return proto.CompactTextString(m) } +func (*Namespace) ProtoMessage() {} + +func (m *Namespace) GetNetwork() string { + if m != nil && m.Network != nil { + return *m.Network + } + return "" +} + +func (m *Namespace) GetOptions() *NamespaceOption { + if m != nil { + return m.Options + } + return nil +} + +// LinuxSandBoxStatus contains status specific to Linux sandboxes. +type LinuxPodSandboxStatus struct { + // Namespaces contains paths to the sandbox's namespaces. + Namespaces *Namespace `protobuf:"bytes,1,opt,name=namespaces" json:"namespaces,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *LinuxPodSandboxStatus) Reset() { *m = LinuxPodSandboxStatus{} } +func (m *LinuxPodSandboxStatus) String() string { return proto.CompactTextString(m) } +func (*LinuxPodSandboxStatus) ProtoMessage() {} + +func (m *LinuxPodSandboxStatus) GetNamespaces() *Namespace { + if m != nil { + return m.Namespaces + } + return nil +} + +// PodSandboxStatus contains the status of the PodSandbox. +type PodSandboxStatus struct { + // ID of the sandbox. + Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` + // Name of the sandbox + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + // State of the sandbox. + State *PodSandBoxState `protobuf:"varint,3,opt,name=state,enum=runtime.PodSandBoxState" json:"state,omitempty"` + // Creation timestamp of the sandbox + CreatedAt *int64 `protobuf:"varint,4,opt,name=created_at" json:"created_at,omitempty"` + // Network contains network status if network is handled by the runtime. + Network *PodSandboxNetworkStatus `protobuf:"bytes,5,opt,name=network" json:"network,omitempty"` + // Linux specific status to a pod sandbox. + Linux *LinuxPodSandboxStatus `protobuf:"bytes,6,opt,name=linux" json:"linux,omitempty"` + // Labels are key value pairs that may be used to scope and select individual resources. + Labels map[string]string `protobuf:"bytes,7,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + Annotations map[string]string `protobuf:"bytes,8,rep,name=annotations" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxStatus) Reset() { *m = PodSandboxStatus{} } +func (m *PodSandboxStatus) String() string { return proto.CompactTextString(m) } +func (*PodSandboxStatus) ProtoMessage() {} + +func (m *PodSandboxStatus) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *PodSandboxStatus) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *PodSandboxStatus) GetState() PodSandBoxState { + if m != nil && m.State != nil { + return *m.State + } + return PodSandBoxState_READY +} + +func (m *PodSandboxStatus) GetCreatedAt() int64 { + if m != nil && m.CreatedAt != nil { + return *m.CreatedAt + } + return 0 +} + +func (m *PodSandboxStatus) GetNetwork() *PodSandboxNetworkStatus { + if m != nil { + return m.Network + } + return nil +} + +func (m *PodSandboxStatus) GetLinux() *LinuxPodSandboxStatus { + if m != nil { + return m.Linux + } + return nil +} + +func (m *PodSandboxStatus) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +func (m *PodSandboxStatus) GetAnnotations() map[string]string { + if m != nil { + return m.Annotations + } + return nil +} + +type PodSandboxStatusResponse struct { + // The status of the PodSandbox + Status *PodSandboxStatus `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxStatusResponse) Reset() { *m = PodSandboxStatusResponse{} } +func (m *PodSandboxStatusResponse) String() string { return proto.CompactTextString(m) } +func (*PodSandboxStatusResponse) ProtoMessage() {} + +func (m *PodSandboxStatusResponse) GetStatus() *PodSandboxStatus { + if m != nil { + return m.Status + } + return nil +} + +// PodSandboxFilter is used to filter a list of PodSandboxes. +// All those fields are combined with 'AND' +type PodSandboxFilter struct { + // Name of the sandbox. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // ID of the sandbox. + Id *string `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"` + // State of the sandbox. + State *PodSandBoxState `protobuf:"varint,3,opt,name=state,enum=runtime.PodSandBoxState" json:"state,omitempty"` + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + LabelSelector map[string]string `protobuf:"bytes,4,rep,name=label_selector" json:"label_selector,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandboxFilter) Reset() { *m = PodSandboxFilter{} } +func (m *PodSandboxFilter) String() string { return proto.CompactTextString(m) } +func (*PodSandboxFilter) ProtoMessage() {} + +func (m *PodSandboxFilter) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *PodSandboxFilter) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *PodSandboxFilter) GetState() PodSandBoxState { + if m != nil && m.State != nil { + return *m.State + } + return PodSandBoxState_READY +} + +func (m *PodSandboxFilter) GetLabelSelector() map[string]string { + if m != nil { + return m.LabelSelector + } + return nil +} + +type ListPodSandboxRequest struct { + // PodSandboxFilter to filter a list of PodSandboxes. + Filter *PodSandboxFilter `protobuf:"bytes,1,opt,name=filter" json:"filter,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListPodSandboxRequest) Reset() { *m = ListPodSandboxRequest{} } +func (m *ListPodSandboxRequest) String() string { return proto.CompactTextString(m) } +func (*ListPodSandboxRequest) ProtoMessage() {} + +func (m *ListPodSandboxRequest) GetFilter() *PodSandboxFilter { + if m != nil { + return m.Filter + } + return nil +} + +// PodSandbox contains minimal information about a sandbox. +type PodSandbox struct { + // The id of the PodSandbox + Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` + // The name of the PodSandbox + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + // The state of the PodSandbox + State *PodSandBoxState `protobuf:"varint,3,opt,name=state,enum=runtime.PodSandBoxState" json:"state,omitempty"` + // Creation timestamps of the sandbox + CreatedAt *int64 `protobuf:"varint,4,opt,name=created_at" json:"created_at,omitempty"` + // The labels of the PodSandbox + Labels map[string]string `protobuf:"bytes,5,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PodSandbox) Reset() { *m = PodSandbox{} } +func (m *PodSandbox) String() string { return proto.CompactTextString(m) } +func (*PodSandbox) ProtoMessage() {} + +func (m *PodSandbox) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *PodSandbox) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *PodSandbox) GetState() PodSandBoxState { + if m != nil && m.State != nil { + return *m.State + } + return PodSandBoxState_READY +} + +func (m *PodSandbox) GetCreatedAt() int64 { + if m != nil && m.CreatedAt != nil { + return *m.CreatedAt + } + return 0 +} + +func (m *PodSandbox) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +type ListPodSandboxResponse struct { + // List of PodSandbox + Items []*PodSandbox `protobuf:"bytes,1,rep,name=items" json:"items,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListPodSandboxResponse) Reset() { *m = ListPodSandboxResponse{} } +func (m *ListPodSandboxResponse) String() string { return proto.CompactTextString(m) } +func (*ListPodSandboxResponse) ProtoMessage() {} + +func (m *ListPodSandboxResponse) GetItems() []*PodSandbox { + if m != nil { + return m.Items + } + return nil +} + +// ImageSpec is an internal representation of an image. Currently, it wraps the +// value of a Container's Image field (e.g. imageName, imageName:tag, or +// imageName:digest), but in the future it will include more detailed +// information about the different image types. +type ImageSpec struct { + Image *string `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ImageSpec) Reset() { *m = ImageSpec{} } +func (m *ImageSpec) String() string { return proto.CompactTextString(m) } +func (*ImageSpec) ProtoMessage() {} + +func (m *ImageSpec) GetImage() string { + if m != nil && m.Image != nil { + return *m.Image + } + return "" +} + +type KeyValue struct { + Key *string `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` + Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *KeyValue) Reset() { *m = KeyValue{} } +func (m *KeyValue) String() string { return proto.CompactTextString(m) } +func (*KeyValue) ProtoMessage() {} + +func (m *KeyValue) GetKey() string { + if m != nil && m.Key != nil { + return *m.Key + } + return "" +} + +func (m *KeyValue) GetValue() string { + if m != nil && m.Value != nil { + return *m.Value + } + return "" +} + +// LinuxContainerResources specifies Linux specific configuration for +// resources. +// TODO: Consider using Resources from opencontainers/runtime-spec/specs-go +// directly. +type LinuxContainerResources struct { + // CPU CFS (Completely Fair Scheduler) period + CpuPeriod *int64 `protobuf:"varint,1,opt,name=cpu_period" json:"cpu_period,omitempty"` + // CPU CFS (Completely Fair Scheduler) quota + CpuQuota *int64 `protobuf:"varint,2,opt,name=cpu_quota" json:"cpu_quota,omitempty"` + // CPU shares (relative weight vs. other containers) + CpuShares *int64 `protobuf:"varint,3,opt,name=cpu_shares" json:"cpu_shares,omitempty"` + // Memory limit in bytes + MemoryLimitInBytes *int64 `protobuf:"varint,4,opt,name=memory_limit_in_bytes" json:"memory_limit_in_bytes,omitempty"` + // OOMScoreAdj adjusts the oom-killer score. + OomScoreAdj *int64 `protobuf:"varint,5,opt,name=oom_score_adj" json:"oom_score_adj,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *LinuxContainerResources) Reset() { *m = LinuxContainerResources{} } +func (m *LinuxContainerResources) String() string { return proto.CompactTextString(m) } +func (*LinuxContainerResources) ProtoMessage() {} + +func (m *LinuxContainerResources) GetCpuPeriod() int64 { + if m != nil && m.CpuPeriod != nil { + return *m.CpuPeriod + } + return 0 +} + +func (m *LinuxContainerResources) GetCpuQuota() int64 { + if m != nil && m.CpuQuota != nil { + return *m.CpuQuota + } + return 0 +} + +func (m *LinuxContainerResources) GetCpuShares() int64 { + if m != nil && m.CpuShares != nil { + return *m.CpuShares + } + return 0 +} + +func (m *LinuxContainerResources) GetMemoryLimitInBytes() int64 { + if m != nil && m.MemoryLimitInBytes != nil { + return *m.MemoryLimitInBytes + } + return 0 +} + +func (m *LinuxContainerResources) GetOomScoreAdj() int64 { + if m != nil && m.OomScoreAdj != nil { + return *m.OomScoreAdj + } + return 0 +} + +// SELinuxOption are the labels to be applied to the container. +type SELinuxOption struct { + User *string `protobuf:"bytes,1,opt,name=user" json:"user,omitempty"` + Role *string `protobuf:"bytes,2,opt,name=role" json:"role,omitempty"` + Type *string `protobuf:"bytes,3,opt,name=type" json:"type,omitempty"` + Level *string `protobuf:"bytes,4,opt,name=level" json:"level,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *SELinuxOption) Reset() { *m = SELinuxOption{} } +func (m *SELinuxOption) String() string { return proto.CompactTextString(m) } +func (*SELinuxOption) ProtoMessage() {} + +func (m *SELinuxOption) GetUser() string { + if m != nil && m.User != nil { + return *m.User + } + return "" +} + +func (m *SELinuxOption) GetRole() string { + if m != nil && m.Role != nil { + return *m.Role + } + return "" +} + +func (m *SELinuxOption) GetType() string { + if m != nil && m.Type != nil { + return *m.Type + } + return "" +} + +func (m *SELinuxOption) GetLevel() string { + if m != nil && m.Level != nil { + return *m.Level + } + return "" +} + +// Capability contains the container capabilities to add or drop +type Capability struct { + // List of capabilities to add. + AddCapabilities []string `protobuf:"bytes,1,rep,name=add_capabilities" json:"add_capabilities,omitempty"` + // List of capabilities to drop. + DropCapabilities []string `protobuf:"bytes,2,rep,name=drop_capabilities" json:"drop_capabilities,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Capability) Reset() { *m = Capability{} } +func (m *Capability) String() string { return proto.CompactTextString(m) } +func (*Capability) ProtoMessage() {} + +func (m *Capability) GetAddCapabilities() []string { + if m != nil { + return m.AddCapabilities + } + return nil +} + +func (m *Capability) GetDropCapabilities() []string { + if m != nil { + return m.DropCapabilities + } + return nil +} + +// LinuxContainerConfig contains platform-specific configuration for +// Linux-based containers. +type LinuxContainerConfig struct { + // Resources specification for the container. + Resources *LinuxContainerResources `protobuf:"bytes,1,opt,name=resources" json:"resources,omitempty"` + // Capabilities to add or drop. + Capabilities *Capability `protobuf:"bytes,2,opt,name=capabilities" json:"capabilities,omitempty"` + // Optional SELinux context to be applied. + SelinuxOptions *SELinuxOption `protobuf:"bytes,3,opt,name=selinux_options" json:"selinux_options,omitempty"` + // User contains the user for the container process. + User *LinuxUser `protobuf:"bytes,4,opt,name=user" json:"user,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *LinuxContainerConfig) Reset() { *m = LinuxContainerConfig{} } +func (m *LinuxContainerConfig) String() string { return proto.CompactTextString(m) } +func (*LinuxContainerConfig) ProtoMessage() {} + +func (m *LinuxContainerConfig) GetResources() *LinuxContainerResources { + if m != nil { + return m.Resources + } + return nil +} + +func (m *LinuxContainerConfig) GetCapabilities() *Capability { + if m != nil { + return m.Capabilities + } + return nil +} + +func (m *LinuxContainerConfig) GetSelinuxOptions() *SELinuxOption { + if m != nil { + return m.SelinuxOptions + } + return nil +} + +func (m *LinuxContainerConfig) GetUser() *LinuxUser { + if m != nil { + return m.User + } + return nil +} + +type LinuxUser struct { + // uid specifies the user ID the container process has. + Uid *int64 `protobuf:"varint,1,opt,name=uid" json:"uid,omitempty"` + // gid specifies the group ID the container process has. + Gid *int64 `protobuf:"varint,2,opt,name=gid" json:"gid,omitempty"` + // additional_gids specifies additional GIDs the container process has. + AdditionalGids []int64 `protobuf:"varint,3,rep,name=additional_gids" json:"additional_gids,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *LinuxUser) Reset() { *m = LinuxUser{} } +func (m *LinuxUser) String() string { return proto.CompactTextString(m) } +func (*LinuxUser) ProtoMessage() {} + +func (m *LinuxUser) GetUid() int64 { + if m != nil && m.Uid != nil { + return *m.Uid + } + return 0 +} + +func (m *LinuxUser) GetGid() int64 { + if m != nil && m.Gid != nil { + return *m.Gid + } + return 0 +} + +func (m *LinuxUser) GetAdditionalGids() []int64 { + if m != nil { + return m.AdditionalGids + } + return nil +} + +type ContainerConfig struct { + // Name of the container. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // Image to use. + Image *ImageSpec `protobuf:"bytes,2,opt,name=image" json:"image,omitempty"` + // Command to execute (i.e., entrypoint for docker) + Command []string `protobuf:"bytes,3,rep,name=command" json:"command,omitempty"` + // Args for the Command (i.e., command for docker) + Args []string `protobuf:"bytes,4,rep,name=args" json:"args,omitempty"` + // Current working directory of the command. + WorkingDir *string `protobuf:"bytes,5,opt,name=working_dir" json:"working_dir,omitempty"` + // List of environment variable to set in the container + Envs []*KeyValue `protobuf:"bytes,6,rep,name=envs" json:"envs,omitempty"` + // Mounts specifies mounts for the container + Mounts []*Mount `protobuf:"bytes,7,rep,name=mounts" json:"mounts,omitempty"` + // Labels are key value pairs that may be used to scope and select individual resources. + // Label keys are of the form: + // label-key ::= prefixed-name | name + // prefixed-name ::= prefix '/' name + // prefix ::= DNS_SUBDOMAIN + // name ::= DNS_LABEL + Labels map[string]string `protobuf:"bytes,8,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + Annotations map[string]string `protobuf:"bytes,9,rep,name=annotations" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // If set, run container in privileged mode. + // Processes in privileged containers are essentially equivalent to root on the host. + Privileged *bool `protobuf:"varint,10,opt,name=privileged" json:"privileged,omitempty"` + // If set, the root filesystem of the container is read-only. + ReadonlyRootfs *bool `protobuf:"varint,11,opt,name=readonly_rootfs" json:"readonly_rootfs,omitempty"` + // Path relative to PodSandboxConfig.LogDirectory for container to store + // the log (STDOUT and STDERR) on the host. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + LogPath *string `protobuf:"bytes,12,opt,name=log_path" json:"log_path,omitempty"` + // Variables for interactive containers, these have very specialized + // use-cases (e.g. debugging). + // TODO: Determine if we need to continue supporting these fields that are + // part of Kubernetes's Container Spec. + Stdin *bool `protobuf:"varint,13,opt,name=stdin" json:"stdin,omitempty"` + StdinOnce *bool `protobuf:"varint,14,opt,name=stdin_once" json:"stdin_once,omitempty"` + Tty *bool `protobuf:"varint,15,opt,name=tty" json:"tty,omitempty"` + // Linux contains configuration specific to Linux containers. + Linux *LinuxContainerConfig `protobuf:"bytes,16,opt,name=linux" json:"linux,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContainerConfig) Reset() { *m = ContainerConfig{} } +func (m *ContainerConfig) String() string { return proto.CompactTextString(m) } +func (*ContainerConfig) ProtoMessage() {} + +func (m *ContainerConfig) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ContainerConfig) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +func (m *ContainerConfig) GetCommand() []string { + if m != nil { + return m.Command + } + return nil +} + +func (m *ContainerConfig) GetArgs() []string { + if m != nil { + return m.Args + } + return nil +} + +func (m *ContainerConfig) GetWorkingDir() string { + if m != nil && m.WorkingDir != nil { + return *m.WorkingDir + } + return "" +} + +func (m *ContainerConfig) GetEnvs() []*KeyValue { + if m != nil { + return m.Envs + } + return nil +} + +func (m *ContainerConfig) GetMounts() []*Mount { + if m != nil { + return m.Mounts + } + return nil +} + +func (m *ContainerConfig) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +func (m *ContainerConfig) GetAnnotations() map[string]string { + if m != nil { + return m.Annotations + } + return nil +} + +func (m *ContainerConfig) GetPrivileged() bool { + if m != nil && m.Privileged != nil { + return *m.Privileged + } + return false +} + +func (m *ContainerConfig) GetReadonlyRootfs() bool { + if m != nil && m.ReadonlyRootfs != nil { + return *m.ReadonlyRootfs + } + return false +} + +func (m *ContainerConfig) GetLogPath() string { + if m != nil && m.LogPath != nil { + return *m.LogPath + } + return "" +} + +func (m *ContainerConfig) GetStdin() bool { + if m != nil && m.Stdin != nil { + return *m.Stdin + } + return false +} + +func (m *ContainerConfig) GetStdinOnce() bool { + if m != nil && m.StdinOnce != nil { + return *m.StdinOnce + } + return false +} + +func (m *ContainerConfig) GetTty() bool { + if m != nil && m.Tty != nil { + return *m.Tty + } + return false +} + +func (m *ContainerConfig) GetLinux() *LinuxContainerConfig { + if m != nil { + return m.Linux + } + return nil +} + +type CreateContainerRequest struct { + // The id of the PodSandbox + PodSandboxId *string `protobuf:"bytes,1,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + // The config of the container + Config *ContainerConfig `protobuf:"bytes,2,opt,name=config" json:"config,omitempty"` + // The config of the PodSandbox + SandboxConfig *PodSandboxConfig `protobuf:"bytes,3,opt,name=sandbox_config" json:"sandbox_config,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CreateContainerRequest) Reset() { *m = CreateContainerRequest{} } +func (m *CreateContainerRequest) String() string { return proto.CompactTextString(m) } +func (*CreateContainerRequest) ProtoMessage() {} + +func (m *CreateContainerRequest) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +func (m *CreateContainerRequest) GetConfig() *ContainerConfig { + if m != nil { + return m.Config + } + return nil +} + +func (m *CreateContainerRequest) GetSandboxConfig() *PodSandboxConfig { + if m != nil { + return m.SandboxConfig + } + return nil +} + +type CreateContainerResponse struct { + // The id of the created container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *CreateContainerResponse) Reset() { *m = CreateContainerResponse{} } +func (m *CreateContainerResponse) String() string { return proto.CompactTextString(m) } +func (*CreateContainerResponse) ProtoMessage() {} + +func (m *CreateContainerResponse) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +type StartContainerRequest struct { + // The id of the container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *StartContainerRequest) Reset() { *m = StartContainerRequest{} } +func (m *StartContainerRequest) String() string { return proto.CompactTextString(m) } +func (*StartContainerRequest) ProtoMessage() {} + +func (m *StartContainerRequest) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +type StartContainerResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *StartContainerResponse) Reset() { *m = StartContainerResponse{} } +func (m *StartContainerResponse) String() string { return proto.CompactTextString(m) } +func (*StartContainerResponse) ProtoMessage() {} + +type StopContainerRequest struct { + // The id of the container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + // Timeout in seconds to stop the container + Timeout *int64 `protobuf:"varint,2,opt,name=timeout" json:"timeout,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *StopContainerRequest) Reset() { *m = StopContainerRequest{} } +func (m *StopContainerRequest) String() string { return proto.CompactTextString(m) } +func (*StopContainerRequest) ProtoMessage() {} + +func (m *StopContainerRequest) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +func (m *StopContainerRequest) GetTimeout() int64 { + if m != nil && m.Timeout != nil { + return *m.Timeout + } + return 0 +} + +type StopContainerResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *StopContainerResponse) Reset() { *m = StopContainerResponse{} } +func (m *StopContainerResponse) String() string { return proto.CompactTextString(m) } +func (*StopContainerResponse) ProtoMessage() {} + +type RemoveContainerRequest struct { + // The id of the container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *RemoveContainerRequest) Reset() { *m = RemoveContainerRequest{} } +func (m *RemoveContainerRequest) String() string { return proto.CompactTextString(m) } +func (*RemoveContainerRequest) ProtoMessage() {} + +func (m *RemoveContainerRequest) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +type RemoveContainerResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *RemoveContainerResponse) Reset() { *m = RemoveContainerResponse{} } +func (m *RemoveContainerResponse) String() string { return proto.CompactTextString(m) } +func (*RemoveContainerResponse) ProtoMessage() {} + +// ContainerFilter is used to filter containers. +// All those fields are combined with 'AND' +type ContainerFilter struct { + // Name of the container. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // ID of the container. + Id *string `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"` + // State of the contianer. + State *ContainerState `protobuf:"varint,3,opt,name=state,enum=runtime.ContainerState" json:"state,omitempty"` + // The id of the pod sandbox + PodSandboxId *string `protobuf:"bytes,4,opt,name=pod_sandbox_id" json:"pod_sandbox_id,omitempty"` + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + LabelSelector map[string]string `protobuf:"bytes,5,rep,name=label_selector" json:"label_selector,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContainerFilter) Reset() { *m = ContainerFilter{} } +func (m *ContainerFilter) String() string { return proto.CompactTextString(m) } +func (*ContainerFilter) ProtoMessage() {} + +func (m *ContainerFilter) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ContainerFilter) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *ContainerFilter) GetState() ContainerState { + if m != nil && m.State != nil { + return *m.State + } + return ContainerState_CREATED +} + +func (m *ContainerFilter) GetPodSandboxId() string { + if m != nil && m.PodSandboxId != nil { + return *m.PodSandboxId + } + return "" +} + +func (m *ContainerFilter) GetLabelSelector() map[string]string { + if m != nil { + return m.LabelSelector + } + return nil +} + +type ListContainersRequest struct { + Filter *ContainerFilter `protobuf:"bytes,1,opt,name=filter" json:"filter,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListContainersRequest) Reset() { *m = ListContainersRequest{} } +func (m *ListContainersRequest) String() string { return proto.CompactTextString(m) } +func (*ListContainersRequest) ProtoMessage() {} + +func (m *ListContainersRequest) GetFilter() *ContainerFilter { + if m != nil { + return m.Filter + } + return nil +} + +// Container provides the runtime information for a container, such as ID, hash, +// state of the container. +type Container struct { + // The ID of the container, used by the container runtime to identify + // a container. + Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` + // The name of the container + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + // The spec of the image + Image *ImageSpec `protobuf:"bytes,3,opt,name=image" json:"image,omitempty"` + // Reference to the image in use. For most runtimes, this should be an + // image ID. + ImageRef *string `protobuf:"bytes,4,opt,name=image_ref" json:"image_ref,omitempty"` + // State is the state of the container. + State *ContainerState `protobuf:"varint,5,opt,name=state,enum=runtime.ContainerState" json:"state,omitempty"` + // Labels are key value pairs that may be used to scope and select individual resources. + Labels map[string]string `protobuf:"bytes,6,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Container) Reset() { *m = Container{} } +func (m *Container) String() string { return proto.CompactTextString(m) } +func (*Container) ProtoMessage() {} + +func (m *Container) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *Container) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *Container) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +func (m *Container) GetImageRef() string { + if m != nil && m.ImageRef != nil { + return *m.ImageRef + } + return "" +} + +func (m *Container) GetState() ContainerState { + if m != nil && m.State != nil { + return *m.State + } + return ContainerState_CREATED +} + +func (m *Container) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +type ListContainersResponse struct { + // List of containers + Containers []*Container `protobuf:"bytes,1,rep,name=containers" json:"containers,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListContainersResponse) Reset() { *m = ListContainersResponse{} } +func (m *ListContainersResponse) String() string { return proto.CompactTextString(m) } +func (*ListContainersResponse) ProtoMessage() {} + +func (m *ListContainersResponse) GetContainers() []*Container { + if m != nil { + return m.Containers + } + return nil +} + +type ContainerStatusRequest struct { + // The id of the container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContainerStatusRequest) Reset() { *m = ContainerStatusRequest{} } +func (m *ContainerStatusRequest) String() string { return proto.CompactTextString(m) } +func (*ContainerStatusRequest) ProtoMessage() {} + +func (m *ContainerStatusRequest) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +// ContainerStatus represents the status of a container. +type ContainerStatus struct { + // ID of the container. + Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` + // Name of the container. + Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` + // Status of the container. + State *ContainerState `protobuf:"varint,3,opt,name=state,enum=runtime.ContainerState" json:"state,omitempty"` + // Creation time of the container. + CreatedAt *int64 `protobuf:"varint,4,opt,name=created_at" json:"created_at,omitempty"` + // Start time of the container. + StartedAt *int64 `protobuf:"varint,5,opt,name=started_at" json:"started_at,omitempty"` + // Finish time of the container. + FinishedAt *int64 `protobuf:"varint,6,opt,name=finished_at" json:"finished_at,omitempty"` + // Exit code of the container. + ExitCode *int32 `protobuf:"varint,7,opt,name=exit_code" json:"exit_code,omitempty"` + // The spec of the image + Image *ImageSpec `protobuf:"bytes,8,opt,name=image" json:"image,omitempty"` + // Reference to the image in use. For most runtimes, this should be an + // image ID + ImageRef *string `protobuf:"bytes,9,opt,name=image_ref" json:"image_ref,omitempty"` + // A string explains why container is in such a status. + Reason *string `protobuf:"bytes,10,opt,name=reason" json:"reason,omitempty"` + // Labels are key value pairs that may be used to scope and select individual resources. + Labels map[string]string `protobuf:"bytes,11,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Annotations is an unstructured key value map. + Annotations map[string]string `protobuf:"bytes,12,rep,name=annotations" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Mounts specifies mounts for the container + Mounts []*Mount `protobuf:"bytes,13,rep,name=mounts" json:"mounts,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContainerStatus) Reset() { *m = ContainerStatus{} } +func (m *ContainerStatus) String() string { return proto.CompactTextString(m) } +func (*ContainerStatus) ProtoMessage() {} + +func (m *ContainerStatus) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *ContainerStatus) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ContainerStatus) GetState() ContainerState { + if m != nil && m.State != nil { + return *m.State + } + return ContainerState_CREATED +} + +func (m *ContainerStatus) GetCreatedAt() int64 { + if m != nil && m.CreatedAt != nil { + return *m.CreatedAt + } + return 0 +} + +func (m *ContainerStatus) GetStartedAt() int64 { + if m != nil && m.StartedAt != nil { + return *m.StartedAt + } + return 0 +} + +func (m *ContainerStatus) GetFinishedAt() int64 { + if m != nil && m.FinishedAt != nil { + return *m.FinishedAt + } + return 0 +} + +func (m *ContainerStatus) GetExitCode() int32 { + if m != nil && m.ExitCode != nil { + return *m.ExitCode + } + return 0 +} + +func (m *ContainerStatus) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +func (m *ContainerStatus) GetImageRef() string { + if m != nil && m.ImageRef != nil { + return *m.ImageRef + } + return "" +} + +func (m *ContainerStatus) GetReason() string { + if m != nil && m.Reason != nil { + return *m.Reason + } + return "" +} + +func (m *ContainerStatus) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +func (m *ContainerStatus) GetAnnotations() map[string]string { + if m != nil { + return m.Annotations + } + return nil +} + +func (m *ContainerStatus) GetMounts() []*Mount { + if m != nil { + return m.Mounts + } + return nil +} + +type ContainerStatusResponse struct { + // The status of the container + Status *ContainerStatus `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ContainerStatusResponse) Reset() { *m = ContainerStatusResponse{} } +func (m *ContainerStatusResponse) String() string { return proto.CompactTextString(m) } +func (*ContainerStatusResponse) ProtoMessage() {} + +func (m *ContainerStatusResponse) GetStatus() *ContainerStatus { + if m != nil { + return m.Status + } + return nil +} + +type ExecRequest struct { + // The id of the container + ContainerId *string `protobuf:"bytes,1,opt,name=container_id" json:"container_id,omitempty"` + // The cmd to execute + Cmd []string `protobuf:"bytes,2,rep,name=cmd" json:"cmd,omitempty"` + // Whether use tty + Tty *bool `protobuf:"varint,3,opt,name=tty" json:"tty,omitempty"` + // Streaming stdin + Stdin []byte `protobuf:"bytes,4,opt,name=stdin" json:"stdin,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ExecRequest) Reset() { *m = ExecRequest{} } +func (m *ExecRequest) String() string { return proto.CompactTextString(m) } +func (*ExecRequest) ProtoMessage() {} + +func (m *ExecRequest) GetContainerId() string { + if m != nil && m.ContainerId != nil { + return *m.ContainerId + } + return "" +} + +func (m *ExecRequest) GetCmd() []string { + if m != nil { + return m.Cmd + } + return nil +} + +func (m *ExecRequest) GetTty() bool { + if m != nil && m.Tty != nil { + return *m.Tty + } + return false +} + +func (m *ExecRequest) GetStdin() []byte { + if m != nil { + return m.Stdin + } + return nil +} + +type ExecResponse struct { + // Streaming stdout + Stdout []byte `protobuf:"bytes,1,opt,name=stdout" json:"stdout,omitempty"` + // Streaming stderr + Stderr []byte `protobuf:"bytes,2,opt,name=stderr" json:"stderr,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ExecResponse) Reset() { *m = ExecResponse{} } +func (m *ExecResponse) String() string { return proto.CompactTextString(m) } +func (*ExecResponse) ProtoMessage() {} + +func (m *ExecResponse) GetStdout() []byte { + if m != nil { + return m.Stdout + } + return nil +} + +func (m *ExecResponse) GetStderr() []byte { + if m != nil { + return m.Stderr + } + return nil +} + +type ImageFilter struct { + // The spec of the image + Image *ImageSpec `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ImageFilter) Reset() { *m = ImageFilter{} } +func (m *ImageFilter) String() string { return proto.CompactTextString(m) } +func (*ImageFilter) ProtoMessage() {} + +func (m *ImageFilter) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +type ListImagesRequest struct { + // The filter to list images + Filter *ImageFilter `protobuf:"bytes,1,opt,name=filter" json:"filter,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListImagesRequest) Reset() { *m = ListImagesRequest{} } +func (m *ListImagesRequest) String() string { return proto.CompactTextString(m) } +func (*ListImagesRequest) ProtoMessage() {} + +func (m *ListImagesRequest) GetFilter() *ImageFilter { + if m != nil { + return m.Filter + } + return nil +} + +// Basic information about a container image. +type Image struct { + // ID of the image. + Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` + // Other names by which this image is known. + RepoTags []string `protobuf:"bytes,2,rep,name=repo_tags" json:"repo_tags,omitempty"` + // Digests by which this image is known. + RepoDigests []string `protobuf:"bytes,3,rep,name=repo_digests" json:"repo_digests,omitempty"` + // The size of the image in bytes. + Size_ *uint64 `protobuf:"varint,4,opt,name=size" json:"size,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *Image) Reset() { *m = Image{} } +func (m *Image) String() string { return proto.CompactTextString(m) } +func (*Image) ProtoMessage() {} + +func (m *Image) GetId() string { + if m != nil && m.Id != nil { + return *m.Id + } + return "" +} + +func (m *Image) GetRepoTags() []string { + if m != nil { + return m.RepoTags + } + return nil +} + +func (m *Image) GetRepoDigests() []string { + if m != nil { + return m.RepoDigests + } + return nil +} + +func (m *Image) GetSize_() uint64 { + if m != nil && m.Size_ != nil { + return *m.Size_ + } + return 0 +} + +type ListImagesResponse struct { + // List of images + Images []*Image `protobuf:"bytes,1,rep,name=images" json:"images,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ListImagesResponse) Reset() { *m = ListImagesResponse{} } +func (m *ListImagesResponse) String() string { return proto.CompactTextString(m) } +func (*ListImagesResponse) ProtoMessage() {} + +func (m *ListImagesResponse) GetImages() []*Image { + if m != nil { + return m.Images + } + return nil +} + +type ImageStatusRequest struct { + // The spec of the image + Image *ImageSpec `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ImageStatusRequest) Reset() { *m = ImageStatusRequest{} } +func (m *ImageStatusRequest) String() string { return proto.CompactTextString(m) } +func (*ImageStatusRequest) ProtoMessage() {} + +func (m *ImageStatusRequest) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +type ImageStatusResponse struct { + // The status of the image + Image *Image `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ImageStatusResponse) Reset() { *m = ImageStatusResponse{} } +func (m *ImageStatusResponse) String() string { return proto.CompactTextString(m) } +func (*ImageStatusResponse) ProtoMessage() {} + +func (m *ImageStatusResponse) GetImage() *Image { + if m != nil { + return m.Image + } + return nil +} + +// AuthConfig contains authorization information for connecting to a registry. +type AuthConfig struct { + Username *string `protobuf:"bytes,1,opt,name=username" json:"username,omitempty"` + Password *string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` + Auth *string `protobuf:"bytes,3,opt,name=auth" json:"auth,omitempty"` + ServerAddress *string `protobuf:"bytes,4,opt,name=server_address" json:"server_address,omitempty"` + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + IdentityToken *string `protobuf:"bytes,5,opt,name=identity_token" json:"identity_token,omitempty"` + // RegistryToken is a bearer token to be sent to a registry + RegistryToken *string `protobuf:"bytes,6,opt,name=registry_token" json:"registry_token,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *AuthConfig) Reset() { *m = AuthConfig{} } +func (m *AuthConfig) String() string { return proto.CompactTextString(m) } +func (*AuthConfig) ProtoMessage() {} + +func (m *AuthConfig) GetUsername() string { + if m != nil && m.Username != nil { + return *m.Username + } + return "" +} + +func (m *AuthConfig) GetPassword() string { + if m != nil && m.Password != nil { + return *m.Password + } + return "" +} + +func (m *AuthConfig) GetAuth() string { + if m != nil && m.Auth != nil { + return *m.Auth + } + return "" +} + +func (m *AuthConfig) GetServerAddress() string { + if m != nil && m.ServerAddress != nil { + return *m.ServerAddress + } + return "" +} + +func (m *AuthConfig) GetIdentityToken() string { + if m != nil && m.IdentityToken != nil { + return *m.IdentityToken + } + return "" +} + +func (m *AuthConfig) GetRegistryToken() string { + if m != nil && m.RegistryToken != nil { + return *m.RegistryToken + } + return "" +} + +type PullImageRequest struct { + // The spec of the image + Image *ImageSpec `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + // The auth config for pulling image + Auth *AuthConfig `protobuf:"bytes,2,opt,name=auth" json:"auth,omitempty"` + // The config of the PodSandbox, which is used to pull image in PodSandbox context + SandboxConfig *PodSandboxConfig `protobuf:"bytes,3,opt,name=sandbox_config" json:"sandbox_config,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *PullImageRequest) Reset() { *m = PullImageRequest{} } +func (m *PullImageRequest) String() string { return proto.CompactTextString(m) } +func (*PullImageRequest) ProtoMessage() {} + +func (m *PullImageRequest) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +func (m *PullImageRequest) GetAuth() *AuthConfig { + if m != nil { + return m.Auth + } + return nil +} + +func (m *PullImageRequest) GetSandboxConfig() *PodSandboxConfig { + if m != nil { + return m.SandboxConfig + } + return nil +} + +type PullImageResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *PullImageResponse) Reset() { *m = PullImageResponse{} } +func (m *PullImageResponse) String() string { return proto.CompactTextString(m) } +func (*PullImageResponse) ProtoMessage() {} + +type RemoveImageRequest struct { + // The spec of the image + Image *ImageSpec `protobuf:"bytes,1,opt,name=image" json:"image,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *RemoveImageRequest) Reset() { *m = RemoveImageRequest{} } +func (m *RemoveImageRequest) String() string { return proto.CompactTextString(m) } +func (*RemoveImageRequest) ProtoMessage() {} + +func (m *RemoveImageRequest) GetImage() *ImageSpec { + if m != nil { + return m.Image + } + return nil +} + +type RemoveImageResponse struct { + XXX_unrecognized []byte `json:"-"` +} + +func (m *RemoveImageResponse) Reset() { *m = RemoveImageResponse{} } +func (m *RemoveImageResponse) String() string { return proto.CompactTextString(m) } +func (*RemoveImageResponse) ProtoMessage() {} + +func init() { + proto.RegisterType((*VersionRequest)(nil), "runtime.VersionRequest") + proto.RegisterType((*VersionResponse)(nil), "runtime.VersionResponse") + proto.RegisterType((*DNSOption)(nil), "runtime.DNSOption") + proto.RegisterType((*PortMapping)(nil), "runtime.PortMapping") + proto.RegisterType((*Mount)(nil), "runtime.Mount") + proto.RegisterType((*ResourceRequirements)(nil), "runtime.ResourceRequirements") + proto.RegisterType((*PodSandboxResources)(nil), "runtime.PodSandboxResources") + proto.RegisterType((*NamespaceOption)(nil), "runtime.NamespaceOption") + proto.RegisterType((*LinuxPodSandboxConfig)(nil), "runtime.LinuxPodSandboxConfig") + proto.RegisterType((*PodSandboxConfig)(nil), "runtime.PodSandboxConfig") + proto.RegisterType((*CreatePodSandboxRequest)(nil), "runtime.CreatePodSandboxRequest") + proto.RegisterType((*CreatePodSandboxResponse)(nil), "runtime.CreatePodSandboxResponse") + proto.RegisterType((*StopPodSandboxRequest)(nil), "runtime.StopPodSandboxRequest") + proto.RegisterType((*StopPodSandboxResponse)(nil), "runtime.StopPodSandboxResponse") + proto.RegisterType((*DeletePodSandboxRequest)(nil), "runtime.DeletePodSandboxRequest") + proto.RegisterType((*DeletePodSandboxResponse)(nil), "runtime.DeletePodSandboxResponse") + proto.RegisterType((*PodSandboxStatusRequest)(nil), "runtime.PodSandboxStatusRequest") + proto.RegisterType((*PodSandboxNetworkStatus)(nil), "runtime.PodSandboxNetworkStatus") + proto.RegisterType((*Namespace)(nil), "runtime.Namespace") + proto.RegisterType((*LinuxPodSandboxStatus)(nil), "runtime.LinuxPodSandboxStatus") + proto.RegisterType((*PodSandboxStatus)(nil), "runtime.PodSandboxStatus") + proto.RegisterType((*PodSandboxStatusResponse)(nil), "runtime.PodSandboxStatusResponse") + proto.RegisterType((*PodSandboxFilter)(nil), "runtime.PodSandboxFilter") + proto.RegisterType((*ListPodSandboxRequest)(nil), "runtime.ListPodSandboxRequest") + proto.RegisterType((*PodSandbox)(nil), "runtime.PodSandbox") + proto.RegisterType((*ListPodSandboxResponse)(nil), "runtime.ListPodSandboxResponse") + proto.RegisterType((*ImageSpec)(nil), "runtime.ImageSpec") + proto.RegisterType((*KeyValue)(nil), "runtime.KeyValue") + proto.RegisterType((*LinuxContainerResources)(nil), "runtime.LinuxContainerResources") + proto.RegisterType((*SELinuxOption)(nil), "runtime.SELinuxOption") + proto.RegisterType((*Capability)(nil), "runtime.Capability") + proto.RegisterType((*LinuxContainerConfig)(nil), "runtime.LinuxContainerConfig") + proto.RegisterType((*LinuxUser)(nil), "runtime.LinuxUser") + proto.RegisterType((*ContainerConfig)(nil), "runtime.ContainerConfig") + proto.RegisterType((*CreateContainerRequest)(nil), "runtime.CreateContainerRequest") + proto.RegisterType((*CreateContainerResponse)(nil), "runtime.CreateContainerResponse") + proto.RegisterType((*StartContainerRequest)(nil), "runtime.StartContainerRequest") + proto.RegisterType((*StartContainerResponse)(nil), "runtime.StartContainerResponse") + proto.RegisterType((*StopContainerRequest)(nil), "runtime.StopContainerRequest") + proto.RegisterType((*StopContainerResponse)(nil), "runtime.StopContainerResponse") + proto.RegisterType((*RemoveContainerRequest)(nil), "runtime.RemoveContainerRequest") + proto.RegisterType((*RemoveContainerResponse)(nil), "runtime.RemoveContainerResponse") + proto.RegisterType((*ContainerFilter)(nil), "runtime.ContainerFilter") + proto.RegisterType((*ListContainersRequest)(nil), "runtime.ListContainersRequest") + proto.RegisterType((*Container)(nil), "runtime.Container") + proto.RegisterType((*ListContainersResponse)(nil), "runtime.ListContainersResponse") + proto.RegisterType((*ContainerStatusRequest)(nil), "runtime.ContainerStatusRequest") + proto.RegisterType((*ContainerStatus)(nil), "runtime.ContainerStatus") + proto.RegisterType((*ContainerStatusResponse)(nil), "runtime.ContainerStatusResponse") + proto.RegisterType((*ExecRequest)(nil), "runtime.ExecRequest") + proto.RegisterType((*ExecResponse)(nil), "runtime.ExecResponse") + proto.RegisterType((*ImageFilter)(nil), "runtime.ImageFilter") + proto.RegisterType((*ListImagesRequest)(nil), "runtime.ListImagesRequest") + proto.RegisterType((*Image)(nil), "runtime.Image") + proto.RegisterType((*ListImagesResponse)(nil), "runtime.ListImagesResponse") + proto.RegisterType((*ImageStatusRequest)(nil), "runtime.ImageStatusRequest") + proto.RegisterType((*ImageStatusResponse)(nil), "runtime.ImageStatusResponse") + proto.RegisterType((*AuthConfig)(nil), "runtime.AuthConfig") + proto.RegisterType((*PullImageRequest)(nil), "runtime.PullImageRequest") + proto.RegisterType((*PullImageResponse)(nil), "runtime.PullImageResponse") + proto.RegisterType((*RemoveImageRequest)(nil), "runtime.RemoveImageRequest") + proto.RegisterType((*RemoveImageResponse)(nil), "runtime.RemoveImageResponse") + proto.RegisterEnum("runtime.Protocol", Protocol_name, Protocol_value) + proto.RegisterEnum("runtime.PodSandBoxState", PodSandBoxState_name, PodSandBoxState_value) + proto.RegisterEnum("runtime.ContainerState", ContainerState_name, ContainerState_value) +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// Client API for RuntimeService service + +type RuntimeServiceClient interface { + // Version returns the runtime name, runtime version and runtime API version + Version(ctx context.Context, in *VersionRequest, opts ...grpc.CallOption) (*VersionResponse, error) + // CreatePodSandbox creates a pod-level sandbox. + // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 + CreatePodSandbox(ctx context.Context, in *CreatePodSandboxRequest, opts ...grpc.CallOption) (*CreatePodSandboxResponse, error) + // StopPodSandbox stops the sandbox. If there are any running containers in the + // sandbox, they should be force terminated. + StopPodSandbox(ctx context.Context, in *StopPodSandboxRequest, opts ...grpc.CallOption) (*StopPodSandboxResponse, error) + // DeletePodSandbox deletes the sandbox. If there are any running containers in the + // sandbox, they should be force deleted. + DeletePodSandbox(ctx context.Context, in *DeletePodSandboxRequest, opts ...grpc.CallOption) (*DeletePodSandboxResponse, error) + // PodSandboxStatus returns the Status of the PodSandbox. + PodSandboxStatus(ctx context.Context, in *PodSandboxStatusRequest, opts ...grpc.CallOption) (*PodSandboxStatusResponse, error) + // ListPodSandbox returns a list of SandBox. + ListPodSandbox(ctx context.Context, in *ListPodSandboxRequest, opts ...grpc.CallOption) (*ListPodSandboxResponse, error) + // CreateContainer creates a new container in specified PodSandbox + CreateContainer(ctx context.Context, in *CreateContainerRequest, opts ...grpc.CallOption) (*CreateContainerResponse, error) + // StartContainer starts the container. + StartContainer(ctx context.Context, in *StartContainerRequest, opts ...grpc.CallOption) (*StartContainerResponse, error) + // StopContainer stops a running container with a grace period (i.e., timeout). + StopContainer(ctx context.Context, in *StopContainerRequest, opts ...grpc.CallOption) (*StopContainerResponse, error) + // RemoveContainer removes the container. If the container is running, the container + // should be force removed. + RemoveContainer(ctx context.Context, in *RemoveContainerRequest, opts ...grpc.CallOption) (*RemoveContainerResponse, error) + // ListContainers lists all containers by filters. + ListContainers(ctx context.Context, in *ListContainersRequest, opts ...grpc.CallOption) (*ListContainersResponse, error) + // ContainerStatus returns status of the container. + ContainerStatus(ctx context.Context, in *ContainerStatusRequest, opts ...grpc.CallOption) (*ContainerStatusResponse, error) + // Exec executes the command in the container. + Exec(ctx context.Context, opts ...grpc.CallOption) (RuntimeService_ExecClient, error) +} + +type runtimeServiceClient struct { + cc *grpc.ClientConn +} + +func NewRuntimeServiceClient(cc *grpc.ClientConn) RuntimeServiceClient { + return &runtimeServiceClient{cc} +} + +func (c *runtimeServiceClient) Version(ctx context.Context, in *VersionRequest, opts ...grpc.CallOption) (*VersionResponse, error) { + out := new(VersionResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/Version", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) CreatePodSandbox(ctx context.Context, in *CreatePodSandboxRequest, opts ...grpc.CallOption) (*CreatePodSandboxResponse, error) { + out := new(CreatePodSandboxResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/CreatePodSandbox", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) StopPodSandbox(ctx context.Context, in *StopPodSandboxRequest, opts ...grpc.CallOption) (*StopPodSandboxResponse, error) { + out := new(StopPodSandboxResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/StopPodSandbox", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) DeletePodSandbox(ctx context.Context, in *DeletePodSandboxRequest, opts ...grpc.CallOption) (*DeletePodSandboxResponse, error) { + out := new(DeletePodSandboxResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/DeletePodSandbox", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) PodSandboxStatus(ctx context.Context, in *PodSandboxStatusRequest, opts ...grpc.CallOption) (*PodSandboxStatusResponse, error) { + out := new(PodSandboxStatusResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/PodSandboxStatus", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) ListPodSandbox(ctx context.Context, in *ListPodSandboxRequest, opts ...grpc.CallOption) (*ListPodSandboxResponse, error) { + out := new(ListPodSandboxResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/ListPodSandbox", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) CreateContainer(ctx context.Context, in *CreateContainerRequest, opts ...grpc.CallOption) (*CreateContainerResponse, error) { + out := new(CreateContainerResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/CreateContainer", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) StartContainer(ctx context.Context, in *StartContainerRequest, opts ...grpc.CallOption) (*StartContainerResponse, error) { + out := new(StartContainerResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/StartContainer", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) StopContainer(ctx context.Context, in *StopContainerRequest, opts ...grpc.CallOption) (*StopContainerResponse, error) { + out := new(StopContainerResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/StopContainer", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) RemoveContainer(ctx context.Context, in *RemoveContainerRequest, opts ...grpc.CallOption) (*RemoveContainerResponse, error) { + out := new(RemoveContainerResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/RemoveContainer", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) ListContainers(ctx context.Context, in *ListContainersRequest, opts ...grpc.CallOption) (*ListContainersResponse, error) { + out := new(ListContainersResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/ListContainers", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) ContainerStatus(ctx context.Context, in *ContainerStatusRequest, opts ...grpc.CallOption) (*ContainerStatusResponse, error) { + out := new(ContainerStatusResponse) + err := grpc.Invoke(ctx, "/runtime.RuntimeService/ContainerStatus", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *runtimeServiceClient) Exec(ctx context.Context, opts ...grpc.CallOption) (RuntimeService_ExecClient, error) { + stream, err := grpc.NewClientStream(ctx, &_RuntimeService_serviceDesc.Streams[0], c.cc, "/runtime.RuntimeService/Exec", opts...) + if err != nil { + return nil, err + } + x := &runtimeServiceExecClient{stream} + return x, nil +} + +type RuntimeService_ExecClient interface { + Send(*ExecRequest) error + Recv() (*ExecResponse, error) + grpc.ClientStream +} + +type runtimeServiceExecClient struct { + grpc.ClientStream +} + +func (x *runtimeServiceExecClient) Send(m *ExecRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *runtimeServiceExecClient) Recv() (*ExecResponse, error) { + m := new(ExecResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// Server API for RuntimeService service + +type RuntimeServiceServer interface { + // Version returns the runtime name, runtime version and runtime API version + Version(context.Context, *VersionRequest) (*VersionResponse, error) + // CreatePodSandbox creates a pod-level sandbox. + // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 + CreatePodSandbox(context.Context, *CreatePodSandboxRequest) (*CreatePodSandboxResponse, error) + // StopPodSandbox stops the sandbox. If there are any running containers in the + // sandbox, they should be force terminated. + StopPodSandbox(context.Context, *StopPodSandboxRequest) (*StopPodSandboxResponse, error) + // DeletePodSandbox deletes the sandbox. If there are any running containers in the + // sandbox, they should be force deleted. + DeletePodSandbox(context.Context, *DeletePodSandboxRequest) (*DeletePodSandboxResponse, error) + // PodSandboxStatus returns the Status of the PodSandbox. + PodSandboxStatus(context.Context, *PodSandboxStatusRequest) (*PodSandboxStatusResponse, error) + // ListPodSandbox returns a list of SandBox. + ListPodSandbox(context.Context, *ListPodSandboxRequest) (*ListPodSandboxResponse, error) + // CreateContainer creates a new container in specified PodSandbox + CreateContainer(context.Context, *CreateContainerRequest) (*CreateContainerResponse, error) + // StartContainer starts the container. + StartContainer(context.Context, *StartContainerRequest) (*StartContainerResponse, error) + // StopContainer stops a running container with a grace period (i.e., timeout). + StopContainer(context.Context, *StopContainerRequest) (*StopContainerResponse, error) + // RemoveContainer removes the container. If the container is running, the container + // should be force removed. + RemoveContainer(context.Context, *RemoveContainerRequest) (*RemoveContainerResponse, error) + // ListContainers lists all containers by filters. + ListContainers(context.Context, *ListContainersRequest) (*ListContainersResponse, error) + // ContainerStatus returns status of the container. + ContainerStatus(context.Context, *ContainerStatusRequest) (*ContainerStatusResponse, error) + // Exec executes the command in the container. + Exec(RuntimeService_ExecServer) error +} + +func RegisterRuntimeServiceServer(s *grpc.Server, srv RuntimeServiceServer) { + s.RegisterService(&_RuntimeService_serviceDesc, srv) +} + +func _RuntimeService_Version_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(VersionRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).Version(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_CreatePodSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(CreatePodSandboxRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).CreatePodSandbox(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_StopPodSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(StopPodSandboxRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).StopPodSandbox(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_DeletePodSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(DeletePodSandboxRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).DeletePodSandbox(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_PodSandboxStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(PodSandboxStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).PodSandboxStatus(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_ListPodSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(ListPodSandboxRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).ListPodSandbox(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_CreateContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(CreateContainerRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).CreateContainer(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_StartContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(StartContainerRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).StartContainer(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_StopContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(StopContainerRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).StopContainer(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_RemoveContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(RemoveContainerRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).RemoveContainer(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_ListContainers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(ListContainersRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).ListContainers(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_ContainerStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(ContainerStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(RuntimeServiceServer).ContainerStatus(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _RuntimeService_Exec_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(RuntimeServiceServer).Exec(&runtimeServiceExecServer{stream}) +} + +type RuntimeService_ExecServer interface { + Send(*ExecResponse) error + Recv() (*ExecRequest, error) + grpc.ServerStream +} + +type runtimeServiceExecServer struct { + grpc.ServerStream +} + +func (x *runtimeServiceExecServer) Send(m *ExecResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *runtimeServiceExecServer) Recv() (*ExecRequest, error) { + m := new(ExecRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +var _RuntimeService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "runtime.RuntimeService", + HandlerType: (*RuntimeServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Version", + Handler: _RuntimeService_Version_Handler, + }, + { + MethodName: "CreatePodSandbox", + Handler: _RuntimeService_CreatePodSandbox_Handler, + }, + { + MethodName: "StopPodSandbox", + Handler: _RuntimeService_StopPodSandbox_Handler, + }, + { + MethodName: "DeletePodSandbox", + Handler: _RuntimeService_DeletePodSandbox_Handler, + }, + { + MethodName: "PodSandboxStatus", + Handler: _RuntimeService_PodSandboxStatus_Handler, + }, + { + MethodName: "ListPodSandbox", + Handler: _RuntimeService_ListPodSandbox_Handler, + }, + { + MethodName: "CreateContainer", + Handler: _RuntimeService_CreateContainer_Handler, + }, + { + MethodName: "StartContainer", + Handler: _RuntimeService_StartContainer_Handler, + }, + { + MethodName: "StopContainer", + Handler: _RuntimeService_StopContainer_Handler, + }, + { + MethodName: "RemoveContainer", + Handler: _RuntimeService_RemoveContainer_Handler, + }, + { + MethodName: "ListContainers", + Handler: _RuntimeService_ListContainers_Handler, + }, + { + MethodName: "ContainerStatus", + Handler: _RuntimeService_ContainerStatus_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Exec", + Handler: _RuntimeService_Exec_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, +} + +// Client API for ImageService service + +type ImageServiceClient interface { + // ListImages lists existing images. + ListImages(ctx context.Context, in *ListImagesRequest, opts ...grpc.CallOption) (*ListImagesResponse, error) + // ImageStatus returns the status of the image. + ImageStatus(ctx context.Context, in *ImageStatusRequest, opts ...grpc.CallOption) (*ImageStatusResponse, error) + // PullImage pulls a image with authentication config. + PullImage(ctx context.Context, in *PullImageRequest, opts ...grpc.CallOption) (*PullImageResponse, error) + // RemoveImage removes the image. + RemoveImage(ctx context.Context, in *RemoveImageRequest, opts ...grpc.CallOption) (*RemoveImageResponse, error) +} + +type imageServiceClient struct { + cc *grpc.ClientConn +} + +func NewImageServiceClient(cc *grpc.ClientConn) ImageServiceClient { + return &imageServiceClient{cc} +} + +func (c *imageServiceClient) ListImages(ctx context.Context, in *ListImagesRequest, opts ...grpc.CallOption) (*ListImagesResponse, error) { + out := new(ListImagesResponse) + err := grpc.Invoke(ctx, "/runtime.ImageService/ListImages", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *imageServiceClient) ImageStatus(ctx context.Context, in *ImageStatusRequest, opts ...grpc.CallOption) (*ImageStatusResponse, error) { + out := new(ImageStatusResponse) + err := grpc.Invoke(ctx, "/runtime.ImageService/ImageStatus", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *imageServiceClient) PullImage(ctx context.Context, in *PullImageRequest, opts ...grpc.CallOption) (*PullImageResponse, error) { + out := new(PullImageResponse) + err := grpc.Invoke(ctx, "/runtime.ImageService/PullImage", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *imageServiceClient) RemoveImage(ctx context.Context, in *RemoveImageRequest, opts ...grpc.CallOption) (*RemoveImageResponse, error) { + out := new(RemoveImageResponse) + err := grpc.Invoke(ctx, "/runtime.ImageService/RemoveImage", in, out, c.cc, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// Server API for ImageService service + +type ImageServiceServer interface { + // ListImages lists existing images. + ListImages(context.Context, *ListImagesRequest) (*ListImagesResponse, error) + // ImageStatus returns the status of the image. + ImageStatus(context.Context, *ImageStatusRequest) (*ImageStatusResponse, error) + // PullImage pulls a image with authentication config. + PullImage(context.Context, *PullImageRequest) (*PullImageResponse, error) + // RemoveImage removes the image. + RemoveImage(context.Context, *RemoveImageRequest) (*RemoveImageResponse, error) +} + +func RegisterImageServiceServer(s *grpc.Server, srv ImageServiceServer) { + s.RegisterService(&_ImageService_serviceDesc, srv) +} + +func _ImageService_ListImages_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(ListImagesRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(ImageServiceServer).ListImages(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _ImageService_ImageStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(ImageStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(ImageServiceServer).ImageStatus(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _ImageService_PullImage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(PullImageRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(ImageServiceServer).PullImage(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +func _ImageService_RemoveImage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { + in := new(RemoveImageRequest) + if err := dec(in); err != nil { + return nil, err + } + out, err := srv.(ImageServiceServer).RemoveImage(ctx, in) + if err != nil { + return nil, err + } + return out, nil +} + +var _ImageService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "runtime.ImageService", + HandlerType: (*ImageServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ListImages", + Handler: _ImageService_ListImages_Handler, + }, + { + MethodName: "ImageStatus", + Handler: _ImageService_ImageStatus_Handler, + }, + { + MethodName: "PullImage", + Handler: _ImageService_PullImage_Handler, + }, + { + MethodName: "RemoveImage", + Handler: _ImageService_RemoveImage_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.proto b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.proto new file mode 100644 index 000000000000..965f362a49e7 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime/api.proto @@ -0,0 +1,654 @@ +// api.pb.go could be generate by hack/update-generate-runtime.sh +syntax = 'proto2'; + +package runtime; + +// Runtime service defines the public APIs for remote container runtimes +service RuntimeService { + // Version returns the runtime name, runtime version and runtime API version + rpc Version(VersionRequest) returns (VersionResponse) {} + + // CreatePodSandbox creates a pod-level sandbox. + // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 + rpc CreatePodSandbox(CreatePodSandboxRequest) returns (CreatePodSandboxResponse) {} + // StopPodSandbox stops the sandbox. If there are any running containers in the + // sandbox, they should be force terminated. + rpc StopPodSandbox(StopPodSandboxRequest) returns (StopPodSandboxResponse) {} + // DeletePodSandbox deletes the sandbox. If there are any running containers in the + // sandbox, they should be force deleted. + rpc DeletePodSandbox(DeletePodSandboxRequest) returns (DeletePodSandboxResponse) {} + // PodSandboxStatus returns the Status of the PodSandbox. + rpc PodSandboxStatus(PodSandboxStatusRequest) returns (PodSandboxStatusResponse) {} + // ListPodSandbox returns a list of SandBox. + rpc ListPodSandbox(ListPodSandboxRequest) returns (ListPodSandboxResponse) {} + + // CreateContainer creates a new container in specified PodSandbox + rpc CreateContainer(CreateContainerRequest) returns (CreateContainerResponse) {} + // StartContainer starts the container. + rpc StartContainer(StartContainerRequest) returns (StartContainerResponse) {} + // StopContainer stops a running container with a grace period (i.e., timeout). + rpc StopContainer(StopContainerRequest) returns (StopContainerResponse) {} + // RemoveContainer removes the container. If the container is running, the container + // should be force removed. + rpc RemoveContainer(RemoveContainerRequest) returns (RemoveContainerResponse) {} + // ListContainers lists all containers by filters. + rpc ListContainers(ListContainersRequest) returns (ListContainersResponse) {} + // ContainerStatus returns status of the container. + rpc ContainerStatus(ContainerStatusRequest) returns (ContainerStatusResponse) {} + + // Exec executes the command in the container. + rpc Exec(stream ExecRequest) returns (stream ExecResponse) {} +} + +// Image service defines the public APIs for managing images +service ImageService { + // ListImages lists existing images. + rpc ListImages(ListImagesRequest) returns (ListImagesResponse) {} + // ImageStatus returns the status of the image. + rpc ImageStatus(ImageStatusRequest) returns (ImageStatusResponse) {} + // PullImage pulls a image with authentication config. + rpc PullImage(PullImageRequest) returns (PullImageResponse) {} + // RemoveImage removes the image. + rpc RemoveImage(RemoveImageRequest) returns (RemoveImageResponse) {} +} + +message VersionRequest { + // The version of kubelet runtime API. + optional string version = 1; +} + +message VersionResponse { + // The version of the kubelet runtime API. + optional string version = 1; + // The name of the container runtime. + optional string runtime_name = 2; + // The version of the container runtime. + optional string runtime_version = 3; + // The API version of the container runtime. + optional string runtime_api_version = 4; +} + +// DNSOption specifies the DNS servers and search domains. +message DNSOption { + // List of DNS servers of the cluster. + repeated string servers = 1; + // List of DNS search domains of the cluster. + repeated string searches = 2; +} + +enum Protocol { + TCP = 0; + UDP = 1; +} + +// PortMapping specifies the port mapping configurations of sandbox +message PortMapping { + // The name of the port mapping + optional string name = 1; + // The protocol of the port mapping. + optional Protocol protocol = 2; + // The port number within the container. + optional int32 container_port = 3; + // The port number on the host. + optional int32 host_port = 4; + // The host IP. + optional string host_ip = 5; +} + +// Mount specifies the volume mount for the sandbox +message Mount { + // The name of the volume mount. + optional string name = 1; + // The path of the mount within the container. + optional string container_path = 2; + // The path of the mount on the host. + optional string host_path = 3; + // If set, the mount is read-only. + optional bool readonly = 4; + // If set, the mount needs SELinux relabeling + optional bool selinux_relabel = 5; +} + +// ResourceRequirements contains a set of resources +// Valid resources are: +// - cpu, in cores. (500m = .5 cores) +// - memory, in bytes. (500Gi = 500GiB = 500 * 1024 * 1024 * 1024) +message ResourceRequirements { + // The maximum amount of compute resources allowed. + optional double limits = 1; + // The minimum amount of compute resources required. + // If Request is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value + optional double requests = 2; +} + +// PodSandboxResources contains the CPU/memory resource requirements. +message PodSandboxResources { + // CPU resource requirement. + optional ResourceRequirements cpu = 1; + // Memory resource requirement. + optional ResourceRequirements memory = 2; +} + +// NamespaceOption provides options for Linux namespaces. +message NamespaceOption { + // If set, use the host's network namespace. + optional bool host_network = 1; + // If set, use the host's pid namesapce. + optional bool host_pid = 2; + // If set, use the host's ipc namespace. + optional bool host_ipc = 3; +} + +// LinuxPodSandboxConfig holds platform-specific configuraions for Linux +// host platforms and Linux-based containers. +message LinuxPodSandboxConfig { + // The parent cgroup of the pod sandbox. + // The cgroupfs style syntax will be used, but the container runtime can + // convert it to systemd semantices if needed. + optional string cgroup_parent = 1; + // The configurations for the sandbox's namespaces. + // This will be used only if the PodSandbox uses namespace for isolation. + optional NamespaceOption namespace_options = 2; +} + +// PodSandboxConfig holds all the required and optional fields for creating a +// sandbox. +message PodSandboxConfig { + // The name of the sandbox. + optional string name = 1; + // The hostname of the sandbox. + optional string hostname = 2; + // Path to the directory on the host in which container log files are + // stored. + // By default the log of a container going into the LogDirectory will be + // hooked up to STDOUT and STDERR. However, the LogDirectory may contain + // binary log files with structured logging data from the individual + // containers. For example the files might be newline seperated JSON + // structured logs, systemd-journald journal files, gRPC trace files, etc. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + optional string log_directory = 3; + // The DNS options for the sandbox. + optional DNSOption dns_options = 4; + // The port mappings for the sandbox. + repeated PortMapping port_mappings = 5; + // Resources specifies the resource limits for the sandbox (i.e., the + // aggregate cpu/memory resources limits of all containers). + // Note: On a Linux host, kubelet will create a pod-level cgroup and pass + // it as the cgroup parent for the PodSandbox. For some runtimes, this is + // sufficent. For others, e.g., hypervisor-based runtimes, explicit + // resource limits for the sandbox are needed at creation time. + optional PodSandboxResources resources = 6; + // Labels are key value pairs that may be used to scope and select individual resources. + map labels = 7; + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + map annotations = 8; + // Optional configurations specific to Linux hosts. + optional LinuxPodSandboxConfig linux = 9; +} + +message CreatePodSandboxRequest { + // The configuration for creating a PodSandBox. + optional PodSandboxConfig config = 1; +} + +message CreatePodSandboxResponse { + // The id of the PodSandBox + optional string pod_sandbox_id = 1; +} + +message StopPodSandboxRequest { + // The id of the PodSandBox + optional string pod_sandbox_id = 1; +} + +message StopPodSandboxResponse {} + +message DeletePodSandboxRequest { + // The id of the PodSandBox + optional string pod_sandbox_id = 1; +} + +message DeletePodSandboxResponse {} + +message PodSandboxStatusRequest { + // The id of the PodSandBox + optional string pod_sandbox_id = 1; +} + +// PodSandboxNetworkStatus is the status of the network for a PodSandbox. +message PodSandboxNetworkStatus { + // The IP address of the PodSandbox + optional string ip = 1; +} + +// Namespace contains paths to the namespaces. +message Namespace { + // Network is the path to the network namespace. + optional string network = 1; + // Options is the namespace options for linux namespaces + optional NamespaceOption options = 2; +} + +// LinuxSandBoxStatus contains status specific to Linux sandboxes. +message LinuxPodSandboxStatus { + // Namespaces contains paths to the sandbox's namespaces. + optional Namespace namespaces = 1; +} + +enum PodSandBoxState { + READY = 0; + NOTREADY = 1; +} + +// PodSandboxStatus contains the status of the PodSandbox. +message PodSandboxStatus { + // ID of the sandbox. + optional string id = 1; + // Name of the sandbox + optional string name = 2; + // State of the sandbox. + optional PodSandBoxState state = 3; + // Creation timestamp of the sandbox + optional int64 created_at = 4; + // Network contains network status if network is handled by the runtime. + optional PodSandboxNetworkStatus network = 5; + // Linux specific status to a pod sandbox. + optional LinuxPodSandboxStatus linux = 6; + // Labels are key value pairs that may be used to scope and select individual resources. + map labels = 7; + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + map annotations = 8; +} + +message PodSandboxStatusResponse { + // The status of the PodSandbox + optional PodSandboxStatus status = 1; +} + +// PodSandboxFilter is used to filter a list of PodSandboxes. +// All those fields are combined with 'AND' +message PodSandboxFilter { + // Name of the sandbox. + optional string name = 1; + // ID of the sandbox. + optional string id = 2; + // State of the sandbox. + optional PodSandBoxState state = 3; + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + map label_selector = 4; +} + +message ListPodSandboxRequest { + // PodSandboxFilter to filter a list of PodSandboxes. + optional PodSandboxFilter filter = 1; +} + + +// PodSandbox contains minimal information about a sandbox. +message PodSandbox { + // The id of the PodSandbox + optional string id = 1; + // The name of the PodSandbox + optional string name = 2; + // The state of the PodSandbox + optional PodSandBoxState state = 3; + // Creation timestamps of the sandbox + optional int64 created_at = 4; + // The labels of the PodSandbox + map labels = 5; +} + +message ListPodSandboxResponse { + // List of PodSandbox + repeated PodSandbox items = 1; +} + +// ImageSpec is an internal representation of an image. Currently, it wraps the +// value of a Container's Image field (e.g. imageName, imageName:tag, or +// imageName:digest), but in the future it will include more detailed +// information about the different image types. +message ImageSpec { + optional string image = 1; +} + +message KeyValue { + optional string key = 1; + optional string value = 2; +} + +// LinuxContainerResources specifies Linux specific configuration for +// resources. +// TODO: Consider using Resources from opencontainers/runtime-spec/specs-go +// directly. +message LinuxContainerResources { + // CPU CFS (Completely Fair Scheduler) period + optional int64 cpu_period = 1; + // CPU CFS (Completely Fair Scheduler) quota + optional int64 cpu_quota = 2; + // CPU shares (relative weight vs. other containers) + optional int64 cpu_shares = 3; + // Memory limit in bytes + optional int64 memory_limit_in_bytes = 4; + // OOMScoreAdj adjusts the oom-killer score. + optional int64 oom_score_adj = 5; +} + +// SELinuxOption are the labels to be applied to the container. +message SELinuxOption { + optional string user = 1; + optional string role = 2; + optional string type = 3; + optional string level = 4; +} + +// Capability contains the container capabilities to add or drop +message Capability { + // List of capabilities to add. + repeated string add_capabilities = 1; + // List of capabilities to drop. + repeated string drop_capabilities = 2; +} + +// LinuxContainerConfig contains platform-specific configuration for +// Linux-based containers. +message LinuxContainerConfig { + // Resources specification for the container. + optional LinuxContainerResources resources = 1; + // Capabilities to add or drop. + optional Capability capabilities = 2; + // Optional SELinux context to be applied. + optional SELinuxOption selinux_options = 3; + // User contains the user for the container process. + optional LinuxUser user = 4; +} + +message LinuxUser { + // uid specifies the user ID the container process has. + optional int64 uid = 1; + // gid specifies the group ID the container process has. + optional int64 gid = 2; + // additional_gids specifies additional GIDs the container process has. + repeated int64 additional_gids = 3; +} + +message ContainerConfig { + // Name of the container. + optional string name = 1; + // Image to use. + optional ImageSpec image = 2; + // Command to execute (i.e., entrypoint for docker) + repeated string command = 3; + // Args for the Command (i.e., command for docker) + repeated string args = 4; + // Current working directory of the command. + optional string working_dir = 5; + // List of environment variable to set in the container + repeated KeyValue envs = 6; + // Mounts specifies mounts for the container + repeated Mount mounts = 7; + // Labels are key value pairs that may be used to scope and select individual resources. + // Label keys are of the form: + // label-key ::= prefixed-name | name + // prefixed-name ::= prefix '/' name + // prefix ::= DNS_SUBDOMAIN + // name ::= DNS_LABEL + map labels = 8; + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + map annotations = 9; + // If set, run container in privileged mode. + // Processes in privileged containers are essentially equivalent to root on the host. + optional bool privileged = 10; + // If set, the root filesystem of the container is read-only. + optional bool readonly_rootfs = 11; + // Path relative to PodSandboxConfig.LogDirectory for container to store + // the log (STDOUT and STDERR) on the host. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + optional string log_path = 12; + // The hash of container config + + // Variables for interactive containers, these have very specialized + // use-cases (e.g. debugging). + // TODO: Determine if we need to continue supporting these fields that are + // part of Kubernetes's Container Spec. + optional bool stdin = 13; + optional bool stdin_once = 14; + optional bool tty = 15; + + // Linux contains configuration specific to Linux containers. + optional LinuxContainerConfig linux = 16; +} + +message CreateContainerRequest { + // The id of the PodSandbox + optional string pod_sandbox_id = 1; + // The config of the container + optional ContainerConfig config = 2; + // The config of the PodSandbox + optional PodSandboxConfig sandbox_config = 3; +} + +message CreateContainerResponse { + // The id of the created container + optional string container_id = 1; +} + +message StartContainerRequest { + // The id of the container + optional string container_id = 1; +} + +message StartContainerResponse {} + +message StopContainerRequest { + // The id of the container + optional string container_id = 1; + // Timeout in seconds to stop the container + optional int64 timeout = 2; +} + +message StopContainerResponse {} + +message RemoveContainerRequest { + // The id of the container + optional string container_id = 1; +} + +message RemoveContainerResponse {} + +enum ContainerState { + CREATED = 0; + RUNNING = 1; + EXITED = 2; + UNKNOWN = 3; +} + +// ContainerFilter is used to filter containers. +// All those fields are combined with 'AND' +message ContainerFilter { + // Name of the container. + optional string name = 1; + // ID of the container. + optional string id = 2; + // State of the contianer. + optional ContainerState state = 3; + // The id of the pod sandbox + optional string pod_sandbox_id = 4; + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + map label_selector = 5; +} + +message ListContainersRequest { + optional ContainerFilter filter = 1; +} + +// Container provides the runtime information for a container, such as ID, hash, +// state of the container. +message Container { + // The ID of the container, used by the container runtime to identify + // a container. + optional string id = 1; + // The name of the container + optional string name = 2; + // The spec of the image + optional ImageSpec image = 3; + // Reference to the image in use. For most runtimes, this should be an + // image ID. + optional string image_ref = 4; + // State is the state of the container. + optional ContainerState state = 5; + // Labels are key value pairs that may be used to scope and select individual resources. + map labels = 6; +} + +message ListContainersResponse { + // List of containers + repeated Container containers = 1; +} + +message ContainerStatusRequest { + // The id of the container + optional string container_id = 1; +} + +// ContainerStatus represents the status of a container. +message ContainerStatus { + // ID of the container. + optional string id = 1; + // Name of the container. + optional string name = 2; + // Status of the container. + optional ContainerState state = 3; + // Creation time of the container. + optional int64 created_at = 4; + // Start time of the container. + optional int64 started_at = 5; + // Finish time of the container. + optional int64 finished_at = 6; + // Exit code of the container. + optional int32 exit_code = 7; + // The spec of the image + optional ImageSpec image = 8; + // Reference to the image in use. For most runtimes, this should be an + // image ID + optional string image_ref = 9; + // A string explains why container is in such a status. + optional string reason = 10; + // Labels are key value pairs that may be used to scope and select individual resources. + map labels = 11; + // Annotations is an unstructured key value map. + map annotations = 12; + // Mounts specifies mounts for the container + repeated Mount mounts = 13; +} + +message ContainerStatusResponse { + // The status of the container + optional ContainerStatus status = 1; +} + +message ExecRequest { + // The id of the container + optional string container_id = 1; + // The cmd to execute + repeated string cmd = 2; + // Whether use tty + optional bool tty = 3; + // Streaming stdin + optional bytes stdin = 4; +} + +message ExecResponse { + // Streaming stdout + optional bytes stdout = 1; + // Streaming stderr + optional bytes stderr = 2; +} + +message ImageFilter { + // The spec of the image + optional ImageSpec image = 1; +} + +message ListImagesRequest { + // The filter to list images + optional ImageFilter filter = 1; +} + +// Basic information about a container image. +message Image { + // ID of the image. + optional string id = 1; + // Other names by which this image is known. + repeated string repo_tags = 2; + // Digests by which this image is known. + repeated string repo_digests = 3; + // The size of the image in bytes. + optional uint64 size = 4; +} + +message ListImagesResponse { + // List of images + repeated Image images = 1; +} + +message ImageStatusRequest { + // The spec of the image + optional ImageSpec image = 1; +} + +message ImageStatusResponse { + // The status of the image + optional Image image = 1; +} + +// AuthConfig contains authorization information for connecting to a registry. +message AuthConfig { + optional string username = 1; + optional string password = 2; + optional string auth = 3; + optional string server_address = 4; + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + optional string identity_token = 5; + // RegistryToken is a bearer token to be sent to a registry + optional string registry_token = 6; +} + +message PullImageRequest { + // The spec of the image + optional ImageSpec image = 1; + // The auth config for pulling image + optional AuthConfig auth = 2; + // The config of the PodSandbox, which is used to pull image in PodSandbox context + optional PodSandboxConfig sandbox_config = 3; +} + +message PullImageResponse {} + +message RemoveImageRequest { + // The spec of the image + optional ImageSpec image = 1; +} + +message RemoveImageResponse {} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats/types.go index 90c566d9d3a7..a752ab30b790 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats/types.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -173,6 +173,8 @@ type FsStats struct { // This may differ from the total bytes used on the filesystem and may not equal CapacityBytes - AvailableBytes. // e.g. For ContainerStats.Rootfs this is the bytes used by the container rootfs on the filesystem. UsedBytes *uint64 `json:"usedBytes,omitempty"` + // InodesFree represents the free inodes in the filesystem. + InodesFree *uint64 `json:"inodesFree,omitempty"` } // UserDefinedMetricType defines how the metric should be interpreted by the user. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_linux.go index 6ba118b37198..b01f06491169 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_linux.go @@ -1,7 +1,7 @@ // +build cgo,linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import ( "flag" "fmt" "net/http" - "regexp" "time" "github.com/golang/glog" @@ -109,18 +108,7 @@ func (cc *cadvisorClient) exportHTTP(port uint) error { return err } - re := regexp.MustCompile(`^k8s_(?P[^_\.]+)[^_]+_(?P[^_]+)_(?P[^_]+)`) - reCaptureNames := re.SubexpNames() - cadvisorhttp.RegisterPrometheusHandler(mux, cc, "/metrics", func(name string) map[string]string { - extraLabels := map[string]string{} - matches := re.FindStringSubmatch(name) - for i, match := range matches { - if len(reCaptureNames[i]) > 0 { - extraLabels[re.SubexpNames()[i]] = match - } - } - return extraLabels - }) + cadvisorhttp.RegisterPrometheusHandler(mux, cc, "/metrics", nil) // Only start the http server if port > 0 if port > 0 { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_unsupported.go index e5f281d64699..f8036e1b3f64 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/cadvisor_unsupported.go @@ -1,7 +1,7 @@ // +build !cgo !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/doc.go index 8e1c076c68db..22ae55f26db2 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/types.go index fbf7b9e058c5..de7d334c1b76 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/types.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/util.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/util.go index 2dac21756521..5fa528a5853e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/util.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cadvisor/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/client/kubelet_client.go b/vendor/k8s.io/kubernetes/pkg/kubelet/client/kubelet_client.go index b656fbf09bee..4d1445791482 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/client/kubelet_client.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/client/kubelet_client.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_linux.go new file mode 100644 index 000000000000..644ceb44a8a2 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_linux.go @@ -0,0 +1,184 @@ +/* +Copyright 2016 The Kubernetes 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 cm + +import ( + "fmt" + "path" + + libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups" + cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs" + libcontainerconfigs "github.com/opencontainers/runc/libcontainer/configs" +) + +// cgroupManagerImpl implements the CgroupManager interface. +// Its a stateless object which can be used to +// update,create or delete any number of cgroups +// It uses the Libcontainer raw fs cgroup manager for cgroup management. +type cgroupManagerImpl struct { + // subsystems holds information about all the + // mounted cgroup subsytems on the node + subsystems *cgroupSubsystems +} + +// Make sure that cgroupManagerImpl implements the CgroupManager interface +var _ CgroupManager = &cgroupManagerImpl{} + +// NewCgroupManager is a factory method that returns a CgroupManager +func NewCgroupManager(cs *cgroupSubsystems) CgroupManager { + return &cgroupManagerImpl{ + subsystems: cs, + } +} + +// Exists checks if all subsystem cgroups already exist +func (m *cgroupManagerImpl) Exists(name string) bool { + // Get map of all cgroup paths on the system for the particular cgroup + cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints)) + for key, val := range m.subsystems.mountPoints { + cgroupPaths[key] = path.Join(val, name) + } + + // If even one cgroup doesn't exist we go on to create it + for _, path := range cgroupPaths { + if !libcontainercgroups.PathExists(path) { + return false + } + } + return true +} + +// Destroy destroys the specified cgroup +func (m *cgroupManagerImpl) Destroy(cgroupConfig *CgroupConfig) error { + //cgroup name + name := cgroupConfig.Name + + // Get map of all cgroup paths on the system for the particular cgroup + cgroupPaths := make(map[string]string, len(m.subsystems.mountPoints)) + for key, val := range m.subsystems.mountPoints { + cgroupPaths[key] = path.Join(val, name) + } + + // Initialize libcontainer's cgroup config + libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{ + Name: path.Base(name), + Parent: path.Dir(name), + } + fsCgroupManager := cgroupfs.Manager{ + Cgroups: libcontainerCgroupConfig, + Paths: cgroupPaths, + } + + // Delete cgroups using libcontainers Managers Destroy() method + if err := fsCgroupManager.Destroy(); err != nil { + return fmt.Errorf("Unable to destroy cgroup paths for cgroup %v : %v", name, err) + } + return nil +} + +type subsystem interface { + // Name returns the name of the subsystem. + Name() string + // Set the cgroup represented by cgroup. + Set(path string, cgroup *libcontainerconfigs.Cgroup) error +} + +// Cgroup subsystems we currently support +var supportedSubsystems []subsystem = []subsystem{ + &cgroupfs.MemoryGroup{}, + &cgroupfs.CpuGroup{}, +} + +// setSupportedSubsytems sets cgroup resource limits only on the supported +// subsytems. ie. cpu and memory. We don't use libcontainer's cgroup/fs/Set() +// method as it dosn't allow us to skip updates on the devices cgroup +// Allowing or denying all devices by writing 'a' to devices.allow or devices.deny is +// not possible once the device cgroups has children. Once the pod level cgroup are +// created under the QOS level cgroup we cannot update the QOS level device cgroup. +// We would like to skip setting any values on the device cgroup in this case +// but this is not possible with libcontainers Set() method +// See https://github.com/opencontainers/runc/issues/932 +func setSupportedSubsytems(cgroupConfig *libcontainerconfigs.Cgroup) error { + for _, sys := range supportedSubsystems { + if _, ok := cgroupConfig.Paths[sys.Name()]; !ok { + return fmt.Errorf("Failed to find subsytem mount for subsytem") + } + if err := sys.Set(cgroupConfig.Paths[sys.Name()], cgroupConfig); err != nil { + return fmt.Errorf("Failed to set config for supported subsystems : %v", err) + } + } + return nil +} + +// Update updates the cgroup with the specified Cgroup Configuration +func (m *cgroupManagerImpl) Update(cgroupConfig *CgroupConfig) error { + //cgroup name + name := cgroupConfig.Name + + // Extract the cgroup resource parameters + resourceConfig := cgroupConfig.ResourceParameters + resources := &libcontainerconfigs.Resources{} + if resourceConfig.Memory != nil { + resources.Memory = *resourceConfig.Memory + } + if resourceConfig.CpuShares != nil { + resources.CpuShares = *resourceConfig.CpuShares + } + if resourceConfig.CpuQuota != nil { + resources.CpuQuota = *resourceConfig.CpuQuota + } + + // Initialize libcontainer's cgroup config + libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{ + Name: path.Base(name), + Parent: path.Dir(name), + Resources: resources, + } + + if err := setSupportedSubsytems(libcontainerCgroupConfig); err != nil { + return fmt.Errorf("Failed to set supported cgroup subsystems for cgroup %v: %v", name, err) + } + return nil +} + +// Create creates the specified cgroup +func (m *cgroupManagerImpl) Create(cgroupConfig *CgroupConfig) error { + // get cgroup name + name := cgroupConfig.Name + + // Initialize libcontainer's cgroup config + libcontainerCgroupConfig := &libcontainerconfigs.Cgroup{ + Name: path.Base(name), + Parent: path.Dir(name), + Resources: &libcontainerconfigs.Resources{}, + } + + // get the fscgroup Manager with the specified cgroup configuration + fsCgroupManager := &cgroupfs.Manager{ + Cgroups: libcontainerCgroupConfig, + } + //Apply(0) is a hack to create the cgroup directories for each resource + // subsystem. The function [cgroups.Manager.apply()] applies cgroup + // configuration to the process with the specified pid. + // It creates cgroup files for each subsytems and writes the pid + // in the tasks file. We use the function to create all the required + // cgroup files but not attach any "real" pid to the cgroup. + if err := fsCgroupManager.Apply(0); err != nil { + return fmt.Errorf("Failed to apply cgroup config for %v: %v", name, err) + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_unsupported.go new file mode 100644 index 000000000000..650aeca6c221 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/cgroup_manager_unsupported.go @@ -0,0 +1,46 @@ +// +build !linux + +/* +Copyright 2016 The Kubernetes 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 cm + +import "fmt" + +type unsupportedCgroupManager struct{} + +// Make sure that unsupportedCgroupManager implements the CgroupManager interface +var _ CgroupManager = &unsupportedCgroupManager{} + +func NewCgroupManager(_ interface{}) CgroupManager { + return &unsupportedCgroupManager{} +} + +func (m *unsupportedCgroupManager) Exists(_ string) bool { + return false +} + +func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error { + return nil +} + +func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error { + return nil +} + +func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error { + return fmt.Errorf("Cgroup Manager is not supported in this build") +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager.go index e18bc6865e27..58ed53620262 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -43,6 +43,8 @@ type NodeConfig struct { SystemCgroupsName string KubeletCgroupsName string ContainerRuntime string + CgroupsPerQOS bool + CgroupRoot string } type Status struct { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_linux.go index 70b53a560882..7e80c09aa4c9 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/kubelet/cadvisor" + "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/util" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/mount" @@ -97,7 +98,10 @@ type containerManagerImpl struct { status Status // External containers being managed. systemContainers []*systemContainer + qosContainers QOSContainersInfo periodicTasks []func() + // holds all the mounted cgroup subsystems + subsystems *cgroupSubsystems } type features struct { @@ -161,10 +165,24 @@ func validateSystemRequirements(mountUtil mount.Interface) (features, error) { // Takes the absolute name of the specified containers. // Empty container name disables use of the specified container. func NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig) (ContainerManager, error) { + // Check if Cgroup-root actually exists on the node + if nodeConfig.CgroupsPerQOS { + if nodeConfig.CgroupRoot == "" { + return nil, fmt.Errorf("invalid configuration: cgroups-per-qos was specified and cgroup-root was not specified. To enable the QoS cgroup hierarchy you need to specify a valid cgroup-root") + } + if _, err := os.Stat(nodeConfig.CgroupRoot); err != nil { + return nil, fmt.Errorf("invalid configuration: cgroup-root doesn't exist : %v", err) + } + } + subsystems, err := getCgroupSubsystems() + if err != nil { + return nil, fmt.Errorf("failed to get mounted subsystems: %v", err) + } return &containerManagerImpl{ cadvisorInterface: cadvisorInterface, mountUtil: mountUtil, NodeConfig: nodeConfig, + subsystems: subsystems, }, nil } @@ -190,6 +208,41 @@ const ( KernelTunableModify KernelTunableBehavior = "modify" ) +// InitQOS creates the top level qos cgroup containers +// We create top level QoS containers for only Burstable and Best Effort +// and not Guaranteed QoS class. All guaranteed pods are nested under the +// RootContainer by default. InitQOS is called only once during kubelet bootstrapping. +// TODO(@dubstack) Add support for cgroup-root to work on both systemd and cgroupfs +// drivers. Currently we only support systems running cgroupfs driver +func InitQOS(rootContainer string, subsystems *cgroupSubsystems) (QOSContainersInfo, error) { + cm := NewCgroupManager(subsystems) + // Top level for Qos containers are created only for Burstable + // and Best Effort classes + qosClasses := [2]qos.QOSClass{qos.Burstable, qos.BestEffort} + + // Create containers for both qos classes + for _, qosClass := range qosClasses { + // get the container's absolute name + absoluteContainerName := path.Join(rootContainer, string(qosClass)) + // containerConfig object stores the cgroup specifications + containerConfig := &CgroupConfig{ + Name: absoluteContainerName, + ResourceParameters: &ResourceConfig{}, + } + // TODO(@dubstack) Add support on systemd cgroups driver + if err := cm.Create(containerConfig); err != nil { + return QOSContainersInfo{}, fmt.Errorf("failed to create top level %v QOS cgroup : %v", qosClass, err) + } + } + // Store the top level qos container names + qosContainersInfo := QOSContainersInfo{ + Guaranteed: rootContainer, + Burstable: path.Join(rootContainer, string(qos.Burstable)), + BestEffort: path.Join(rootContainer, string(qos.BestEffort)), + } + return qosContainersInfo, nil +} + // setupKernelTunables validates kernel tunable flags are set as expected // depending upon the specified option, it will either warn, error, or modify the kernel tunable flags func setupKernelTunables(option KernelTunableBehavior) error { @@ -240,6 +293,15 @@ func (cm *containerManagerImpl) setupNode() error { return err } + // Setup top level qos containers only if CgroupsPerQOS flag is specified as true + if cm.NodeConfig.CgroupsPerQOS { + qosContainersInfo, err := InitQOS(cm.NodeConfig.CgroupRoot, cm.subsystems) + if err != nil { + return fmt.Errorf("failed to initialise top level QOS containers: %v", err) + } + cm.qosContainers = qosContainersInfo + } + systemContainers := []*systemContainer{} if cm.ContainerRuntime == "docker" { if cm.RuntimeCgroupsName != "" { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_stub.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_stub.go index 4bca506c2fab..977b713fa8e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_stub.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_stub.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_unsupported.go index 426c95ca4cc9..fe6cb808fa10 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/helpers_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/helpers_linux.go new file mode 100644 index 000000000000..92b3c7565c05 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/helpers_linux.go @@ -0,0 +1,58 @@ +/* +Copyright 2016 The Kubernetes 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 cm + +import ( + "fmt" + + libcontainercgroups "github.com/opencontainers/runc/libcontainer/cgroups" +) + +// cgroupSubsystems holds information about the mounted cgroup subsytems +type cgroupSubsystems struct { + // Cgroup subsystem mounts. + // e.g.: "/sys/fs/cgroup/cpu" -> ["cpu", "cpuacct"] + mounts []libcontainercgroups.Mount + + // Cgroup subsystem to their mount location. + // e.g.: "cpu" -> "/sys/fs/cgroup/cpu" + mountPoints map[string]string +} + +// GetCgroupSubsystems returns information about the mounted cgroup subsystems +func getCgroupSubsystems() (*cgroupSubsystems, error) { + // Get all cgroup mounts. + allCgroups, err := libcontainercgroups.GetCgroupMounts() + if err != nil { + return &cgroupSubsystems{}, err + } + if len(allCgroups) == 0 { + return &cgroupSubsystems{}, fmt.Errorf("failed to find cgroup mounts") + } + + //TODO(@dubstack) should we trim to only the supported ones + mountPoints := make(map[string]string, len(allCgroups)) + for _, mount := range allCgroups { + for _, subsystem := range mount.Subsystems { + mountPoints[subsystem] = mount.Mountpoint + } + } + return &cgroupSubsystems{ + mounts: allCgroups, + mountPoints: mountPoints, + }, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/cm/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/types.go new file mode 100644 index 000000000000..745870bcdcc8 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/cm/types.go @@ -0,0 +1,65 @@ +/* +Copyright 2016 The Kubernetes 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 cm + +// ResourceConfig holds information about all the supported cgroup resource parameters. +type ResourceConfig struct { + // Memory limit (in bytes). + Memory *int64 + // CPU shares (relative weight vs. other containers). + CpuShares *int64 + // CPU hardcap limit (in usecs). Allowed cpu time in a given period. + CpuQuota *int64 +} + +// CgroupConfig holds the cgroup configuration information. +// This is common object which is used to specify +// cgroup information to both systemd and raw cgroup fs +// implementation of the Cgroup Manager interface. +type CgroupConfig struct { + // We would expect systemd implementation to make appropriate + // name conversion. For example, if we pass /foo/bar + // then systemd should convert the name to something like + // foo.slice/foo-bar.slice + + // Fully qualified name + Name string + // ResourceParameters contains various cgroups settings to apply. + ResourceParameters *ResourceConfig +} + +// CgroupManager allows for cgroup management. +// Supports Cgroup Creation ,Deletion and Updates. +type CgroupManager interface { + // Create creates and applies the cgroup configurations on the cgroup. + // It just creates the leaf cgroups. + // It expects the parent cgroup to already exist. + Create(*CgroupConfig) error + // Destroys the cgroup. + Destroy(*CgroupConfig) error + // Update cgroup configuration. + Update(*CgroupConfig) error + // Exists checks if the cgroup already exists + Exists(string) bool +} + +// QOSContainersInfo hold the names of containers per qos +type QOSContainersInfo struct { + Guaranteed string + BestEffort string + Burstable string +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/apiserver.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/apiserver.go index c3baed8d0421..8975449935a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/apiserver.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/apiserver.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/common.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/common.go index 0838699ec262..ec11b227a317 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/common.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/common.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/config.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/config.go index 0d190e01e043..f91d19787737 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/config.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/pkg/util/config" @@ -43,10 +44,10 @@ const ( // PodConfigNotificationSnapshot delivers the full configuration as a SET whenever // any change occurs. PodConfigNotificationSnapshot - // PodConfigNotificationSnapshotAndUpdates delivers an UPDATE message whenever pods are + // PodConfigNotificationSnapshotAndUpdates delivers an UPDATE and DELETE message whenever pods are // changed, and a SET message if there are any additions or removals. PodConfigNotificationSnapshotAndUpdates - // PodConfigNotificationIncremental delivers ADD, UPDATE, REMOVE, RECONCILE to the update channel. + // PodConfigNotificationIncremental delivers ADD, UPDATE, DELETE, REMOVE, RECONCILE to the update channel. PodConfigNotificationIncremental ) @@ -152,14 +153,14 @@ func (s *podStorage) Merge(source string, change interface{}) error { defer s.updateLock.Unlock() seenBefore := s.sourcesSeen.Has(source) - adds, updates, deletes, reconciles := s.merge(source, change) + adds, updates, deletes, removes, reconciles := s.merge(source, change) firstSet := !seenBefore && s.sourcesSeen.Has(source) // deliver update notifications switch s.mode { case PodConfigNotificationIncremental: - if len(deletes.Pods) > 0 { - s.updates <- *deletes + if len(removes.Pods) > 0 { + s.updates <- *removes } if len(adds.Pods) > 0 { s.updates <- *adds @@ -167,9 +168,12 @@ func (s *podStorage) Merge(source string, change interface{}) error { if len(updates.Pods) > 0 { s.updates <- *updates } - if firstSet && len(adds.Pods) == 0 && len(updates.Pods) == 0 { + if len(deletes.Pods) > 0 { + s.updates <- *deletes + } + if firstSet && len(adds.Pods) == 0 && len(updates.Pods) == 0 && len(deletes.Pods) == 0 { // Send an empty update when first seeing the source and there are - // no ADD or UPDATE pods from the source. This signals kubelet that + // no ADD or UPDATE or DELETE pods from the source. This signals kubelet that // the source is ready. s.updates <- *adds } @@ -179,15 +183,18 @@ func (s *podStorage) Merge(source string, change interface{}) error { } case PodConfigNotificationSnapshotAndUpdates: - if len(deletes.Pods) > 0 || len(adds.Pods) > 0 || firstSet { + if len(removes.Pods) > 0 || len(adds.Pods) > 0 || firstSet { s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*api.Pod), Op: kubetypes.SET, Source: source} } if len(updates.Pods) > 0 { s.updates <- *updates } + if len(deletes.Pods) > 0 { + s.updates <- *deletes + } case PodConfigNotificationSnapshot: - if len(updates.Pods) > 0 || len(deletes.Pods) > 0 || len(adds.Pods) > 0 || firstSet { + if len(updates.Pods) > 0 || len(deletes.Pods) > 0 || len(adds.Pods) > 0 || len(removes.Pods) > 0 || firstSet { s.updates <- kubetypes.PodUpdate{Pods: s.MergedState().([]*api.Pod), Op: kubetypes.SET, Source: source} } @@ -200,13 +207,14 @@ func (s *podStorage) Merge(source string, change interface{}) error { return nil } -func (s *podStorage) merge(source string, change interface{}) (adds, updates, deletes, reconciles *kubetypes.PodUpdate) { +func (s *podStorage) merge(source string, change interface{}) (adds, updates, deletes, removes, reconciles *kubetypes.PodUpdate) { s.podLock.Lock() defer s.podLock.Unlock() addPods := []*api.Pod{} updatePods := []*api.Pod{} deletePods := []*api.Pod{} + removePods := []*api.Pod{} reconcilePods := []*api.Pod{} pods := s.pods[source] @@ -228,11 +236,13 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de ref.Annotations[kubetypes.ConfigSourceAnnotationKey] = source if existing, found := oldPods[name]; found { pods[name] = existing - needUpdate, needReconcile := checkAndUpdatePod(existing, ref) + needUpdate, needReconcile, needGracefulDelete := checkAndUpdatePod(existing, ref) if needUpdate { updatePods = append(updatePods, existing) } else if needReconcile { reconcilePods = append(reconcilePods, existing) + } else if needGracefulDelete { + deletePods = append(deletePods, existing) } continue } @@ -244,9 +254,11 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de update := change.(kubetypes.PodUpdate) switch update.Op { - case kubetypes.ADD, kubetypes.UPDATE: + case kubetypes.ADD, kubetypes.UPDATE, kubetypes.DELETE: if update.Op == kubetypes.ADD { glog.V(4).Infof("Adding new pods from source %s : %v", source, update.Pods) + } else if update.Op == kubetypes.DELETE { + glog.V(4).Infof("Graceful deleting pods from source %s : %v", source, update.Pods) } else { glog.V(4).Infof("Updating pods from source %s : %v", source, update.Pods) } @@ -259,7 +271,7 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de if existing, found := pods[name]; found { // this is a delete delete(pods, name) - deletePods = append(deletePods, existing) + removePods = append(removePods, existing) continue } // this is a no-op @@ -275,7 +287,7 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de for name, existing := range oldPods { if _, found := pods[name]; !found { // this is a delete - deletePods = append(deletePods, existing) + removePods = append(removePods, existing) } } @@ -288,10 +300,11 @@ func (s *podStorage) merge(source string, change interface{}) (adds, updates, de adds = &kubetypes.PodUpdate{Op: kubetypes.ADD, Pods: copyPods(addPods), Source: source} updates = &kubetypes.PodUpdate{Op: kubetypes.UPDATE, Pods: copyPods(updatePods), Source: source} - deletes = &kubetypes.PodUpdate{Op: kubetypes.REMOVE, Pods: copyPods(deletePods), Source: source} + deletes = &kubetypes.PodUpdate{Op: kubetypes.DELETE, Pods: copyPods(deletePods), Source: source} + removes = &kubetypes.PodUpdate{Op: kubetypes.REMOVE, Pods: copyPods(removePods), Source: source} reconciles = &kubetypes.PodUpdate{Op: kubetypes.RECONCILE, Pods: copyPods(reconcilePods), Source: source} - return adds, updates, deletes, reconciles + return adds, updates, deletes, removes, reconciles } func (s *podStorage) markSourceSet(source string) { @@ -328,7 +341,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco name := bestPodIdentString(pod) err := errlist.ToAggregate() glog.Warningf("Pod[%d] (%s) from %s failed validation, ignoring: %v", i+1, name, source, err) - recorder.Eventf(pod, api.EventTypeWarning, kubecontainer.FailedValidation, "Error validating pod %s from %s, ignoring: %v", name, source, err) + recorder.Eventf(pod, api.EventTypeWarning, events.FailedValidation, "Error validating pod %s from %s, ignoring: %v", name, source, err) continue } filtered = append(filtered, pod) @@ -413,10 +426,13 @@ func podsDifferSemantically(existing, ref *api.Pod) bool { // checkAndUpdatePod updates existing, and: // * if ref makes a meaningful change, returns needUpdate=true +// * if ref makes a meaningful change, and this change is graceful deletion, returns needGracefulDelete=true // * if ref makes no meaningful change, but changes the pod status, returns needReconcile=true -// * else return both false -// Now, needUpdate and needReconcile should never be both true -func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile bool) { +// * else return all false +// Now, needUpdate, needGracefulDelete and needReconcile should never be both true +func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile, needGracefulDelete bool) { + + // 1. this is a reconcile // TODO: it would be better to update the whole object and only preserve certain things // like the source annotation or the UID (to ensure safety) if !podsDifferSemantically(existing, ref) { @@ -431,7 +447,6 @@ func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile bool) } return } - // this is an update // Overwrite the first-seen time with the existing one. This is our own // internal annotation, there is no need to update. @@ -443,7 +458,15 @@ func checkAndUpdatePod(existing, ref *api.Pod) (needUpdate, needReconcile bool) existing.DeletionGracePeriodSeconds = ref.DeletionGracePeriodSeconds existing.Status = ref.Status updateAnnotations(existing, ref) - needUpdate = true + + // 2. this is an graceful delete + if ref.DeletionTimestamp != nil { + needGracefulDelete = true + } else { + // 3. this is an update + needUpdate = true + } + return } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/doc.go index 511d05522086..1d839ba325ec 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/file.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/file.go index da5cd74007d2..bc2d346c9530 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/file.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/file.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/http.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/http.go index 0752e5fa3021..c061714a5a23 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/http.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/http.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/config/sources.go b/vendor/k8s.io/kubernetes/pkg/kubelet/config/sources.go index e26b9de28a49..772c020ab394 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/config/sources.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/config/sources.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache.go index 219ad49f397a..a15acf006c24 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_gc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_gc.go index c749a43037b3..a66acc9ef091 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_gc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_gc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_reference_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_reference_manager.go index 1f44389c7f17..f37a7103ab24 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_reference_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/container_reference_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers.go index 8aacbea11b35..b0b9d0c84bb8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/types" hashutil "k8s.io/kubernetes/pkg/util/hash" - "k8s.io/kubernetes/third_party/golang/expansion" + "k8s.io/kubernetes/third_party/forked/golang/expansion" "github.com/golang/glog" ) @@ -95,11 +95,12 @@ func ConvertPodStatusToRunningPod(podStatus *PodStatus) Pod { continue } container := &Container{ - ID: containerStatus.ID, - Name: containerStatus.Name, - Image: containerStatus.Image, - Hash: containerStatus.Hash, - State: containerStatus.State, + ID: containerStatus.ID, + Name: containerStatus.Name, + Image: containerStatus.Image, + ImageID: containerStatus.ImageID, + Hash: containerStatus.Hash, + State: containerStatus.State, } runningPod.Containers = append(runningPod.Containers, container) } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/interface.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/interface.go new file mode 100644 index 000000000000..198545ecd208 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/interface.go @@ -0,0 +1,413 @@ +/* +Copyright 2016 The Kubernetes 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 container + +import ( + "io" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/unversioned" +) + +type PodSandboxID string + +// PodSandboxManager provides basic operations to create/delete and examine the +// PodSandboxes. These methods should either return an error or block until the +// operation succeeds. +type PodSandboxManager interface { + // Create creates a sandbox based on the given config, and returns the + // the new sandbox. + Create(config *PodSandboxConfig) (PodSandboxID, error) + // Stop stops the sandbox by its ID. If there are any running + // containers in the sandbox, they will be terminated as a side-effect. + Stop(id PodSandboxID) error + // Delete deletes the sandbox by its ID. If there are any running + // containers in the sandbox, they will be deleted as a side-effect. + Delete(id PodSandboxID) error + // List lists existing sandboxes, filtered by the given PodSandboxFilter. + List(filter PodSandboxFilter) ([]PodSandboxListItem, error) + // Status gets the status of the sandbox by ID. + Status(id PodSandboxID) (PodSandboxStatus, error) +} + +// PodSandboxConfig holds all the required and optional fields for creating a +// sandbox. +type PodSandboxConfig struct { + // Name is the name of the sandbox. The string should conform to + // [a-zA-Z0-9_-]+. + Name string + // Hostname is the hostname of the sandbox. + Hostname string + // DNSOptions sets the DNS options for the sandbox. + DNSOptions DNSOptions + // PortMappings lists the port mappings for the sandbox. + PortMappings []PortMapping + // Resources specifies the resource limits for the sandbox (i.e., the + // aggregate cpu/memory resources limits of all containers). + // Note: On a Linux host, kubelet will create a pod-level cgroup and pass + // it as the cgroup parent for the PodSandbox. For some runtimes, this is + // sufficent. For others, e.g., hypervisor-based runtimes, explicit + // resource limits for the sandbox are needed at creation time. + Resources PodSandboxResources + // Path to the directory on the host in which container log files are + // stored. + // By default the Log of a container going into the LogDirectory will be + // hooked up to STDOUT and STDERR. However, the LogDirectory may contain + // binary log files with structured logging data from the individual + // containers. For example the files might be newline seperated JSON + // structured logs, systemd-journald journal files, gRPC trace files, etc. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + LogDirectory string + // Labels are key value pairs that may be used to scope and select + // individual resources. + Labels Labels + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + Annotations map[string]string + + // Linux contains configurations specific to Linux hosts. + Linux *LinuxPodSandboxConfig +} + +// Labels are key value pairs that may be used to scope and select individual +// resources. +// Label keys are of the form: +// label-key ::= prefixed-name | name +// prefixed-name ::= prefix '/' name +// prefix ::= DNS_SUBDOMAIN +// name ::= DNS_LABEL +type Labels map[string]string + +// LinuxPodSandboxConfig holds platform-specific configuraions for Linux +// host platforms and Linux-based containers. +type LinuxPodSandboxConfig struct { + // CgroupParent is the parent cgroup of the sandbox. The cgroupfs style + // syntax will be used, but the container runtime can convert it to systemd + // semantices if needed. + CgroupParent string + // NamespaceOptions contains configurations for the sandbox's namespaces. + // This will be used only if the PodSandbox uses namespace for isolation. + NamespaceOptions NamespaceOptions +} + +// NamespaceOptions provides options for Linux namespaces. +type NamespaceOptions struct { + // HostNetwork uses the host's network namespace. + HostNetwork bool + // HostPID uses the host's pid namesapce. + HostPID bool + // HostIPC uses the host's ipc namespace. + HostIPC bool +} + +// DNSOptions specifies the DNS servers and search domains. +type DNSOptions struct { + // Servers is a list of DNS servers of the cluster. + Servers []string + // Searches is a list of DNS search domains of the cluster. + Searches []string +} + +type PodSandboxState string + +const ( + // PodSandboxReady means the sandbox is functioning properly. + PodSandboxReady PodSandboxState = "Ready" + // PodSandboxInNotReady means the sandbox is not functioning properly. + PodSandboxNotReady PodSandboxState = "NotReady" +) + +// PodSandboxFilter is used to filter a list of PodSandboxes. +type PodSandboxFilter struct { + // Name of the sandbox. + Name *string + // ID of the sandbox. + ID *PodSandboxID + // State of the sandbox. + State *PodSandboxState + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + LabelSelector unversioned.LabelSelector +} + +// PodSandboxListItem contains minimal information about a sandbox. +type PodSandboxListItem struct { + ID PodSandboxID + State PodSandboxState + // Labels are key value pairs that may be used to scope and select individual resources. + Labels Labels +} + +// PodSandboxStatus contains the status of the PodSandbox. +type PodSandboxStatus struct { + // ID of the sandbox. + ID PodSandboxID + // State of the sandbox. + State PodSandboxState + // Network contains network status if network is handled by the runtime. + Network *PodSandboxNetworkStatus + // Status specific to a Linux sandbox. + Linux *LinuxPodSandboxStatus + // Labels are key value pairs that may be used to scope and select individual resources. + Labels Labels + // Annotations is an unstructured key value map. + Annotations map[string]string +} + +// PodSandboxNetworkStatus is the status of the network for a PodSandbox. +type PodSandboxNetworkStatus struct { + IPs []string +} + +// Namespaces contains paths to the namespaces. +type Namespaces struct { + // Network is the path to the network namespace. + Network string +} + +// LinuxSandBoxStatus contains status specific to Linux sandboxes. +type LinuxPodSandboxStatus struct { + // Namespaces contains paths to the sandbox's namespaces. + Namespaces *Namespaces +} + +// PodSandboxResources contains the CPU/memory resource requirements. +type PodSandboxResources struct { + // CPU resource requirement. + CPU resource.Quantity + // Memory resource requirement. + Memory resource.Quantity +} + +// This is to distinguish with existing ContainerID type, which includes a +// runtime type prefix (e.g., docker://). We may rename this later. +type RawContainerID string + +// ContainerRuntime provides methods for container lifecycle operations, as +// well as listing or inspecting existing containers. These methods should +// either return an error or block until the operation succeeds. +type ContainerRuntime interface { + // Create creates a container in the sandbox, and returns the ID + // of the created container. + Create(config *ContainerConfig, sandboxConfig *PodSandboxConfig, sandboxID PodSandboxID) (RawContainerID, error) + // Start starts a created container. + Start(id RawContainerID) error + // Stop stops a running container with a grace period (i.e., timeout). + Stop(id RawContainerID, timeout int) error + // Remove removes the container. + Remove(id RawContainerID) error + // List lists the existing containers that match the ContainerFilter. + // The returned list should only include containers previously created + // by this ContainerRuntime. + List(filter ContainerFilter) ([]ContainerListItem, error) + // Status returns the status of the container. + Status(id RawContainerID) (RawContainerStatus, error) + // Exec executes a command in the container. + Exec(id RawContainerID, cmd []string, streamOpts StreamOptions) error +} + +// ContainerListItem provides the runtime information for a container returned +// by List(). +type ContainerListItem struct { + // The ID of the container, used by the container runtime to identify + // a container. + ID ContainerID + // The name of the container, which should be the same as specified by + // api.Container. + Name string + // Reference to the image in use. For most runtimes, this should be an + // image ID. + ImageRef string + // State is the state of the container. + State ContainerState + // Labels are key value pairs that may be used to scope and select individual resources. + Labels Labels +} + +type ContainerConfig struct { + // Name of the container. The string should conform to [a-zA-Z0-9_-]+. + Name string + // Image to use. + Image ImageSpec + // Command to execute (i.e., entrypoint for docker) + Command []string + // Args for the Command (i.e., command for docker) + Args []string + // Current working directory of the command. + WorkingDir string + // List of environment variable to set in the container + Env []KeyValue + // Mounts specifies mounts for the container + Mounts []Mount + // Labels are key value pairs that may be used to scope and select individual resources. + Labels Labels + // Annotations is an unstructured key value map that may be set by external + // tools to store and retrieve arbitrary metadata. + Annotations map[string]string + // Privileged runs the container in the privileged mode. + Privileged bool + // ReadOnlyRootFS sets the root filesystem of the container to be + // read-only. + ReadOnlyRootFS bool + // Path relative to PodSandboxConfig.LogDirectory for container to store + // the log (STDOUT and STDERR) on the host. + // E.g., + // PodSandboxConfig.LogDirectory = `/var/log/pods//` + // ContainerConfig.LogPath = `containerName_Instance#.log` + // + // WARNING: Log managment and how kubelet should interface with the + // container logs are under active discussion in + // https://issues.k8s.io/24677. There *may* be future change of direction + // for logging as the discussion carries on. + LogPath string + + // Variables for interactive containers, these have very specialized + // use-cases (e.g. debugging). + // TODO: Determine if we need to continue supporting these fields that are + // part of Kubernetes's Container Spec. + STDIN bool + STDINONCE bool + TTY bool + + // Linux contains configuration specific to Linux containers. + Linux *LinuxContainerConfig +} + +// RawContainerStatus represents the status of a container. +type RawContainerStatus struct { + // ID of the container. + ID ContainerID + // Name of the container. + Name string + // Status of the container. + State ContainerState + // Creation time of the container. + CreatedAt unversioned.Time + // Start time of the container. + StartedAt unversioned.Time + // Finish time of the container. + FinishedAt unversioned.Time + // Exit code of the container. + ExitCode int + // Reference to the image in use. For most runtimes, this should be an + // image ID. + ImageRef string + // Labels are key value pairs that may be used to scope and select individual resources. + Labels Labels + // Annotations is an unstructured key value map. + Annotations map[string]string + // A brief CamelCase string explains why container is in such a status. + Reason string +} + +// LinuxContainerConfig contains platform-specific configuration for +// Linux-based containers. +type LinuxContainerConfig struct { + // Resources specification for the container. + Resources *LinuxContainerResources + // Capabilities to add or drop. + Capabilities *api.Capabilities + // SELinux is the SELinux context to be applied. + SELinux *api.SELinuxOptions + // TODO: Add support for seccomp. +} + +// LinuxContainerResources specifies Linux specific configuration for +// resources. +// TODO: Consider using Resources from opencontainers/runtime-spec/specs-go +// directly. +type LinuxContainerResources struct { + // CPU CFS (Completely Fair Scheduler) period + CPUPeriod *int64 + // CPU CFS (Completely Fair Scheduler) quota + CPUQuota *int64 + // CPU shares (relative weight vs. other containers) + CPUShares *int64 + // Memory limit in bytes + MemoryLimitInBytes *int64 + // OOMScoreAdj adjusts the oom-killer score. + OOMScoreAdj *int64 +} + +// ContainerFilter is used to filter containers. +type ContainerFilter struct { + // Name of the container. + Name *string + // ID of the container. + ID *RawContainerID + // State of the contianer. + State *ContainerState + // ID of the PodSandbox. + PodSandboxID *PodSandboxID + // LabelSelector to select matches. + // Only api.MatchLabels is supported for now and the requirements + // are ANDed. MatchExpressions is not supported yet. + LabelSelector unversioned.LabelSelector +} + +type StreamOptions struct { + TTY bool + InputStream io.Reader + OutputStream io.Writer + ErrorStream io.Writer +} + +// KeyValue represents a key-value pair. +type KeyValue struct { + Key string + Value string +} + +// ImageService offers basic image operations. +type ImageService interface { + // List lists the existing images. + List() ([]Image, error) + // Pull pulls an image with authentication config. The PodSandboxConfig is + // passed so that the image service can charge the resources used for + // pulling to a sepcific pod. + Pull(image ImageSpec, auth AuthConfig, sandboxConfig *PodSandboxConfig) error + // Remove removes an image. + Remove(image ImageSpec) error + // Status returns the status of an image. + Status(image ImageSpec) (Image, error) +} + +// AuthConfig contains authorization information for connecting to a registry. +// TODO: This is copied from docker's Authconfig. We should re-evaluate to +// support other registries. +type AuthConfig struct { + Username string + Password string + Auth string + ServerAddress string + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + IdentityToken string + // RegistryToken is a bearer token to be sent to a registry + RegistryToken string +} + +// TODO: Add ContainerMetricsGetter and ImageMetricsGetter. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/kuberuntime.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/kuberuntime.go new file mode 100644 index 000000000000..1e031681718d --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/kuberuntime.go @@ -0,0 +1,71 @@ +/* +Copyright 2016 The Kubernetes 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 container + +import ( + "io" + + runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime" +) + +// RuntimeService interface should be implemented by a container runtime. +// The methods should be thread-safe. +type RuntimeService interface { + // Version returns the runtime name, runtime version and runtime API version + Version(apiVersion string) (*runtimeApi.VersionResponse, error) + // CreatePodSandbox creates a pod-level sandbox. + // The definition of PodSandbox is at https://github.com/kubernetes/kubernetes/pull/25899 + CreatePodSandbox(config *runtimeApi.PodSandboxConfig) (string, error) + // StopPodSandbox stops the sandbox. If there are any running containers in the + // sandbox, they should be force terminated. + StopPodSandbox(podSandboxID string) error + // DeletePodSandbox deletes the sandbox. If there are running containers in the + // sandbox, they should be forcibly deleted. + DeletePodSandbox(podSandboxID string) error + // PodSandboxStatus returns the Status of the PodSandbox. + PodSandboxStatus(podSandboxID string) (*runtimeApi.PodSandboxStatus, error) + // ListPodSandbox returns a list of Sandbox. + ListPodSandbox(filter *runtimeApi.PodSandboxFilter) ([]*runtimeApi.PodSandbox, error) + // CreateContainer creates a new container in specified PodSandbox. + CreateContainer(podSandboxID string, config *runtimeApi.ContainerConfig, sandboxConfig *runtimeApi.PodSandboxConfig) (string, error) + // StartContainer starts the container. + StartContainer(rawContainerID string) error + // StopContainer stops a running container with a grace period (i.e., timeout). + StopContainer(rawContainerID string, timeout int64) error + // RemoveContainer removes the container. + RemoveContainer(rawContainerID string) error + // ListContainers lists all containers by filters. + ListContainers(filter *runtimeApi.ContainerFilter) ([]*runtimeApi.Container, error) + // ContainerStatus returns the status of the container. + ContainerStatus(rawContainerID string) (*runtimeApi.ContainerStatus, error) + // Exec executes a command in the container. + Exec(rawContainerID string, cmd []string, tty bool, stdin io.Reader, stdout, stderr io.WriteCloser) error +} + +// ImageManagerService interface should be implemented by a container image +// manager. +// The methods should be thread-safe. +type ImageManagerService interface { + // ListImages lists the existing images. + ListImages(filter *runtimeApi.ImageFilter) ([]*runtimeApi.Image, error) + // ImageStatus returns the status of the image. + ImageStatus(image *runtimeApi.ImageSpec) (*runtimeApi.Image, error) + // PullImage pulls an image with the authentication config. + PullImage(image *runtimeApi.ImageSpec, auth *runtimeApi.AuthConfig) error + // RemoveImage removes the image. + RemoveImage(image *runtimeApi.ImageSpec) error +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/os.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/os.go index 21c0264e2af4..8a07391998a3 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/os.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/os.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ type OSInterface interface { ReadDir(dirname string) ([]os.FileInfo, error) } -// RealOS is used to dispatch the real system level operaitons. +// RealOS is used to dispatch the real system level operations. type RealOS struct{} // MkDir will will call os.Mkdir to create a directory. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_linux.go index cbc36f6d3ff7..40906ce99b63 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_unsupported.go index b48a999b0a96..24ea2f787f82 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/pty_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref.go index ebfff2ebf703..8fcdc95ad218 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/resize.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/resize.go new file mode 100644 index 000000000000..168603177736 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/resize.go @@ -0,0 +1,46 @@ +/* +Copyright 2015 The Kubernetes 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 container + +import ( + "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/term" +) + +// handleResizing spawns a goroutine that processes the resize channel, calling resizeFunc for each +// term.Size received from the channel. The resize channel must be closed elsewhere to stop the +// goroutine. +func HandleResizing(resize <-chan term.Size, resizeFunc func(size term.Size)) { + if resize == nil { + return + } + + go func() { + defer runtime.HandleCrash() + + for { + size, ok := <-resize + if !ok { + return + } + if size.Height < 1 || size.Width < 1 { + continue + } + resizeFunc(size) + } + }() +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime.go index d48f4a7024a5..c407bd97828b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/flowcontrol" + "k8s.io/kubernetes/pkg/util/term" "k8s.io/kubernetes/pkg/volume" ) @@ -119,6 +120,8 @@ type Runtime interface { // stream the log. Set 'follow' to false and specify the number of lines (e.g. // "100" or "all") to tail the log. GetContainerLogs(pod *api.Pod, containerID ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) + // Delete a container. If the container is still running, an error is returned. + DeleteContainer(containerID ContainerID) error // ContainerCommandRunner encapsulates the command runner interfaces for testability. ContainerCommandRunner // ContainerAttach encapsulates the attaching to containers for testability @@ -126,7 +129,7 @@ type Runtime interface { } type ContainerAttacher interface { - AttachContainer(id ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) (err error) + AttachContainer(id ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) (err error) } // CommandRunner encapsulates the command runner interfaces for testability. @@ -134,18 +137,11 @@ type ContainerCommandRunner interface { // Runs the command in the container of the specified pod using nsenter. // Attaches the processes stdin, stdout, and stderr. Optionally uses a // tty. - ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error + ExecInContainer(containerID ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error // Forward the specified port from the specified pod to the stream. PortForward(pod *Pod, port uint16, stream io.ReadWriteCloser) error } -// ImagePuller wraps Runtime.PullImage() to pull a container image. -// It will check the presence of the image, and report the 'image pulling', -// 'image pulled' events correspondingly. -type ImagePuller interface { - PullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) -} - // Pod is a group of containers. type Pod struct { // The ID of the pod, which can be used to retrieve a particular pod @@ -233,6 +229,8 @@ const ( ContainerStateExited ContainerState = "exited" // This unknown encompasses all the states that we currently don't care. ContainerStateUnknown ContainerState = "unknown" + // Not in use yet. + ContainerStateCreated ContainerState = "created" ) // Container provides the runtime information for a container, such as ID, hash, @@ -247,6 +245,8 @@ type Container struct { // The image name of the container, this also includes the tag of the image, // the expected form is "NAME:TAG". Image string + // The id of the image used by the container. + ImageID string // Hash of the container, used for comparison. Optional for containers // not managed by kubelet. Hash uint64 diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache.go index 0926107da5a0..d15852f886a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_fake.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_fake.go index 0b6e7d868bfd..5416d9167234 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_fake.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_fake.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result.go index 6a196f602b2a..5a976115585b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,24 +29,9 @@ import ( var ErrCrashLoopBackOff = errors.New("CrashLoopBackOff") var ( - // Container image pull failed, kubelet is backing off image pull - ErrImagePullBackOff = errors.New("ImagePullBackOff") - - // Unable to inspect image - ErrImageInspect = errors.New("ImageInspectError") - - // General image pull error - ErrImagePull = errors.New("ErrImagePull") - - // Required Image is absent on host and PullPolicy is NeverPullImage - ErrImageNeverPull = errors.New("ErrImageNeverPull") - // ErrContainerNotFound returned when a container in the given pod with the // given container name was not found, amongst those managed by the kubelet. ErrContainerNotFound = errors.New("no matching container") - - // Get http error when pulling image from registry - RegistryUnavailable = errors.New("RegistryUnavailable") ) var ( diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container_bridge.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container_bridge.go index e151dc709b47..525550230884 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container_bridge.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/container_bridge.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/custommetrics/custom_metrics.go b/vendor/k8s.io/kubernetes/pkg/kubelet/custommetrics/custom_metrics.go index 05a628a440bc..314a3b5df006 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/custommetrics/custom_metrics.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/custommetrics/custom_metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/disk_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/disk_manager.go index edf749b4f8b8..b5b0d499dd9f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/disk_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/disk_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/doc.go index 8fd7b3b3df37..7d31922769f4 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/container_gc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/container_gc.go index b6e7acb5fc8d..5b00875b70ee 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/container_gc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/container_gc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -111,15 +111,7 @@ func (cgc *containerGC) removeOldestN(containers []containerGCInfo, toRemove int // Remove from oldest to newest (last to first). numToKeep := len(containers) - toRemove for i := numToKeep; i < len(containers); i++ { - err := cgc.client.RemoveContainer(containers[i].id, dockertypes.ContainerRemoveOptions{RemoveVolumes: true}) - if err != nil { - glog.Warningf("Failed to remove dead container %q: %v", containers[i].name, err) - } - symlinkPath := LogSymlink(cgc.containerLogsDir, containers[i].podNameWithNamespace, containers[i].containerName, containers[i].id) - err = os.Remove(symlinkPath) - if err != nil && !os.IsNotExist(err) { - glog.Warningf("Failed to remove container %q log symlink %q: %v", containers[i].name, symlinkPath, err) - } + cgc.removeContainer(containers[i].id, containers[i].podNameWithNamespace, containers[i].containerName) } // Assume we removed the containers so that we're not too aggressive. @@ -253,6 +245,38 @@ func (cgc *containerGC) GarbageCollect(gcPolicy kubecontainer.ContainerGCPolicy, return nil } +func (cgc *containerGC) removeContainer(id string, podNameWithNamespace string, containerName string) { + glog.V(4).Infof("Removing container %q name %q", id, containerName) + err := cgc.client.RemoveContainer(id, dockertypes.ContainerRemoveOptions{RemoveVolumes: true}) + if err != nil { + glog.Warningf("Failed to remove container %q: %v", id, err) + } + symlinkPath := LogSymlink(cgc.containerLogsDir, podNameWithNamespace, containerName, id) + err = os.Remove(symlinkPath) + if err != nil && !os.IsNotExist(err) { + glog.Warningf("Failed to remove container %q log symlink %q: %v", id, symlinkPath, err) + } +} + +func (cgc *containerGC) deleteContainer(id string) error { + containerInfo, err := cgc.client.InspectContainer(id) + if err != nil { + glog.Warningf("Failed to inspect container %q: %v", id, err) + return err + } + if containerInfo.State.Running { + return fmt.Errorf("container %q is still running", id) + } + + containerName, _, err := ParseDockerName(containerInfo.Name) + if err != nil { + return err + } + + cgc.removeContainer(id, containerName.PodFullName, containerName.ContainerName) + return nil +} + func (cgc *containerGC) isPodDeleted(podUID types.UID) bool { _, found := cgc.podGetter.GetPodByUID(podUID) return !found diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/convert.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/convert.go index 48c594ff1af2..2bbf3758dce2 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/convert.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/convert.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -56,10 +56,11 @@ func toRuntimeContainer(c *dockertypes.Container) (*kubecontainer.Container, err } return &kubecontainer.Container{ - ID: kubecontainer.DockerID(c.ID).ContainerID(), - Name: dockerName.ContainerName, - Image: c.Image, - Hash: hash, + ID: kubecontainer.DockerID(c.ID).ContainerID(), + Name: dockerName.ContainerName, + Image: c.Image, + ImageID: c.ImageID, + Hash: hash, // (random-liu) docker uses status to indicate whether a container is running or exited. // However, in kubernetes we usually use state to indicate whether a container is running or exited, // while use status to indicate the comprehensive status of the container. So we have different naming diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker.go index be94cf5fe288..e71f93d96b6e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/credentialprovider" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/images" "k8s.io/kubernetes/pkg/kubelet/leaky" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" @@ -44,6 +45,7 @@ const ( PodInfraContainerName = leaky.PodInfraContainerName DockerPrefix = "docker://" LogSuffix = "log" + ext4MaxFileNameLen = 255 ) const ( @@ -53,8 +55,8 @@ const ( milliCPUToCPU = 1000 // 100000 is equivalent to 100ms - quotaPeriod = 100000 - minQuotaPerod = 1000 + quotaPeriod = 100000 + minQuotaPeriod = 1000 ) // DockerInterface is an abstract interface for testability. It abstracts the interface of docker client. @@ -77,6 +79,8 @@ type DockerInterface interface { StartExec(string, dockertypes.ExecStartCheck, StreamOptions) error InspectExec(id string) (*dockertypes.ContainerExecInspect, error) AttachToContainer(string, dockertypes.ContainerAttachOptions, StreamOptions) error + ResizeContainerTTY(id string, height, width int) error + ResizeExecTTY(id string, height, width int) error } // KubeletContainerName encapsulates a pod name and a Kubernetes container name. @@ -140,7 +144,7 @@ func filterHTTPError(err error, image string) error { jerr.Code == http.StatusServiceUnavailable || jerr.Code == http.StatusGatewayTimeout) { glog.V(2).Infof("Pulling image %q failed: %v", image, err) - return kubecontainer.RegistryUnavailable + return images.RegistryUnavailable } else { return err } @@ -297,7 +301,13 @@ func ParseDockerName(name string) (dockerName *KubeletContainerName, hash uint64 } func LogSymlink(containerLogsDir, podFullName, containerName, dockerId string) string { - return path.Join(containerLogsDir, fmt.Sprintf("%s_%s-%s.%s", podFullName, containerName, dockerId, LogSuffix)) + suffix := fmt.Sprintf(".%s", LogSuffix) + logPath := fmt.Sprintf("%s_%s-%s", podFullName, containerName, dockerId) + // Length of a filename cannot exceed 255 characters in ext4 on Linux. + if len(logPath) > ext4MaxFileNameLen-len(suffix) { + logPath = logPath[:ext4MaxFileNameLen-len(suffix)] + } + return path.Join(containerLogsDir, logPath+suffix) } // Get a *dockerapi.Client, either using the endpoint passed in, or using @@ -348,8 +358,8 @@ func milliCPUToQuota(milliCPU int64) (quota int64, period int64) { quota = (milliCPU * quotaPeriod) / milliCPUToCPU // quota needs to be a minimum of 1ms. - if quota < minQuotaPerod { - quota = minQuotaPerod + if quota < minQuotaPeriod { + quota = minQuotaPeriod } return @@ -372,7 +382,6 @@ func milliCPUToShares(milliCPU int64) int64 { // GetKubeletDockerContainers lists all container or just the running ones. // Returns a list of docker containers that we manage -// TODO: Move this function with dockerCache to DockerManager. func GetKubeletDockerContainers(client DockerInterface, allContainers bool) ([]*dockertypes.Container, error) { result := []*dockertypes.Container{} containers, err := client.ListContainers(dockertypes.ContainerListOptions{All: allContainers}) @@ -386,9 +395,7 @@ func GetKubeletDockerContainers(client DockerInterface, allContainers bool) ([]* } // Skip containers that we didn't create to allow users to manually // spin up their own containers if they want. - // TODO(dchen1107): Remove the old separator "--" by end of Oct - if !strings.HasPrefix(container.Names[0], "/"+containerNamePrefix+"_") && - !strings.HasPrefix(container.Names[0], "/"+containerNamePrefix+"--") { + if !strings.HasPrefix(container.Names[0], "/"+containerNamePrefix+"_") { glog.V(3).Infof("Docker Container: %s is not managed by kubelet.", container.Names[0]) continue } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker_manager.go index 31742838a652..bff3e8891b67 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/docker_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,10 +32,11 @@ import ( "sync" "time" + "github.com/coreos/go-semver/semver" dockertypes "github.com/docker/engine-api/types" dockercontainer "github.com/docker/engine-api/types/container" dockerstrslice "github.com/docker/engine-api/types/strslice" - dockerversion "github.com/docker/engine-api/types/versions" + dockerapiversion "github.com/docker/engine-api/types/versions" dockernat "github.com/docker/go-connections/nat" "github.com/golang/glog" cadvisorapi "github.com/google/cadvisor/info/v1" @@ -44,6 +45,8 @@ import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" + "k8s.io/kubernetes/pkg/kubelet/images" "k8s.io/kubernetes/pkg/kubelet/lifecycle" "k8s.io/kubernetes/pkg/kubelet/metrics" "k8s.io/kubernetes/pkg/kubelet/network" @@ -62,6 +65,7 @@ import ( utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" utilstrings "k8s.io/kubernetes/pkg/util/strings" + "k8s.io/kubernetes/pkg/util/term" ) const ( @@ -125,7 +129,7 @@ type DockerManager struct { dockerPuller DockerPuller // wrapped image puller. - imagePuller kubecontainer.ImagePuller + imagePuller images.ImageManager // Root of the Docker runtime. dockerRoot string @@ -221,7 +225,7 @@ func NewDockerManager( seccompProfileRoot string, options ...kubecontainer.Option) *DockerManager { // Wrap the docker client with instrumentedDockerInterface - client = newInstrumentedDockerInterface(client) + client = NewInstrumentedDockerInterface(client) // Work out the location of the Docker runtime, defaulting to /var/lib/docker // if there are any problems. @@ -258,11 +262,7 @@ func NewDockerManager( seccompProfileRoot: seccompProfileRoot, } dm.runner = lifecycle.NewHandlerRunner(httpClient, dm, dm) - if serializeImagePulls { - dm.imagePuller = kubecontainer.NewSerializedImagePuller(kubecontainer.FilterEventRecorder(recorder), dm, imageBackOff) - } else { - dm.imagePuller = kubecontainer.NewImagePuller(kubecontainer.FilterEventRecorder(recorder), dm, imageBackOff) - } + dm.imagePuller = images.NewImageManager(kubecontainer.FilterEventRecorder(recorder), dm, imageBackOff, serializeImagePulls) dm.containerGC = NewContainerGC(client, podGetter, containerLogsDir) dm.versionCache = cache.NewObjectCache( @@ -694,20 +694,20 @@ func (dm *DockerManager) runContainer( securityContextProvider.ModifyHostConfig(pod, container, dockerOpts.HostConfig, supplementalGids) createResp, err := dm.client.CreateContainer(dockerOpts) if err != nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedToCreateContainer, "Failed to create docker container with error: %v", err) + dm.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create docker container with error: %v", err) return kubecontainer.ContainerID{}, err } if len(createResp.Warnings) != 0 { glog.V(2).Infof("Container %q of pod %q created with warnings: %v", container.Name, format.Pod(pod), createResp.Warnings) } - dm.recorder.Eventf(ref, api.EventTypeNormal, kubecontainer.CreatedContainer, "Created container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) + dm.recorder.Eventf(ref, api.EventTypeNormal, events.CreatedContainer, "Created container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) if err = dm.client.StartContainer(createResp.ID); err != nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedToStartContainer, + dm.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToStartContainer, "Failed to start container with docker id %v with error: %v", utilstrings.ShortenString(createResp.ID, 12), err) return kubecontainer.ContainerID{}, err } - dm.recorder.Eventf(ref, api.EventTypeNormal, kubecontainer.StartedContainer, "Started container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) + dm.recorder.Eventf(ref, api.EventTypeNormal, events.StartedContainer, "Started container with docker id %v", utilstrings.ShortenString(createResp.ID, 12)) return kubecontainer.DockerID(createResp.ID).ContainerID(), nil } @@ -848,7 +848,6 @@ func (dm *DockerManager) ListImages() ([]kubecontainer.Image, error) { return images, nil } -// TODO(vmarmol): Consider unexporting. // PullImage pulls an image from network to local storage. func (dm *DockerManager) PullImage(image kubecontainer.ImageSpec, secrets []api.Secret) error { return dm.dockerPuller.Pull(image.Image, secrets) @@ -924,18 +923,52 @@ func getDockerNetworkMode(container *dockertypes.ContainerJSON) string { return "" } -// dockerVersion implementes kubecontainer.Version interface by implementing -// Compare() and String(). It could contain either server version or api version. -type dockerVersion string +// dockerVersion implements kubecontainer.Version interface by implementing +// Compare() and String() (which is implemented by the underlying semver.Version) +// TODO: this code is the same as rktVersion and may make sense to be moved to +// somewhere shared. +type dockerVersion struct { + *semver.Version +} + +// newDockerVersion returns a semantically versioned docker version value +func newDockerVersion(version string) (dockerVersion, error) { + sem, err := semver.NewVersion(version) + return dockerVersion{sem}, err +} + +func (r dockerVersion) String() string { + return r.Version.String() +} + +func (r dockerVersion) Compare(other string) (int, error) { + v, err := newDockerVersion(other) + if err != nil { + return -1, err + } + + if r.LessThan(*v.Version) { + return -1, nil + } + if v.Version.LessThan(*r.Version) { + return 1, nil + } + return 0, nil +} + +// apiVersion implements kubecontainer.Version interface by implementing +// Compare() and String(). It uses the compare function of engine-api to +// compare docker apiversions. +type apiVersion string -func (v dockerVersion) String() string { +func (v apiVersion) String() string { return string(v) } -func (v dockerVersion) Compare(other string) (int, error) { - if dockerversion.LessThan(string(v), other) { +func (v apiVersion) Compare(other string) (int, error) { + if dockerapiversion.LessThan(string(v), other) { return -1, nil - } else if dockerversion.GreaterThan(string(v), other) { + } else if dockerapiversion.GreaterThan(string(v), other) { return 1, nil } return 0, nil @@ -950,8 +983,11 @@ func (dm *DockerManager) Version() (kubecontainer.Version, error) { if err != nil { return nil, fmt.Errorf("docker: failed to get docker version: %v", err) } - - return dockerVersion(v.Version), nil + version, err := newDockerVersion(v.Version) + if err != nil { + return nil, fmt.Errorf("docker: failed to parse docker version %q: %v", v.Version, err) + } + return version, nil } func (dm *DockerManager) APIVersion() (kubecontainer.Version, error) { @@ -960,7 +996,7 @@ func (dm *DockerManager) APIVersion() (kubecontainer.Version, error) { return nil, fmt.Errorf("docker: failed to get docker version: %v", err) } - return dockerVersion(v.APIVersion), nil + return apiVersion(v.APIVersion), nil } // Status returns error if docker daemon is unhealthy, nil otherwise. @@ -1070,7 +1106,7 @@ func (d *dockerExitError) ExitStatus() int { } // ExecInContainer runs the command inside the container identified by containerID. -func (dm *DockerManager) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (dm *DockerManager) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { if dm.execHandler == nil { return errors.New("unable to exec without an exec handler") } @@ -1083,10 +1119,16 @@ func (dm *DockerManager) ExecInContainer(containerID kubecontainer.ContainerID, return fmt.Errorf("container not running (%s)", container.ID) } - return dm.execHandler.ExecInContainer(dm.client, container, cmd, stdin, stdout, stderr, tty) + return dm.execHandler.ExecInContainer(dm.client, container, cmd, stdin, stdout, stderr, tty, resize) } -func (dm *DockerManager) AttachContainer(containerID kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (dm *DockerManager) AttachContainer(containerID kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { + // Have to start this before the call to client.AttachToContainer because client.AttachToContainer is a blocking + // call :-( Otherwise, resize events don't get processed and the terminal never resizes. + kubecontainer.HandleResizing(resize, func(size term.Size) { + dm.client.ResizeContainerTTY(containerID.ID, int(size.Height), int(size.Width)) + }) + // TODO(random-liu): Do we really use the *Logs* field here? opts := dockertypes.ContainerAttachOptions{ Stream: true, @@ -1186,7 +1228,6 @@ func (dm *DockerManager) KillPod(pod *api.Pod, runningPod kubecontainer.Pod, gra return result.Error() } -// TODO(random-liu): This is just a temporary function, will be removed when we acturally add PodSyncResult // NOTE(random-liu): The pod passed in could be *nil* when kubelet restarted. func (dm *DockerManager) killPodWithSyncResult(pod *api.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) { // Send the kills in parallel since they may take a long time. @@ -1298,7 +1339,7 @@ func (dm *DockerManager) KillContainerInPod(containerID kubecontainer.ContainerI } storedPod, storedContainer, cerr := containerAndPodFromLabels(inspect) if cerr != nil { - glog.Errorf("unable to access pod data from container: %v", err) + glog.Errorf("unable to access pod data from container: %v", cerr) } if container == nil { container = storedContainer @@ -1344,7 +1385,7 @@ func (dm *DockerManager) killContainer(containerID kubecontainer.ContainerID, co defer utilruntime.HandleCrash() if msg, err := dm.runner.Run(containerID, pod, container, container.Lifecycle.PreStop); err != nil { glog.Errorf("preStop hook for container %q failed: %v", name, err) - dm.generateFailedContainerEvent(containerID, pod.Name, kubecontainer.FailedPreStopHook, msg) + dm.generateFailedContainerEvent(containerID, pod.Name, events.FailedPreStopHook, msg) } }() select { @@ -1384,7 +1425,7 @@ func (dm *DockerManager) killContainer(containerID kubecontainer.ContainerID, co if reason != "" { message = fmt.Sprint(message, ": ", reason) } - dm.recorder.Event(ref, api.EventTypeNormal, kubecontainer.KillingContainer, message) + dm.recorder.Event(ref, api.EventTypeNormal, events.KillingContainer, message) dm.containerRefManager.ClearRef(containerID) } return err @@ -1403,7 +1444,7 @@ var errNoPodOnContainer = fmt.Errorf("no pod information labels on Docker contai // containerAndPodFromLabels tries to load the appropriate container info off of a Docker container's labels func containerAndPodFromLabels(inspect *dockertypes.ContainerJSON) (pod *api.Pod, container *api.Container, err error) { - if inspect == nil && inspect.Config == nil && inspect.Config.Labels == nil { + if inspect == nil || inspect.Config == nil || inspect.Config.Labels == nil { return nil, nil, errNoPodOnContainer } labels := inspect.Config.Labels @@ -1518,7 +1559,7 @@ func (dm *DockerManager) runContainerInPod(pod *api.Pod, container *api.Containe msg, handlerErr := dm.runner.Run(id, pod, container, container.Lifecycle.PostStart) if handlerErr != nil { err := fmt.Errorf("PostStart handler: %v", handlerErr) - dm.generateFailedContainerEvent(id, pod.Name, kubecontainer.FailedPostStartHook, msg) + dm.generateFailedContainerEvent(id, pod.Name, events.FailedPostStartHook, msg) dm.KillContainerInPod(id, container, pod, err.Error(), nil) return kubecontainer.ContainerID{}, err } @@ -1569,7 +1610,7 @@ func (dm *DockerManager) applyOOMScoreAdjIfNeeded(pod *api.Pod, container *api.C // If current api version is older than OOMScoreAdj requested, use the old way. if result < 0 { if err := dm.applyOOMScoreAdj(pod, container, containerInfo); err != nil { - return fmt.Errorf("Failed to apply oom-score-adj to container %q- %v", err, containerInfo.Name) + return fmt.Errorf("Failed to apply oom-score-adj to container %q- %v", containerInfo.Name, err) } } @@ -1684,7 +1725,7 @@ func (dm *DockerManager) createPodInfraContainer(pod *api.Pod) (kubecontainer.Do // No pod secrets for the infra container. // The message isn't needed for the Infra container - if err, msg := dm.imagePuller.PullImage(pod, container, nil); err != nil { + if err, msg := dm.imagePuller.EnsureImageExists(pod, container, nil); err != nil { return "", err, msg } @@ -1761,9 +1802,6 @@ func (dm *DockerManager) computePodContainerChanges(pod *api.Pod, podStatus *kub Containers: for i, container := range pod.Spec.InitContainers { containerStatus := podStatus.FindContainerStatusByName(container.Name) - if containerStatus == nil { - continue - } switch { case containerStatus == nil: continue @@ -1887,11 +1925,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec glog.V(3).Infof("Got container changes for pod %q: %+v", format.Pod(pod), containerChanges) if containerChanges.InfraChanged { - ref, err := api.GetReference(pod) - if err != nil { - glog.Errorf("Couldn't make a ref to pod %q: '%v'", format.Pod(pod), err) - } - dm.recorder.Eventf(ref, api.EventTypeNormal, "InfraChanged", "Pod infrastructure changed, it will be killed and re-created.") + dm.recorder.Eventf(pod, api.EventTypeNormal, "InfraChanged", "Pod infrastructure changed, it will be killed and re-created.") } if containerChanges.StartInfraContainer || (len(containerChanges.ContainersToKeep) == 0 && len(containerChanges.ContainersToStart) == 0) { if len(containerChanges.ContainersToKeep) == 0 && len(containerChanges.ContainersToStart) == 0 { @@ -2004,7 +2038,8 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec } // Overwrite the podIP passed in the pod status, since we just started the infra container. - podIP = dm.determineContainerIP(pod.Name, pod.Namespace, podInfraContainer) + podIP = dm.determineContainerIP(pod.Namespace, pod.Name, podInfraContainer) + glog.V(4).Infof("Determined pod ip after infra change: %q: %q", format.Pod(pod), podIP) } } @@ -2102,7 +2137,7 @@ func (dm *DockerManager) SyncPod(pod *api.Pod, _ api.PodStatus, podStatus *kubec // tryContainerStart attempts to pull and start the container, returning an error and a reason string if the start // was not successful. func (dm *DockerManager) tryContainerStart(container *api.Container, pod *api.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []api.Secret, namespaceMode, pidMode, podIP string) (err error, reason string) { - err, msg := dm.imagePuller.PullImage(pod, container, pullSecrets) + err, msg := dm.imagePuller.EnsureImageExists(pod, container, pullSecrets) if err != nil { return err, msg } @@ -2121,7 +2156,6 @@ func (dm *DockerManager) tryContainerStart(container *api.Container, pod *api.Po restartCount = containerStatus.RestartCount + 1 } - // TODO(dawnchen): Check RestartPolicy.DelaySeconds before restart a container _, err = dm.runContainerInPod(pod, container, namespaceMode, namespaceMode, pidMode, podIP, restartCount) if err != nil { // TODO(bburns) : Perhaps blacklist a container after N failures? @@ -2297,7 +2331,7 @@ func (dm *DockerManager) doBackOff(pod *api.Pod, container *api.Container, podSt stableName, _, _ := BuildDockerName(dockerName, container) if backOff.IsInBackOffSince(stableName, ts) { if ref, err := kubecontainer.GenerateContainerRef(pod, container); err == nil { - dm.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.BackOffStartContainer, "Back-off restarting failed docker container") + dm.recorder.Eventf(ref, api.EventTypeWarning, events.BackOffStartContainer, "Back-off restarting failed docker container") } err := fmt.Errorf("Back-off %s restarting failed container=%s pod=%s", backOff.Get(stableName), container.Name, format.Pod(pod)) glog.Infof("%s", err.Error()) @@ -2326,6 +2360,10 @@ func getIPCMode(pod *api.Pod) string { return ipcMode } +func (dm *DockerManager) DeleteContainer(containerID kubecontainer.ContainerID) error { + return dm.containerGC.deleteContainer(containerID.ID) +} + // GetNetNS returns the network namespace path for the given container func (dm *DockerManager) GetNetNS(containerID kubecontainer.ContainerID) (string, error) { inspectResult, err := dm.client.InspectContainer(containerID.ID) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/exec.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/exec.go index 2568b60b2d4f..ce213650b065 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/exec.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/exec.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,18 +26,19 @@ import ( dockertypes "github.com/docker/engine-api/types" "github.com/golang/glog" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/util/term" ) // ExecHandler knows how to execute a command in a running Docker container. type ExecHandler interface { - ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error + ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error } // NsenterExecHandler executes commands in Docker containers using nsenter. type NsenterExecHandler struct{} // TODO should we support nsenter in a container, running with elevated privs and --pid=host? -func (*NsenterExecHandler) ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (*NsenterExecHandler) ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { nsenter, err := exec.LookPath("nsenter") if err != nil { return fmt.Errorf("exec unavailable - unable to locate nsenter") @@ -61,6 +62,10 @@ func (*NsenterExecHandler) ExecInContainer(client DockerInterface, container *do // make sure to close the stdout stream defer stdout.Close() + kubecontainer.HandleResizing(resize, func(size term.Size) { + term.SetSize(p.Fd(), size) + }) + if stdin != nil { go io.Copy(p, stdin) } @@ -98,7 +103,7 @@ func (*NsenterExecHandler) ExecInContainer(client DockerInterface, container *do // NativeExecHandler executes commands in Docker containers using Docker's exec API. type NativeExecHandler struct{} -func (*NativeExecHandler) ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (*NativeExecHandler) ExecInContainer(client DockerInterface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { createOpts := dockertypes.ExecConfig{ Cmd: cmd, AttachStdin: stdin != nil, @@ -110,6 +115,13 @@ func (*NativeExecHandler) ExecInContainer(client DockerInterface, container *doc if err != nil { return fmt.Errorf("failed to exec in container - Exec setup failed - %v", err) } + + // Have to start this before the call to client.StartExec because client.StartExec is a blocking + // call :-( Otherwise, resize events don't get processed and the terminal never resizes. + kubecontainer.HandleResizing(resize, func(size term.Size) { + client.ResizeExecTTY(execObj.ID, int(size.Height), int(size.Width)) + }) + startOpts := dockertypes.ExecStartCheck{Detach: false, Tty: tty} streamOpts := StreamOptions{ InputStream: stdin, @@ -121,6 +133,7 @@ func (*NativeExecHandler) ExecInContainer(client DockerInterface, container *doc if err != nil { return err } + ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() count := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_docker_client.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_docker_client.go index 4d799972fce6..822c570dc1cf 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_docker_client.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_docker_client.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -507,6 +507,20 @@ func (f *FakeDockerClient) updateContainerStatus(id, status string) { } } +func (f *FakeDockerClient) ResizeExecTTY(id string, height, width int) error { + f.Lock() + defer f.Unlock() + f.called = append(f.called, calledDetail{name: "resize_exec"}) + return nil +} + +func (f *FakeDockerClient) ResizeContainerTTY(id string, height, width int) error { + f.Lock() + defer f.Unlock() + f.called = append(f.called, calledDetail{name: "resize_container"}) + return nil +} + // FakeDockerPuller is a stub implementation of DockerPuller. type FakeDockerPuller struct { sync.Mutex diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_manager.go index 38c801e35a8d..1bb5cf59b823 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/fake_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/images.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/images.go index 6f7be9e0eb2b..e87c30fcf819 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/images.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/images.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/instrumented_docker.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/instrumented_docker.go index 36e3fdd637c1..eb15226498a7 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/instrumented_docker.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/instrumented_docker.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ type instrumentedDockerInterface struct { } // Creates an instrumented DockerInterface from an existing DockerInterface. -func newInstrumentedDockerInterface(dockerClient DockerInterface) DockerInterface { +func NewInstrumentedDockerInterface(dockerClient DockerInterface) DockerInterface { return instrumentedDockerInterface{ client: dockerClient, } @@ -213,3 +213,21 @@ func (in instrumentedDockerInterface) ImageHistory(id string) ([]dockertypes.Ima recordError(operation, err) return out, err } + +func (in instrumentedDockerInterface) ResizeExecTTY(id string, height, width int) error { + const operation = "resize_exec" + defer recordOperation(operation, time.Now()) + + err := in.client.ResizeExecTTY(id, height, width) + recordError(operation, err) + return err +} + +func (in instrumentedDockerInterface) ResizeContainerTTY(id string, height, width int) error { + const operation = "resize_container" + defer recordOperation(operation, time.Now()) + + err := in.client.ResizeContainerTTY(id, height, width) + recordError(operation, err) + return err +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/kube_docker_client.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/kube_docker_client.go index d390eff1081d..9b31b4b6e5be 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/kube_docker_client.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/kube_docker_client.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -454,6 +454,24 @@ func (d *kubeDockerClient) AttachToContainer(id string, opts dockertypes.Contain return d.holdHijackedConnection(sopts.RawTerminal, sopts.InputStream, sopts.OutputStream, sopts.ErrorStream, resp) } +func (d *kubeDockerClient) ResizeExecTTY(id string, height, width int) error { + ctx, cancel := d.getCancelableContext() + defer cancel() + return d.client.ContainerExecResize(ctx, id, dockertypes.ResizeOptions{ + Height: height, + Width: width, + }) +} + +func (d *kubeDockerClient) ResizeContainerTTY(id string, height, width int) error { + ctx, cancel := d.getCancelableContext() + defer cancel() + return d.client.ContainerResize(ctx, id, dockertypes.ResizeOptions{ + Height: height, + Width: width, + }) +} + // redirectResponseToOutputStream redirect the response stream to stdout and stderr. When tty is true, all stream will // only be redirected to stdout. func (d *kubeDockerClient) redirectResponseToOutputStream(tty bool, outputStream, errorStream io.Writer, resp io.Reader) error { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/labels.go b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/labels.go index 9d2bd68b50dd..8e9e0dadd45e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/labels.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/dockertools/labels.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/doc.go index 22f57e80a885..42fea62f2204 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/envvars.go b/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/envvars.go index 31e82eb781b4..186a0a87c817 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/envvars.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/envvars/envvars.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/event.go b/vendor/k8s.io/kubernetes/pkg/kubelet/events/event.go similarity index 96% rename from vendor/k8s.io/kubernetes/pkg/kubelet/container/event.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/events/event.go index 949dfcccc0e7..2db0419d6086 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/event.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/events/event.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package container +package events const ( // Container event reason list diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/doc.go index d46bb277968d..1395301680d8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/eviction_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/eviction_manager.go index a672ebb9b887..adb4ee85bd43 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/eviction_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/eviction_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,17 +25,17 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/kubelet/lifecycle" - qosutil "k8s.io/kubernetes/pkg/kubelet/qos/util" + "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/kubelet/server/stats" "k8s.io/kubernetes/pkg/kubelet/util/format" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/wait" ) // managerImpl implements NodeStabilityManager type managerImpl struct { // used to track time - clock util.Clock + clock clock.Clock // config is how the manager is configured config Config // the function to invoke to kill a pod @@ -54,6 +54,8 @@ type managerImpl struct { summaryProvider stats.SummaryProvider // records when a threshold was first observed thresholdsFirstObservedAt thresholdsObservedAt + // resourceToRankFunc maps a resource to ranking function for that resource. + resourceToRankFunc map[api.ResourceName]rankFunc } // ensure it implements the required interface @@ -66,7 +68,7 @@ func NewManager( killPodFunc KillPodFunc, recorder record.EventRecorder, nodeRef *api.ObjectReference, - clock util.Clock) (Manager, lifecycle.PodAdmitHandler, error) { + clock clock.Clock) (Manager, lifecycle.PodAdmitHandler, error) { manager := &managerImpl{ clock: clock, killPodFunc: killPodFunc, @@ -87,12 +89,17 @@ func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAd if len(m.nodeConditions) == 0 { return lifecycle.PodAdmitResult{Admit: true} } - notBestEffort := qosutil.BestEffort != qosutil.GetPodQos(attrs.Pod) - if notBestEffort { - return lifecycle.PodAdmitResult{Admit: true} + + // the node has memory pressure, admit if not best-effort + if hasNodeCondition(m.nodeConditions, api.NodeMemoryPressure) { + notBestEffort := qos.BestEffort != qos.GetPodQOS(attrs.Pod) + if notBestEffort { + return lifecycle.PodAdmitResult{Admit: true} + } } + + // reject pods when under memory pressure (if pod is best effort), or if under disk pressure. glog.Warningf("Failed to admit pod %v - %s", format.Pod(attrs.Pod), "node has conditions: %v", m.nodeConditions) - // we reject all best effort pods until we are stable. return lifecycle.PodAdmitResult{ Admit: false, Reason: reason, @@ -101,8 +108,10 @@ func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAd } // Start starts the control loop to observe and response to low compute resources. -func (m *managerImpl) Start(podFunc ActivePodsFunc, monitoringInterval time.Duration) { - go wait.Until(func() { m.synchronize(podFunc) }, monitoringInterval, wait.NeverStop) +func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, monitoringInterval time.Duration) error { + // start the eviction manager monitoring + go wait.Until(func() { m.synchronize(diskInfoProvider, podFunc) }, monitoringInterval, wait.NeverStop) + return nil } // IsUnderMemoryPressure returns true if the node is under memory pressure. @@ -112,14 +121,32 @@ func (m *managerImpl) IsUnderMemoryPressure() bool { return hasNodeCondition(m.nodeConditions, api.NodeMemoryPressure) } +// IsUnderDiskPressure returns true if the node is under disk pressure. +func (m *managerImpl) IsUnderDiskPressure() bool { + m.RLock() + defer m.RUnlock() + return hasNodeCondition(m.nodeConditions, api.NodeDiskPressure) +} + // synchronize is the main control loop that enforces eviction thresholds. -func (m *managerImpl) synchronize(podFunc ActivePodsFunc) { +func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc) { // if we have nothing to do, just return thresholds := m.config.Thresholds if len(thresholds) == 0 { return } + // build the ranking functions (if not yet known) + // TODO: have a function in cadvisor that lets us know if global housekeeping has completed + if len(m.resourceToRankFunc) == 0 { + // this may error if cadvisor has yet to complete housekeeping, so we will just try again in next pass. + hasDedicatedImageFs, err := diskInfoProvider.HasDedicatedImageFs() + if err != nil { + return + } + m.resourceToRankFunc = buildResourceToRankFunc(hasDedicatedImageFs) + } + // make observations and get a function to derive pod usage stats relative to those observations. observations, statsFunc, err := makeSignalObservations(m.summaryProvider) if err != nil { @@ -174,7 +201,7 @@ func (m *managerImpl) synchronize(podFunc ActivePodsFunc) { m.recorder.Eventf(m.nodeRef, api.EventTypeWarning, "EvictionThresholdMet", "Attempting to reclaim %s", resourceToReclaim) // rank the pods for eviction - rank, ok := resourceToRankFunc[resourceToReclaim] + rank, ok := m.resourceToRankFunc[resourceToReclaim] if !ok { glog.Errorf("eviction manager: no ranking function for resource %s", resourceToReclaim) return diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/helpers.go b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/helpers.go index d5b95ab19755..ea6911240d23 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/helpers.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/helpers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" statsapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats" - qosutil "k8s.io/kubernetes/pkg/kubelet/qos/util" + "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/kubelet/server/stats" "k8s.io/kubernetes/pkg/quota/evaluator/core" "k8s.io/kubernetes/pkg/util/sets" @@ -41,21 +41,24 @@ const ( message = "The node was low on compute resources." // disk, in bytes. internal to this module, used to account for local disk usage. resourceDisk api.ResourceName = "disk" + // imagefs, in bytes. internal to this module, used to account for local image filesystem usage. + resourceImageFs api.ResourceName = "imagefs" + // nodefs, in bytes. internal to this module, used to account for local node root filesystem usage. + resourceNodeFs api.ResourceName = "nodefs" ) -// resourceToRankFunc maps a resource to ranking function for that resource. -var resourceToRankFunc = map[api.ResourceName]rankFunc{ - api.ResourceMemory: rankMemoryPressure, -} - // signalToNodeCondition maps a signal to the node condition to report if threshold is met. var signalToNodeCondition = map[Signal]api.NodeConditionType{ - SignalMemoryAvailable: api.NodeMemoryPressure, + SignalMemoryAvailable: api.NodeMemoryPressure, + SignalImageFsAvailable: api.NodeDiskPressure, + SignalNodeFsAvailable: api.NodeDiskPressure, } // signalToResource maps a Signal to its associated Resource. var signalToResource = map[Signal]api.ResourceName{ - SignalMemoryAvailable: api.ResourceMemory, + SignalMemoryAvailable: api.ResourceMemory, + SignalImageFsAvailable: resourceImageFs, + SignalNodeFsAvailable: resourceNodeFs, } // validSignal returns true if the signal is supported. @@ -65,7 +68,7 @@ func validSignal(signal Signal) bool { } // ParseThresholdConfig parses the flags for thresholds. -func ParseThresholdConfig(evictionHard, evictionSoft, evictionSoftGracePeriod string) ([]Threshold, error) { +func ParseThresholdConfig(evictionHard, evictionSoft, evictionSoftGracePeriod, evictionMinimumReclaim string) ([]Threshold, error) { results := []Threshold{} hardThresholds, err := parseThresholdStatements(evictionHard) @@ -82,6 +85,10 @@ func ParseThresholdConfig(evictionHard, evictionSoft, evictionSoftGracePeriod st if err != nil { return nil, err } + minReclaims, err := parseMinimumReclaims(evictionMinimumReclaim) + if err != nil { + return nil, err + } for i := range softThresholds { signal := softThresholds[i].Signal period, found := gracePeriods[signal] @@ -91,6 +98,14 @@ func ParseThresholdConfig(evictionHard, evictionSoft, evictionSoftGracePeriod st softThresholds[i].GracePeriod = period } results = append(results, softThresholds...) + for i := range results { + for signal, minReclaim := range minReclaims { + if results[i].Signal == signal { + results[i].MinReclaim = &minReclaim + break + } + } + } return results, nil } @@ -145,6 +160,9 @@ func parseThresholdStatement(statement string) (Threshold, error) { if err != nil { return Threshold{}, err } + if quantity.Sign() < 0 { + return Threshold{}, fmt.Errorf("eviction threshold %v cannot be negative: %s", signal, &quantity) + } return Threshold{ Signal: signal, Operator: operator, @@ -186,6 +204,38 @@ func parseGracePeriods(expr string) (map[Signal]time.Duration, error) { return results, nil } +// parseMinimumReclaims parses the minimum reclaim statements +func parseMinimumReclaims(expr string) (map[Signal]resource.Quantity, error) { + if len(expr) == 0 { + return nil, nil + } + results := map[Signal]resource.Quantity{} + statements := strings.Split(expr, ",") + for _, statement := range statements { + parts := strings.Split(statement, "=") + if len(parts) != 2 { + return nil, fmt.Errorf("invalid eviction minimum reclaim syntax: %v, expected =", statement) + } + signal := Signal(parts[0]) + if !validSignal(signal) { + return nil, fmt.Errorf(unsupportedEvictionSignal, signal) + } + // check against duplicate statements + if _, found := results[signal]; found { + return nil, fmt.Errorf("duplicate eviction minimum reclaim specified for %v", signal) + } + quantity, err := resource.ParseQuantity(parts[1]) + if quantity.Sign() < 0 { + return nil, fmt.Errorf("negative eviction minimum reclaim specified for %v", signal) + } + if err != nil { + return nil, err + } + results[signal] = quantity + } + return results, nil +} + // diskUsage converts used bytes into a resource quantity. func diskUsage(fsStats *statsapi.FsStats) *resource.Quantity { if fsStats == nil || fsStats.UsedBytes == nil { @@ -204,14 +254,54 @@ func memoryUsage(memStats *statsapi.MemoryStats) *resource.Quantity { return resource.NewQuantity(usage, resource.BinarySI) } -// podUsage aggregates usage of compute resources. -// it supports the following memory and disk. -func podUsage(podStats statsapi.PodStats) (api.ResourceList, error) { +// localVolumeNames returns the set of volumes for the pod that are local +// TODO: sumamry API should report what volumes consume local storage rather than hard-code here. +func localVolumeNames(pod *api.Pod) []string { + result := []string{} + for _, volume := range pod.Spec.Volumes { + if volume.HostPath != nil || + (volume.EmptyDir != nil && volume.EmptyDir.Medium != api.StorageMediumMemory) || + volume.ConfigMap != nil || + volume.GitRepo != nil { + result = append(result, volume.Name) + } + } + return result +} + +// podDiskUsage aggregates pod disk usage for the specified stats to measure. +func podDiskUsage(podStats statsapi.PodStats, pod *api.Pod, statsToMeasure []fsStatsType) (api.ResourceList, error) { + disk := resource.Quantity{Format: resource.BinarySI} + for _, container := range podStats.Containers { + if hasFsStatsType(statsToMeasure, fsStatsRoot) { + disk.Add(*diskUsage(container.Rootfs)) + } + if hasFsStatsType(statsToMeasure, fsStatsLogs) { + disk.Add(*diskUsage(container.Logs)) + } + } + if hasFsStatsType(statsToMeasure, fsStatsLocalVolumeSource) { + volumeNames := localVolumeNames(pod) + for _, volumeName := range volumeNames { + for _, volumeStats := range podStats.VolumeStats { + if volumeStats.Name == volumeName { + disk.Add(*diskUsage(&volumeStats.FsStats)) + break + } + } + } + } + return api.ResourceList{ + resourceDisk: disk, + }, nil +} + +// podMemoryUsage aggregates pod memory usage. +func podMemoryUsage(podStats statsapi.PodStats) (api.ResourceList, error) { disk := resource.Quantity{Format: resource.BinarySI} memory := resource.Quantity{Format: resource.BinarySI} for _, container := range podStats.Containers { // disk usage (if known) - // TODO: need to handle volumes for _, fsStats := range []*statsapi.FsStats{container.Rootfs, container.Logs} { disk.Add(*diskUsage(fsStats)) } @@ -299,21 +389,21 @@ func (ms *multiSorter) Less(i, j int) bool { return ms.cmp[k](p1, p2) < 0 } -// qos compares pods by QoS (BestEffort < Burstable < Guaranteed) -func qos(p1, p2 *api.Pod) int { - qosP1 := qosutil.GetPodQos(p1) - qosP2 := qosutil.GetPodQos(p2) +// qosComparator compares pods by QoS (BestEffort < Burstable < Guaranteed) +func qosComparator(p1, p2 *api.Pod) int { + qosP1 := qos.GetPodQOS(p1) + qosP2 := qos.GetPodQOS(p2) // its a tie if qosP1 == qosP2 { return 0 } // if p1 is best effort, we know p2 is burstable or guaranteed - if qosP1 == qosutil.BestEffort { + if qosP1 == qos.BestEffort { return -1 } // we know p1 and p2 are not besteffort, so if p1 is burstable, p2 must be guaranteed - if qosP1 == qosutil.Burstable { - if qosP2 == qosutil.Guaranteed { + if qosP1 == qos.Burstable { + if qosP2 == qos.Guaranteed { return -1 } return 1 @@ -336,12 +426,12 @@ func memory(stats statsFunc) cmpFunc { return 1 } // if we cant get usage for p1 measured, we want p2 first - p1Usage, err := podUsage(p1Stats) + p1Usage, err := podMemoryUsage(p1Stats) if err != nil { return -1 } // if we cant get usage for p2 measured, we want p1 first - p2Usage, err := podUsage(p2Stats) + p2Usage, err := podMemoryUsage(p2Stats) if err != nil { return 1 } @@ -363,7 +453,7 @@ func memory(stats statsFunc) cmpFunc { } // disk compares pods by largest consumer of disk relative to request. -func disk(stats statsFunc) cmpFunc { +func disk(stats statsFunc, fsStatsToMeasure []fsStatsType) cmpFunc { return func(p1, p2 *api.Pod) int { p1Stats, found := stats(p1) // if we have no usage stats for p1, we want p2 first @@ -376,20 +466,20 @@ func disk(stats statsFunc) cmpFunc { return 1 } // if we cant get usage for p1 measured, we want p2 first - p1Usage, err := podUsage(p1Stats) + p1Usage, err := podDiskUsage(p1Stats, p1, fsStatsToMeasure) if err != nil { return -1 } // if we cant get usage for p2 measured, we want p1 first - p2Usage, err := podUsage(p2Stats) + p2Usage, err := podDiskUsage(p2Stats, p2, fsStatsToMeasure) if err != nil { return 1 } // disk is best effort, so we don't measure relative to a request. // TODO: add disk as a guaranteed resource - p1Disk := p1Usage[api.ResourceStorage] - p2Disk := p2Usage[api.ResourceStorage] + p1Disk := p1Usage[resourceDisk] + p2Disk := p2Usage[resourceDisk] // if p2 is using more than p1, we want p2 first return p2Disk.Cmp(p1Disk) } @@ -397,12 +487,14 @@ func disk(stats statsFunc) cmpFunc { // rankMemoryPressure orders the input pods for eviction in response to memory pressure. func rankMemoryPressure(pods []*api.Pod, stats statsFunc) { - orderedBy(qos, memory(stats)).Sort(pods) + orderedBy(qosComparator, memory(stats)).Sort(pods) } -// rankDiskPressure orders the input pods for eviction in response to disk pressure. -func rankDiskPressure(pods []*api.Pod, stats statsFunc) { - orderedBy(qos, disk(stats)).Sort(pods) +// rankDiskPressureFunc returns a rankFunc that measures the specified fs stats. +func rankDiskPressureFunc(fsStatsToMeasure []fsStatsType) rankFunc { + return func(pods []*api.Pod, stats statsFunc) { + orderedBy(qosComparator, disk(stats, fsStatsToMeasure)).Sort(pods) + } } // byEvictionPriority implements sort.Interface for []api.ResourceName. @@ -426,7 +518,18 @@ func makeSignalObservations(summaryProvider stats.SummaryProvider) (signalObserv statsFunc := cachedStatsFunc(summary.Pods) // build an evaluation context for current eviction signals result := signalObservations{} - result[SignalMemoryAvailable] = resource.NewQuantity(int64(*summary.Node.Memory.AvailableBytes), resource.BinarySI) + + if memory := summary.Node.Memory; memory != nil && memory.AvailableBytes != nil { + result[SignalMemoryAvailable] = resource.NewQuantity(int64(*memory.AvailableBytes), resource.BinarySI) + } + if nodeFs := summary.Node.Fs; nodeFs != nil && nodeFs.AvailableBytes != nil { + result[SignalNodeFsAvailable] = resource.NewQuantity(int64(*nodeFs.AvailableBytes), resource.BinarySI) + } + if summary.Node.Runtime != nil { + if imageFs := summary.Node.Runtime.ImageFs; imageFs != nil && imageFs.AvailableBytes != nil { + result[SignalImageFsAvailable] = resource.NewQuantity(int64(*imageFs.AvailableBytes), resource.BinarySI) + } + } return result, statsFunc, nil } @@ -521,6 +624,16 @@ func nodeConditionsObservedSince(observedAt nodeConditionsObservedAt, period tim return results } +// hasFsStatsType returns true if the fsStat is in the input list +func hasFsStatsType(inputs []fsStatsType, item fsStatsType) bool { + for _, input := range inputs { + if input == item { + return true + } + } + return false +} + // hasNodeCondition returns true if the node condition is in the input list func hasNodeCondition(inputs []api.NodeConditionType, item api.NodeConditionType) bool { for _, input := range inputs { @@ -564,3 +677,21 @@ func isSoftEviction(thresholds []Threshold, starvedResource api.ResourceName) bo } return true } + +// buildResourceToRankFunc returns ranking functions associated with resources +func buildResourceToRankFunc(withImageFs bool) map[api.ResourceName]rankFunc { + resourceToRankFunc := map[api.ResourceName]rankFunc{ + api.ResourceMemory: rankMemoryPressure, + } + // usage of an imagefs is optional + if withImageFs { + // with an imagefs, nodefs pod rank func for eviction only includes logs and local volumes + resourceToRankFunc[resourceNodeFs] = rankDiskPressureFunc([]fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource}) + // with an imagefs, imagefs pod rank func for eviction only includes rootfs + resourceToRankFunc[resourceImageFs] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot}) + } else { + // without an imagefs, nodefs pod rank func for eviction looks at all fs stats + resourceToRankFunc[resourceNodeFs] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}) + } + return resourceToRankFunc +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/types.go index 3b4470d7c7b4..053c47809da8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/types.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,6 +30,22 @@ type Signal string const ( // SignalMemoryAvailable is memory available (i.e. capacity - workingSet), in bytes. SignalMemoryAvailable Signal = "memory.available" + // SignalNodeFsAvailable is amount of storage available on filesystem that kubelet uses for volumes, daemon logs, etc. + SignalNodeFsAvailable Signal = "nodefs.available" + // SignalImageFsAvailable is amount of storage available on filesystem that container runtime uses for for storing images and container writable layers. + SignalImageFsAvailable Signal = "imagefs.available" +) + +// fsStatsType defines the types of filesystem stats to collect. +type fsStatsType string + +const ( + // fsStatsLocalVolumeSource identifies stats for pod local volume sources. + fsStatsLocalVolumeSource fsStatsType = "localVolumeSource" + // fsStatsLogs identifies stats for pod logs. + fsStatsLogs fsStatsType = "logs" + // fsStatsRoot identifies stats for pod container writable layers. + fsStatsRoot fsStatsType = "root" ) // ThresholdOperator is the operator used to express a Threshold. @@ -60,15 +76,26 @@ type Threshold struct { Value *resource.Quantity // GracePeriod represents the amount of time that a threshold must be met before eviction is triggered. GracePeriod time.Duration + // MinReclaim represents the minimum amount of resource to reclaim if the threshold is met. + MinReclaim *resource.Quantity } // Manager evaluates when an eviction threshold for node stability has been met on the node. type Manager interface { // Start starts the control loop to monitor eviction thresholds at specified interval. - Start(podFunc ActivePodsFunc, monitoringInterval time.Duration) + Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, monitoringInterval time.Duration) error // IsUnderMemoryPressure returns true if the node is under memory pressure. IsUnderMemoryPressure() bool + + // IsUnderDiskPressure returns true if the node is under disk pressure. + IsUnderDiskPressure() bool +} + +// DiskInfoProvider is responsible for informing the manager how disk is configured. +type DiskInfoProvider interface { + // HasDedicatedImageFs returns true if the imagefs is on a separate device from the rootfs. + HasDedicatedImageFs() (bool, error) } // KillPodFunc kills a pod. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/flannel_helper.go b/vendor/k8s.io/kubernetes/pkg/kubelet/flannel_helper.go index c81cb594fec8..eb61e81ed9bd 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/flannel_helper.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/flannel_helper.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/image_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/image_manager.go index 9fd4780ff251..7d21892dd368 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/image_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/image_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package kubelet import ( "fmt" + "math" "sort" "sync" "time" @@ -28,6 +29,8 @@ import ( "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/container" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" + "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" ) @@ -45,6 +48,9 @@ type imageManager interface { GetImageList() ([]kubecontainer.Image, error) + // Delete all unused images and returns the number of bytes freed. The number of bytes freed is always returned. + DeleteUnusedImages() (int64, error) + // TODO(vmarmol): Have this subsume pulls as well. } @@ -164,8 +170,8 @@ func (im *realImageManager) detectImages(detectTime time.Time) error { imagesInUse := sets.NewString() for _, pod := range pods { for _, container := range pod.Containers { - glog.V(5).Infof("Pod %s/%s, container %s uses image %s", pod.Namespace, pod.Name, container.Name, container.Image) - imagesInUse.Insert(container.Image) + glog.V(5).Infof("Pod %s/%s, container %s uses image %s(%s)", pod.Namespace, pod.Name, container.Name, container.Image, container.ImageID) + imagesInUse.Insert(container.ImageID) } } @@ -223,7 +229,7 @@ func (im *realImageManager) GarbageCollect() error { // Check valid capacity. if capacity == 0 { err := fmt.Errorf("invalid capacity %d on device %q at mount point %q", capacity, fsInfo.Device, fsInfo.Mountpoint) - im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, container.InvalidDiskCapacity, err.Error()) + im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, events.InvalidDiskCapacity, err.Error()) return err } @@ -239,7 +245,7 @@ func (im *realImageManager) GarbageCollect() error { if freed < amountToFree { err := fmt.Errorf("failed to garbage collect required amount of images. Wanted to free %d, but freed %d", amountToFree, freed) - im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, container.FreeDiskSpaceFailed, err.Error()) + im.recorder.Eventf(im.nodeRef, api.EventTypeWarning, events.FreeDiskSpaceFailed, err.Error()) return err } } @@ -247,6 +253,10 @@ func (im *realImageManager) GarbageCollect() error { return nil } +func (im *realImageManager) DeleteUnusedImages() (int64, error) { + return im.freeSpace(math.MaxInt64, time.Now()) +} + // Tries to free bytesToFree worth of images on the disk. // // Returns the number of bytes free and an error if any occurred. The number of @@ -273,7 +283,7 @@ func (im *realImageManager) freeSpace(bytesToFree int64, freeTime time.Time) (in sort.Sort(byLastUsedAndDetected(images)) // Delete unused images until we've freed up enough space. - var lastErr error + var deletionErrors []error spaceFreed := int64(0) for _, image := range images { glog.V(5).Infof("Evaluating image ID %s for possible garbage collection", image.id) @@ -295,7 +305,7 @@ func (im *realImageManager) freeSpace(bytesToFree int64, freeTime time.Time) (in glog.Infof("[ImageManager]: Removing image %q to free %d bytes", image.id, image.size) err := im.runtime.RemoveImage(container.ImageSpec{Image: image.id}) if err != nil { - lastErr = err + deletionErrors = append(deletionErrors, err) continue } delete(im.imageRecords, image.id) @@ -306,7 +316,10 @@ func (im *realImageManager) freeSpace(bytesToFree int64, freeTime time.Time) (in } } - return spaceFreed, lastErr + if len(deletionErrors) > 0 { + return spaceFreed, fmt.Errorf("wanted to free %d, but freed %d space with errors in image deletion: %v", bytesToFree, spaceFreed, errors.NewAggregate(deletionErrors)) + } + return spaceFreed, nil } type evictionInfo struct { @@ -328,14 +341,9 @@ func (ev byLastUsedAndDetected) Less(i, j int) bool { } func isImageUsed(image container.Image, imagesInUse sets.String) bool { - // Check the image ID and all the RepoTags and RepoDigests. + // Check the image ID. if _, ok := imagesInUse[image.ID]; ok { return true } - for _, tag := range append(image.RepoTags, image.RepoDigests...) { - if _, ok := imagesInUse[tag]; ok { - return true - } - } return false } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/images/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/images/doc.go new file mode 100644 index 000000000000..9ccecb6b7a7e --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/images/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2016 The Kubernetes 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 images is responsible for managing lifecycle of container images. +package images diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/images/impl.go b/vendor/k8s.io/kubernetes/pkg/kubelet/images/impl.go new file mode 100644 index 000000000000..4a00a2e36f89 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/images/impl.go @@ -0,0 +1,52 @@ +/* +Copyright 2016 The Kubernetes 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 images + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/record" + kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/util/flowcontrol" +) + +type imageManager struct { + recorder record.EventRecorder + runtime kubecontainer.Runtime + backOff *flowcontrol.Backoff + imagePuller imagePuller +} + +var _ ImageManager = &imageManager{} + +func NewImageManager(recorder record.EventRecorder, runtime kubecontainer.Runtime, imageBackOff *flowcontrol.Backoff, serialized bool) ImageManager { + var imagePuller imagePuller + if serialized { + imagePuller = newSerializedImagePuller(recorder, runtime, imageBackOff) + } else { + imagePuller = newParallelImagePuller(recorder, runtime, imageBackOff) + } + return &imageManager{ + recorder: recorder, + runtime: runtime, + backOff: imageBackOff, + imagePuller: imagePuller, + } +} + +func (im *imageManager) EnsureImageExists(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { + return im.imagePuller.pullImage(pod, container, pullSecrets) +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/image_puller.go b/vendor/k8s.io/kubernetes/pkg/kubelet/images/parallel_image_puller.go similarity index 65% rename from vendor/k8s.io/kubernetes/pkg/kubelet/container/image_puller.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/images/parallel_image_puller.go index 60f6ee4a2408..09fd47a04f81 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/image_puller.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/images/parallel_image_puller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package container +package images import ( "fmt" @@ -22,25 +22,27 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/record" + kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/util/flowcontrol" ) // imagePuller pulls the image using Runtime.PullImage(). // It will check the presence of the image, and report the 'image pulling', // 'image pulled' events correspondingly. -type imagePuller struct { +type parallelImagePuller struct { recorder record.EventRecorder - runtime Runtime + runtime kubecontainer.Runtime backOff *flowcontrol.Backoff } // enforce compatibility. -var _ ImagePuller = &imagePuller{} +var _ imagePuller = ¶llelImagePuller{} // NewImagePuller takes an event recorder and container runtime to create a // image puller that wraps the container runtime's PullImage interface. -func NewImagePuller(recorder record.EventRecorder, runtime Runtime, imageBackOff *flowcontrol.Backoff) ImagePuller { - return &imagePuller{ +func newParallelImagePuller(recorder record.EventRecorder, runtime kubecontainer.Runtime, imageBackOff *flowcontrol.Backoff) imagePuller { + return ¶llelImagePuller{ recorder: recorder, runtime: runtime, backOff: imageBackOff, @@ -63,7 +65,7 @@ func shouldPullImage(container *api.Container, imagePresent bool) bool { } // records an event using ref, event msg. log to glog using prefix, msg, logFn -func (puller *imagePuller) logIt(ref *api.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) { +func (puller *parallelImagePuller) logIt(ref *api.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) { if ref != nil { puller.recorder.Event(ref, eventtype, event, msg) } else { @@ -72,29 +74,29 @@ func (puller *imagePuller) logIt(ref *api.ObjectReference, eventtype, event, pre } // PullImage pulls the image for the specified pod and container. -func (puller *imagePuller) PullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { +func (puller *parallelImagePuller) pullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { logPrefix := fmt.Sprintf("%s/%s", pod.Name, container.Image) - ref, err := GenerateContainerRef(pod, container) + ref, err := kubecontainer.GenerateContainerRef(pod, container) if err != nil { glog.Errorf("Couldn't make a ref to pod %v, container %v: '%v'", pod.Name, container.Name, err) } - spec := ImageSpec{container.Image} + spec := kubecontainer.ImageSpec{Image: container.Image} present, err := puller.runtime.IsImagePresent(spec) if err != nil { msg := fmt.Sprintf("Failed to inspect image %q: %v", container.Image, err) - puller.logIt(ref, api.EventTypeWarning, FailedToInspectImage, logPrefix, msg, glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) return ErrImageInspect, msg } if !shouldPullImage(container, present) { if present { msg := fmt.Sprintf("Container image %q already present on machine", container.Image) - puller.logIt(ref, api.EventTypeNormal, PulledImage, logPrefix, msg, glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, msg, glog.Info) return nil, "" } else { msg := fmt.Sprintf("Container image %q is not present with pull policy of Never", container.Image) - puller.logIt(ref, api.EventTypeWarning, ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) return ErrImageNeverPull, msg } } @@ -102,12 +104,12 @@ func (puller *imagePuller) PullImage(pod *api.Pod, container *api.Container, pul backOffKey := fmt.Sprintf("%s_%s", pod.UID, container.Image) if puller.backOff.IsInBackOffSinceUpdate(backOffKey, puller.backOff.Clock.Now()) { msg := fmt.Sprintf("Back-off pulling image %q", container.Image) - puller.logIt(ref, api.EventTypeNormal, BackOffPullImage, logPrefix, msg, glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, glog.Info) return ErrImagePullBackOff, msg } - puller.logIt(ref, api.EventTypeNormal, PullingImage, logPrefix, fmt.Sprintf("pulling image %q", container.Image), glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf("pulling image %q", container.Image), glog.Info) if err := puller.runtime.PullImage(spec, pullSecrets); err != nil { - puller.logIt(ref, api.EventTypeWarning, FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) puller.backOff.Next(backOffKey, puller.backOff.Clock.Now()) if err == RegistryUnavailable { msg := fmt.Sprintf("image pull failed for %s because the registry is unavailable.", container.Image) @@ -116,8 +118,7 @@ func (puller *imagePuller) PullImage(pod *api.Pod, container *api.Container, pul return ErrImagePull, err.Error() } } - puller.logIt(ref, api.EventTypeNormal, PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) - puller.backOff.DeleteEntry(backOffKey) + puller.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) puller.backOff.GC() return nil, "" } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/serialized_image_puller.go b/vendor/k8s.io/kubernetes/pkg/kubelet/images/serialized_image_puller.go similarity index 72% rename from vendor/k8s.io/kubernetes/pkg/kubelet/container/serialized_image_puller.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/images/serialized_image_puller.go index 3b5c4689f549..b08c43fefb5a 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/serialized_image_puller.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/images/serialized_image_puller.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package container +package images import ( "fmt" @@ -23,12 +23,14 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/record" + kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/util/flowcontrol" "k8s.io/kubernetes/pkg/util/wait" ) type imagePullRequest struct { - spec ImageSpec + spec kubecontainer.ImageSpec container *api.Container pullSecrets []api.Secret logPrefix string @@ -41,19 +43,19 @@ type imagePullRequest struct { // 'image pulled' events correspondingly. type serializedImagePuller struct { recorder record.EventRecorder - runtime Runtime + runtime kubecontainer.Runtime backOff *flowcontrol.Backoff pullRequests chan *imagePullRequest } // enforce compatibility. -var _ ImagePuller = &serializedImagePuller{} +var _ imagePuller = &serializedImagePuller{} // NewSerializedImagePuller takes an event recorder and container runtime to create a // image puller that wraps the container runtime's PullImage interface. // Pulls one image at a time. // Issue #10959 has the rationale behind serializing image pulls. -func NewSerializedImagePuller(recorder record.EventRecorder, runtime Runtime, imageBackOff *flowcontrol.Backoff) ImagePuller { +func newSerializedImagePuller(recorder record.EventRecorder, runtime kubecontainer.Runtime, imageBackOff *flowcontrol.Backoff) imagePuller { imagePuller := &serializedImagePuller{ recorder: recorder, runtime: runtime, @@ -74,37 +76,37 @@ func (puller *serializedImagePuller) logIt(ref *api.ObjectReference, eventtype, } // PullImage pulls the image for the specified pod and container. -func (puller *serializedImagePuller) PullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { +func (puller *serializedImagePuller) pullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) { logPrefix := fmt.Sprintf("%s/%s", pod.Name, container.Image) - ref, err := GenerateContainerRef(pod, container) + ref, err := kubecontainer.GenerateContainerRef(pod, container) if err != nil { glog.Errorf("Couldn't make a ref to pod %v, container %v: '%v'", pod.Name, container.Name, err) } - spec := ImageSpec{container.Image} + spec := kubecontainer.ImageSpec{Image: container.Image} present, err := puller.runtime.IsImagePresent(spec) if err != nil { msg := fmt.Sprintf("Failed to inspect image %q: %v", container.Image, err) - puller.logIt(ref, api.EventTypeWarning, FailedToInspectImage, logPrefix, msg, glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, glog.Warning) return ErrImageInspect, msg } if !shouldPullImage(container, present) { if present { msg := fmt.Sprintf("Container image %q already present on machine", container.Image) - puller.logIt(ref, api.EventTypeNormal, PulledImage, logPrefix, msg, glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, msg, glog.Info) return nil, "" } else { msg := fmt.Sprintf("Container image %q is not present with pull policy of Never", container.Image) - puller.logIt(ref, api.EventTypeWarning, ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, glog.Warning) return ErrImageNeverPull, msg } } - backOffKey := fmt.Sprintf("%s_%s", pod.Name, container.Image) + backOffKey := fmt.Sprintf("%s_%s", pod.UID, container.Image) if puller.backOff.IsInBackOffSinceUpdate(backOffKey, puller.backOff.Clock.Now()) { msg := fmt.Sprintf("Back-off pulling image %q", container.Image) - puller.logIt(ref, api.EventTypeNormal, BackOffPullImage, logPrefix, msg, glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, glog.Info) return ErrImagePullBackOff, msg } @@ -119,7 +121,7 @@ func (puller *serializedImagePuller) PullImage(pod *api.Pod, container *api.Cont returnChan: returnChan, } if err = <-returnChan; err != nil { - puller.logIt(ref, api.EventTypeWarning, FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) + puller.logIt(ref, api.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, err), glog.Warning) puller.backOff.Next(backOffKey, puller.backOff.Clock.Now()) if err == RegistryUnavailable { msg := fmt.Sprintf("image pull failed for %s because the registry is unavailable.", container.Image) @@ -128,14 +130,14 @@ func (puller *serializedImagePuller) PullImage(pod *api.Pod, container *api.Cont return ErrImagePull, err.Error() } } - puller.logIt(ref, api.EventTypeNormal, PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) + puller.logIt(ref, api.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), glog.Info) puller.backOff.GC() return nil, "" } func (puller *serializedImagePuller) pullImages() { for pullRequest := range puller.pullRequests { - puller.logIt(pullRequest.ref, api.EventTypeNormal, PullingImage, pullRequest.logPrefix, fmt.Sprintf("pulling image %q", pullRequest.container.Image), glog.Info) + puller.logIt(pullRequest.ref, api.EventTypeNormal, events.PullingImage, pullRequest.logPrefix, fmt.Sprintf("pulling image %q", pullRequest.container.Image), glog.Info) pullRequest.returnChan <- puller.runtime.PullImage(pullRequest.spec, pullRequest.pullSecrets) } } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/images/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/images/types.go new file mode 100644 index 000000000000..4c79110fb657 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/images/types.go @@ -0,0 +1,59 @@ +/* +Copyright 2016 The Kubernetes 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 images + +import ( + "errors" + + "k8s.io/kubernetes/pkg/api" +) + +var ( + // Container image pull failed, kubelet is backing off image pull + ErrImagePullBackOff = errors.New("ImagePullBackOff") + + // Unable to inspect image + ErrImageInspect = errors.New("ImageInspectError") + + // General image pull error + ErrImagePull = errors.New("ErrImagePull") + + // Required Image is absent on host and PullPolicy is NeverPullImage + ErrImageNeverPull = errors.New("ErrImageNeverPull") + + // Get http error when pulling image from registry + RegistryUnavailable = errors.New("RegistryUnavailable") +) + +// ImageManager provides an interface to manage the lifecycle of images. +// Implementations of this interface are expected to deal with pulling (downloading), +// managing, and deleting container images. +// Implementations are expected to abstract the underlying runtimes. +// Implementations are expected to be thread safe. +type ImageManager interface { + // EnsureImageExists ensures that image specified in `container` exists. + EnsureImageExists(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) + + // TODO(ronl): consolidating image managing and deleting operation in this interface +} + +// ImagePuller wraps Runtime.PullImage() to pull a container image. +// It will check the presence of the image, and report the 'image pulling', +// 'image pulled' events correspondingly. +type imagePuller interface { + pullImage(pod *api.Pod, container *api.Container, pullSecrets []api.Secret) (error, string) +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go index 744216c8127f..3d2896202fd6 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,13 +21,11 @@ import ( "fmt" "io" "io/ioutil" - "math" "net" "net/http" "os" "path" "path/filepath" - goRuntime "runtime" "sort" "strings" "sync" @@ -37,9 +35,7 @@ import ( "github.com/golang/glog" cadvisorapi "github.com/google/cadvisor/info/v1" "k8s.io/kubernetes/pkg/api" - apierrors "k8s.io/kubernetes/pkg/api/errors" utilpod "k8s.io/kubernetes/pkg/api/pod" - "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/validation" "k8s.io/kubernetes/pkg/apis/componentconfig" @@ -55,7 +51,9 @@ import ( kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/dockertools" "k8s.io/kubernetes/pkg/kubelet/envvars" + "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/kubelet/eviction" + "k8s.io/kubernetes/pkg/kubelet/images" "k8s.io/kubernetes/pkg/kubelet/lifecycle" "k8s.io/kubernetes/pkg/kubelet/metrics" "k8s.io/kubernetes/pkg/kubelet/network" @@ -75,29 +73,28 @@ import ( "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/securitycontext" "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/bandwidth" + "k8s.io/kubernetes/pkg/util/clock" utilerrors "k8s.io/kubernetes/pkg/util/errors" utilexec "k8s.io/kubernetes/pkg/util/exec" "k8s.io/kubernetes/pkg/util/flowcontrol" kubeio "k8s.io/kubernetes/pkg/util/io" "k8s.io/kubernetes/pkg/util/mount" - utilnet "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/pkg/util/oom" "k8s.io/kubernetes/pkg/util/procfs" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/selinux" "k8s.io/kubernetes/pkg/util/sets" + "k8s.io/kubernetes/pkg/util/term" utilvalidation "k8s.io/kubernetes/pkg/util/validation" "k8s.io/kubernetes/pkg/util/validation/field" "k8s.io/kubernetes/pkg/util/wait" - "k8s.io/kubernetes/pkg/version" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/volumehelper" "k8s.io/kubernetes/pkg/watch" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" - "k8s.io/kubernetes/third_party/golang/expansion" + "k8s.io/kubernetes/third_party/forked/golang/expansion" ) const ( @@ -160,7 +157,7 @@ const ( type SyncHandler interface { HandlePodAdditions(pods []*api.Pod) HandlePodUpdates(pods []*api.Pod) - HandlePodDeletions(pods []*api.Pod) + HandlePodRemoves(pods []*api.Pod) HandlePodReconcile(pods []*api.Pod) HandlePodSyncs(pods []*api.Pod) HandlePodCleanups() error @@ -205,6 +202,7 @@ func NewMainKubelet( nodeLabels map[string]string, nodeStatusUpdateFrequency time.Duration, osInterface kubecontainer.OSInterface, + CgroupsPerQOS bool, cgroupRoot string, containerRuntime string, runtimeRequestTimeout time.Duration, @@ -338,6 +336,7 @@ func NewMainKubelet( nodeStatusUpdateFrequency: nodeStatusUpdateFrequency, os: osInterface, oomWatcher: oomWatcher, + CgroupsPerQOS: CgroupsPerQOS, cgroupRoot: cgroupRoot, mounter: mounter, writer: writer, @@ -355,7 +354,7 @@ func NewMainKubelet( flannelExperimentalOverlay: flannelExperimentalOverlay, flannelHelper: nil, nodeIP: nodeIP, - clock: util.RealClock{}, + clock: clock.RealClock{}, outOfDiskTransitionFrequency: outOfDiskTransitionFrequency, reservation: reservation, enableCustomMetrics: enableCustomMetrics, @@ -467,7 +466,7 @@ func NewMainKubelet( // TODO: Factor out "StatsProvider" from Kubelet so we don't have a cyclic dependency klet.resourceAnalyzer = stats.NewResourceAnalyzer(klet, volumeStatsAggPeriod, klet.containerRuntime) - klet.pleg = pleg.NewGenericPLEG(klet.containerRuntime, plegChannelCapacity, plegRelistPeriod, klet.podCache, util.RealClock{}) + klet.pleg = pleg.NewGenericPLEG(klet.containerRuntime, plegChannelCapacity, plegRelistPeriod, klet.podCache, clock.RealClock{}) klet.runtimeState = newRuntimeState(maxWaitForContainerRuntime) klet.updatePodCIDR(podCIDR) @@ -507,7 +506,8 @@ func NewMainKubelet( klet.podManager, klet.kubeClient, klet.volumePluginMgr, - klet.containerRuntime) + klet.containerRuntime, + mounter) runtimeCache, err := kubecontainer.NewRuntimeCache(klet.containerRuntime) if err != nil { @@ -530,6 +530,14 @@ func NewMainKubelet( klet.evictionManager = evictionManager klet.AddPodAdmitHandler(evictionAdmitHandler) + // enable active deadline handler + activeDeadlineHandler, err := newActiveDeadlineHandler(klet.statusManager, klet.recorder, klet.clock) + if err != nil { + return nil, err + } + klet.AddPodSyncLoopHandler(activeDeadlineHandler) + klet.AddPodSyncHandler(activeDeadlineHandler) + // apply functional Option's for _, opt := range kubeOptions { opt(klet) @@ -537,40 +545,6 @@ func NewMainKubelet( return klet, nil } -// effectiveHairpinMode determines the effective hairpin mode given the -// configured mode, container runtime, and whether cbr0 should be configured. -func effectiveHairpinMode(hairpinMode componentconfig.HairpinMode, containerRuntime string, configureCBR0 bool, networkPlugin string) (componentconfig.HairpinMode, error) { - // The hairpin mode setting doesn't matter if: - // - We're not using a bridge network. This is hard to check because we might - // be using a plugin. It matters if --configure-cbr0=true, and we currently - // don't pipe it down to any plugins. - // - It's set to hairpin-veth for a container runtime that doesn't know how - // to set the hairpin flag on the veth's of containers. Currently the - // docker runtime is the only one that understands this. - // - It's set to "none". - if hairpinMode == componentconfig.PromiscuousBridge || hairpinMode == componentconfig.HairpinVeth { - // Only on docker. - if containerRuntime != "docker" { - glog.Warningf("Hairpin mode set to %q but container runtime is %q, ignoring", hairpinMode, containerRuntime) - return componentconfig.HairpinNone, nil - } - if hairpinMode == componentconfig.PromiscuousBridge && !configureCBR0 && networkPlugin != "kubenet" { - // This is not a valid combination. Users might be using the - // default values (from before the hairpin-mode flag existed) and we - // should keep the old behavior. - glog.Warningf("Hairpin mode set to %q but configureCBR0 is false, falling back to %q", hairpinMode, componentconfig.HairpinVeth) - return componentconfig.HairpinVeth, nil - } - } else if hairpinMode == componentconfig.HairpinNone { - if configureCBR0 { - glog.Warningf("Hairpin mode set to %q and configureCBR0 is true, this might result in loss of hairpin packets", hairpinMode) - } - } else { - return "", fmt.Errorf("unknown value: %q", hairpinMode) - } - return hairpinMode, nil -} - type serviceLister interface { List() (api.ServiceList, error) } @@ -731,6 +705,9 @@ type Kubelet struct { // Monitor resource usage resourceAnalyzer stats.ResourceAnalyzer + // Whether or not we should have the QOS cgroup hierarchy for resource management + CgroupsPerQOS bool + // If non-empty, pass this to the container runtime as the root cgroup. cgroupRoot string @@ -788,6 +765,8 @@ type Kubelet struct { // oneTimeInitializer is used to initialize modules that are dependent on the runtime to be up. oneTimeInitializer sync.Once + // flannelExperimentalOverlay determines whether the experimental flannel + // network overlay is active. flannelExperimentalOverlay bool // TODO: Flannelhelper doesn't store any state, we can instantiate it @@ -800,7 +779,7 @@ type Kubelet struct { // clock is an interface that provides time related functionality in a way that makes it // easy to test the code. - clock util.Clock + clock clock.Clock // outOfDiskTransitionFrequency specifies the amount of time the kubelet has to be actually // not out of disk before it can transition the node condition status from out-of-disk to @@ -845,48 +824,6 @@ type Kubelet struct { enableControllerAttachDetach bool } -// Validate given node IP belongs to the current host -func (kl *Kubelet) validateNodeIP() error { - if kl.nodeIP == nil { - return nil - } - - // Honor IP limitations set in setNodeStatus() - if kl.nodeIP.IsLoopback() { - return fmt.Errorf("nodeIP can't be loopback address") - } - if kl.nodeIP.To4() == nil { - return fmt.Errorf("nodeIP must be IPv4 address") - } - - addrs, err := net.InterfaceAddrs() - if err != nil { - return err - } - for _, addr := range addrs { - var ip net.IP - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - if ip != nil && ip.Equal(kl.nodeIP) { - return nil - } - } - return fmt.Errorf("Node IP: %q not found in the host's network interfaces", kl.nodeIP.String()) -} - -// dirExists returns true if the path exists and represents a directory. -func dirExists(path string) bool { - s, err := os.Stat(path) - if err != nil { - return false - } - return s.IsDir() -} - // setupDataDirs creates: // 1. the root directory // 2. the pods directory @@ -981,6 +918,10 @@ func (kl *Kubelet) initializeRuntimeDependentModules() { // TODO(random-liu): Add backoff logic in the babysitter glog.Fatalf("Failed to start cAdvisor %v", err) } + // eviction manager must start after cadvisor because it needs to know if the container runtime has a dedicated imagefs + if err := kl.evictionManager.Start(kl, kl.getActivePods, evictionMonitoringPeriod); err != nil { + kl.runtimeState.setInternalError(fmt.Errorf("failed to start eviction manager %v", err)) + } } // Run starts the kubelet reacting to config updates @@ -992,7 +933,7 @@ func (kl *Kubelet) Run(updates <-chan kubetypes.PodUpdate) { glog.Warning("No api server defined - no node status update will be sent.") } if err := kl.initializeModules(); err != nil { - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, kubecontainer.KubeletSetupFailed, err.Error()) + kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.KubeletSetupFailed, err.Error()) glog.Error(err) kl.runtimeState.setInitError(err) } @@ -1014,7 +955,6 @@ func (kl *Kubelet) Run(updates <-chan kubetypes.PodUpdate) { // Start component sync loops. kl.statusManager.Start() kl.probeManager.Start() - kl.evictionManager.Start(kl.getActivePods, evictionMonitoringPeriod) // Start the pod lifecycle event generator. kl.pleg.Start() @@ -1028,199 +968,6 @@ func (kl *Kubelet) getActivePods() []*api.Pod { return activePods } -// initialNodeStatus determines the initial node status, incorporating node -// labels and information from the cloud provider. -func (kl *Kubelet) initialNodeStatus() (*api.Node, error) { - node := &api.Node{ - ObjectMeta: api.ObjectMeta{ - Name: kl.nodeName, - Labels: map[string]string{ - unversioned.LabelHostname: kl.hostname, - unversioned.LabelOS: goRuntime.GOOS, - unversioned.LabelArch: goRuntime.GOARCH, - }, - }, - Spec: api.NodeSpec{ - Unschedulable: !kl.registerSchedulable, - }, - } - // Initially, set NodeNetworkUnavailable to true. - if kl.providerRequiresNetworkingConfiguration() { - node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ - Type: api.NodeNetworkUnavailable, - Status: api.ConditionTrue, - Reason: "NoRouteCreated", - Message: "Node created without a route", - LastTransitionTime: unversioned.NewTime(kl.clock.Now()), - }) - } - - if kl.enableControllerAttachDetach { - if node.Annotations == nil { - node.Annotations = make(map[string]string) - } - - node.Annotations[volumehelper.ControllerManagedAttachAnnotation] = "true" - } - - // @question: should this be place after the call to the cloud provider? which also applies labels - for k, v := range kl.nodeLabels { - if cv, found := node.ObjectMeta.Labels[k]; found { - glog.Warningf("the node label %s=%s will overwrite default setting %s", k, v, cv) - } - node.ObjectMeta.Labels[k] = v - } - - if kl.cloud != nil { - instances, ok := kl.cloud.Instances() - if !ok { - return nil, fmt.Errorf("failed to get instances from cloud provider") - } - - // TODO(roberthbailey): Can we do this without having credentials to talk - // to the cloud provider? - // TODO: ExternalID is deprecated, we'll have to drop this code - externalID, err := instances.ExternalID(kl.nodeName) - if err != nil { - return nil, fmt.Errorf("failed to get external ID from cloud provider: %v", err) - } - node.Spec.ExternalID = externalID - - // TODO: We can't assume that the node has credentials to talk to the - // cloudprovider from arbitrary nodes. At most, we should talk to a - // local metadata server here. - node.Spec.ProviderID, err = cloudprovider.GetInstanceProviderID(kl.cloud, kl.nodeName) - if err != nil { - return nil, err - } - - instanceType, err := instances.InstanceType(kl.nodeName) - if err != nil { - return nil, err - } - if instanceType != "" { - glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelInstanceType, instanceType) - node.ObjectMeta.Labels[unversioned.LabelInstanceType] = instanceType - } - // If the cloud has zone information, label the node with the zone information - zones, ok := kl.cloud.Zones() - if ok { - zone, err := zones.GetZone() - if err != nil { - return nil, fmt.Errorf("failed to get zone from cloud provider: %v", err) - } - if zone.FailureDomain != "" { - glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelZoneFailureDomain, zone.FailureDomain) - node.ObjectMeta.Labels[unversioned.LabelZoneFailureDomain] = zone.FailureDomain - } - if zone.Region != "" { - glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelZoneRegion, zone.Region) - node.ObjectMeta.Labels[unversioned.LabelZoneRegion] = zone.Region - } - } - } else { - node.Spec.ExternalID = kl.hostname - if kl.autoDetectCloudProvider { - // If no cloud provider is defined - use the one detected by cadvisor - info, err := kl.GetCachedMachineInfo() - if err == nil { - kl.updateCloudProviderFromMachineInfo(node, info) - } - } - } - if err := kl.setNodeStatus(node); err != nil { - return nil, err - } - - return node, nil -} - -func (kl *Kubelet) providerRequiresNetworkingConfiguration() bool { - // TODO: We should have a mechanism to say whether native cloud provider - // is used or whether we are using overlay networking. We should return - // true for cloud providers if they implement Routes() interface and - // we are not using overlay networking. - if kl.cloud == nil || kl.cloud.ProviderName() != "gce" || kl.flannelExperimentalOverlay { - return false - } - _, supported := kl.cloud.Routes() - return supported -} - -// registerWithApiserver registers the node with the cluster master. It is safe -// to call multiple times, but not concurrently (kl.registrationCompleted is -// not locked). -func (kl *Kubelet) registerWithApiserver() { - if kl.registrationCompleted { - return - } - step := 100 * time.Millisecond - for { - time.Sleep(step) - step = step * 2 - if step >= 7*time.Second { - step = 7 * time.Second - } - - node, err := kl.initialNodeStatus() - if err != nil { - glog.Errorf("Unable to construct api.Node object for kubelet: %v", err) - continue - } - - glog.V(2).Infof("Attempting to register node %s", node.Name) - if _, err := kl.kubeClient.Core().Nodes().Create(node); err != nil { - if !apierrors.IsAlreadyExists(err) { - glog.V(2).Infof("Unable to register %s with the apiserver: %v", node.Name, err) - continue - } - currentNode, err := kl.kubeClient.Core().Nodes().Get(kl.nodeName) - if err != nil { - glog.Errorf("error getting node %q: %v", kl.nodeName, err) - continue - } - if currentNode == nil { - glog.Errorf("no node instance returned for %q", kl.nodeName) - continue - } - if currentNode.Spec.ExternalID == node.Spec.ExternalID { - glog.Infof("Node %s was previously registered", node.Name) - kl.registrationCompleted = true - return - } - glog.Errorf( - "Previously %q had externalID %q; now it is %q; will delete and recreate.", - kl.nodeName, node.Spec.ExternalID, currentNode.Spec.ExternalID, - ) - if err := kl.kubeClient.Core().Nodes().Delete(node.Name, nil); err != nil { - glog.Errorf("Unable to delete old node: %v", err) - } else { - glog.Errorf("Deleted old node object %q", kl.nodeName) - } - continue - } - glog.Infof("Successfully registered node %s", node.Name) - kl.registrationCompleted = true - return - } -} - -// syncNodeStatus should be called periodically from a goroutine. -// It synchronizes node status to master, registering the kubelet first if -// necessary. -func (kl *Kubelet) syncNodeStatus() { - if kl.kubeClient == nil { - return - } - if kl.registerNode { - // This will exit immediately if it doesn't need to do anything. - kl.registerWithApiserver() - } - if err := kl.updateNodeStatus(); err != nil { - glog.Errorf("Unable to update node status: %v", err) - } -} - // relabelVolumes relabels SELinux volumes to match the pod's // SELinuxOptions specification. This is only needed if the pod uses // hostPID or hostIPC. Otherwise relabeling is delegated to docker. @@ -1712,62 +1459,7 @@ func (kl *Kubelet) GetClusterDNS(pod *api.Pod) ([]string, []string, error) { return dns, dnsSearch, nil } -// Returns the list of DNS servers and DNS search domains. -func (kl *Kubelet) parseResolvConf(reader io.Reader) (nameservers []string, searches []string, err error) { - var scrubber dnsScrubber - if kl.cloud != nil { - scrubber = kl.cloud - } - return parseResolvConf(reader, scrubber) -} - -// A helper for testing. -type dnsScrubber interface { - ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) -} - -// parseResolveConf reads a resolv.conf file from the given reader, and parses -// it into nameservers and searches, possibly returning an error. The given -// dnsScrubber allows cloud providers to post-process dns names. -// TODO: move to utility package -func parseResolvConf(reader io.Reader, dnsScrubber dnsScrubber) (nameservers []string, searches []string, err error) { - file, err := ioutil.ReadAll(reader) - if err != nil { - return nil, nil, err - } - - // Lines of the form "nameserver 1.2.3.4" accumulate. - nameservers = []string{} - - // Lines of the form "search example.com" overrule - last one wins. - searches = []string{} - - lines := strings.Split(string(file), "\n") - for l := range lines { - trimmed := strings.TrimSpace(lines[l]) - if strings.HasPrefix(trimmed, "#") { - continue - } - fields := strings.Fields(trimmed) - if len(fields) == 0 { - continue - } - if fields[0] == "nameserver" { - nameservers = append(nameservers, fields[1:]...) - } - if fields[0] == "search" { - searches = fields[1:] - } - } - - // Give the cloud-provider a chance to post-process DNS settings. - if dnsScrubber != nil { - nameservers, searches = dnsScrubber.ScrubDNS(nameservers, searches) - } - return nameservers, searches, nil -} - -// One of the following aruguements must be non-nil: runningPod, status. +// One of the following arguments must be non-nil: runningPod, status. // TODO: Modify containerRuntime.KillPod() to accept the right arguments. func (kl *Kubelet) killPod(pod *api.Pod, runningPod *kubecontainer.Pod, status *kubecontainer.PodStatus, gracePeriodOverride *int64) error { var p kubecontainer.Pod @@ -1798,10 +1490,7 @@ func (kl *Kubelet) makePodDataDirs(pod *api.Pod) error { // // Arguments: // -// pod - the pod to sync -// mirrorPod - the mirror pod for the pod to sync, if it is a static pod -// podStatus - the current status (TODO: always from the status manager?) -// updateType - the type of update (ADD, UPDATE, REMOVE, RECONCILE) +// o - the SyncPodOptions for this invocation // // The workflow is: // * If the pod is being created, record pod worker start latency @@ -1926,12 +1615,9 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { return err } if err := kl.volumeManager.WaitForAttachAndMount(defaultedPod); err != nil { - ref, errGetRef := api.GetReference(pod) - if errGetRef == nil && ref != nil { - kl.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedMountVolume, "Unable to mount volumes for pod %q: %v", format.Pod(pod), err) - glog.Errorf("Unable to mount volumes for pod %q: %v; skipping pod", format.Pod(pod), err) - return err - } + kl.recorder.Eventf(pod, api.EventTypeWarning, events.FailedMountVolume, "Unable to mount volumes for pod %q: %v", format.Pod(pod), err) + glog.Errorf("Unable to mount volumes for pod %q: %v; skipping pod", format.Pod(pod), err) + return err } // Fetch the pull secrets for the pod @@ -1960,13 +1646,13 @@ func (kl *Kubelet) syncPod(o syncPodOptions) error { } if egress != nil || ingress != nil { if podUsesHostNetwork(pod) { - kl.recorder.Event(pod, api.EventTypeWarning, kubecontainer.HostNetworkNotSupported, "Bandwidth shaping is not currently supported on the host network") + kl.recorder.Event(pod, api.EventTypeWarning, events.HostNetworkNotSupported, "Bandwidth shaping is not currently supported on the host network") } else if kl.shaper != nil { if len(apiPodStatus.PodIP) > 0 { err = kl.shaper.ReconcileCIDR(fmt.Sprintf("%s/32", apiPodStatus.PodIP), egress, ingress) } } else { - kl.recorder.Event(pod, api.EventTypeWarning, kubecontainer.UndefinedShaper, "Pod requests bandwidth shaping, but the shaper is undefined") + kl.recorder.Event(pod, api.EventTypeWarning, events.UndefinedShaper, "Pod requests bandwidth shaping, but the shaper is undefined") } } @@ -1978,8 +1664,11 @@ func podUsesHostNetwork(pod *api.Pod) bool { return pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork } -// getPullSecretsForPod inspects the Pod and retrieves the referenced pull secrets -// TODO duplicate secrets are being retrieved multiple times and there is no cache. Creating and using a secret manager interface will make this easier to address. +// getPullSecretsForPod inspects the Pod and retrieves the referenced pull +// secrets. +// TODO: duplicate secrets are being retrieved multiple times and there +// is no cache. Creating and using a secret manager interface will make this +// easier to address. func (kl *Kubelet) getPullSecretsForPod(pod *api.Pod) ([]api.Secret, error) { pullSecrets := []api.Secret{} @@ -2033,74 +1722,8 @@ func (kl *Kubelet) cleanupOrphanedPodDirs( return utilerrors.NewAggregate(errlist) } -// cleanupBandwidthLimits updates the status of bandwidth-limited containers -// and ensures that only the the appropriate CIDRs are active on the node. -func (kl *Kubelet) cleanupBandwidthLimits(allPods []*api.Pod) error { - if kl.shaper == nil { - return nil - } - currentCIDRs, err := kl.shaper.GetCIDRs() - if err != nil { - return err - } - possibleCIDRs := sets.String{} - for ix := range allPods { - pod := allPods[ix] - ingress, egress, err := bandwidth.ExtractPodBandwidthResources(pod.Annotations) - if err != nil { - return err - } - if ingress == nil && egress == nil { - glog.V(8).Infof("Not a bandwidth limited container...") - continue - } - status, found := kl.statusManager.GetPodStatus(pod.UID) - if !found { - // TODO(random-liu): Cleanup status get functions. (issue #20477) - s, err := kl.containerRuntime.GetPodStatus(pod.UID, pod.Name, pod.Namespace) - if err != nil { - return err - } - status = kl.generateAPIPodStatus(pod, s) - } - if status.Phase == api.PodRunning { - possibleCIDRs.Insert(fmt.Sprintf("%s/32", status.PodIP)) - } - } - for _, cidr := range currentCIDRs { - if !possibleCIDRs.Has(cidr) { - glog.V(2).Infof("Removing CIDR: %s (%v)", cidr, possibleCIDRs) - if err := kl.shaper.Reset(cidr); err != nil { - return err - } - } - } - return nil -} - -// pastActiveDeadline returns true if the pod has been active for more than -// ActiveDeadlineSeconds. -func (kl *Kubelet) pastActiveDeadline(pod *api.Pod) bool { - if pod.Spec.ActiveDeadlineSeconds != nil { - podStatus, ok := kl.statusManager.GetPodStatus(pod.UID) - if !ok { - podStatus = pod.Status - } - if !podStatus.StartTime.IsZero() { - startTime := podStatus.StartTime.Time - duration := kl.clock.Since(startTime) - allowedDuration := time.Duration(*pod.Spec.ActiveDeadlineSeconds) * time.Second - if duration >= allowedDuration { - return true - } - } - } - return false -} - // Get pods which should be resynchronized. Currently, the following pod should be resynchronized: // * pod whose work is ready. -// * pod past the active deadline. // * internal modules that request sync of a pod. func (kl *Kubelet) getPodsToSync() []*api.Pod { allPods := kl.podManager.GetPods() @@ -2111,12 +1734,6 @@ func (kl *Kubelet) getPodsToSync() []*api.Pod { } var podsToSync []*api.Pod for _, pod := range allPods { - // TODO: move active deadline code into a sync/evict pattern - if kl.pastActiveDeadline(pod) { - // The pod has passed the active deadline - podsToSync = append(podsToSync, pod) - continue - } if podUIDSet.Has(string(pod.UID)) { // The work of the pod is ready podsToSync = append(podsToSync, pod) @@ -2218,9 +1835,8 @@ type empty struct{} // HandlePodCleanups performs a series of cleanup work, including terminating // pod workers, killing unwanted pods, and removing orphaned volumes/pod // directories. -// TODO(yujuhong): This function is executed by the main sync loop, so it -// should not contain any blocking calls. Re-examine the function and decide -// whether or not we should move it into a separte goroutine. +// NOTE: This function is executed by the main sync loop, so it +// should not contain any blocking calls. func (kl *Kubelet) HandlePodCleanups() error { allPods, mirrorPods := kl.podManager.GetPodsAndMirrorPods() // Pod phase progresses monotonically. Once a pod has reached a final state, @@ -2272,20 +1888,23 @@ func (kl *Kubelet) HandlePodCleanups() error { // deleted pods. err = kl.cleanupOrphanedPodDirs(allPods, runningPods) if err != nil { + // We want all cleanup tasks to be run even if one of them failed. So + // we just log an error here and continue other cleanup tasks. + // This also applies to the other clean up tasks. glog.Errorf("Failed cleaning up orphaned pod directories: %v", err) - return err } // Remove any orphaned mirror pods. kl.podManager.DeleteOrphanedMirrorPods() // Clear out any old bandwidth rules - if err = kl.cleanupBandwidthLimits(allPods); err != nil { - return err + err = kl.cleanupBandwidthLimits(allPods) + if err != nil { + glog.Errorf("Failed cleaning up bandwidth limits: %v", err) } kl.backOff.GC() - return err + return nil } // podKiller launches a goroutine to kill a pod received from the channel if @@ -2378,19 +1997,6 @@ func (kl *Kubelet) isOutOfDisk() bool { return false } -// matchesNodeSelector returns true if pod matches node's labels. -func (kl *Kubelet) matchesNodeSelector(pod *api.Pod) bool { - if kl.standaloneMode { - return true - } - node, err := kl.GetNode() - if err != nil { - glog.Errorf("error getting node: %v", err) - return true - } - return predicates.PodMatchesNodeLabels(pod, node) -} - // rejectPod records an event about the pod with the given reason and message, // and updates the pod to the failed phase in the status manage. func (kl *Kubelet) rejectPod(pod *api.Pod, reason, message string) { @@ -2402,8 +2008,8 @@ func (kl *Kubelet) rejectPod(pod *api.Pod, reason, message string) { } // canAdmitPod determines if a pod can be admitted, and gives a reason if it -// cannot. "pod" is new pod, while "pods" include all admitted pods plus the -// new pod. The function returns a boolean value indicating whether the pod +// cannot. "pod" is new pod, while "pods" are all admitted pods +// The function returns a boolean value indicating whether the pod // can be admitted, a brief single-word reason and a message explaining why // the pod cannot be admitted. func (kl *Kubelet) canAdmitPod(pods []*api.Pod, pod *api.Pod) (bool, string, string) { @@ -2412,27 +2018,21 @@ func (kl *Kubelet) canAdmitPod(pods []*api.Pod, pod *api.Pod) (bool, string, str glog.Errorf("Cannot get Node info: %v", err) return false, "InvalidNodeInfo", "Kubelet cannot get node info." } - otherPods := []*api.Pod{} - for _, p := range pods { - if p != pod { - otherPods = append(otherPods, p) - } - } // the kubelet will invoke each pod admit handler in sequence // if any handler rejects, the pod is rejected. // TODO: move predicate check into a pod admitter // TODO: move out of disk check into a pod admitter // TODO: out of resource eviction should have a pod admitter call-out - attrs := &lifecycle.PodAdmitAttributes{Pod: pod, OtherPods: otherPods} + attrs := &lifecycle.PodAdmitAttributes{Pod: pod, OtherPods: pods} for _, podAdmitHandler := range kl.PodAdmitHandlers { if result := podAdmitHandler.Admit(attrs); !result.Admit { return false, result.Reason, result.Message } } - nodeInfo := schedulercache.NewNodeInfo(otherPods...) + nodeInfo := schedulercache.NewNodeInfo(pods...) nodeInfo.SetNode(node) - fit, err := predicates.GeneralPredicates(pod, nodeInfo) + fit, err := predicates.GeneralPredicates(pod, nil, nodeInfo) if !fit { if re, ok := err.(*predicates.PredicateFailureError); ok { reason := re.PredicateName @@ -2544,24 +2144,31 @@ func (kl *Kubelet) syncLoopIteration(configCh <-chan kubetypes.PodUpdate, handle handler.HandlePodUpdates(u.Pods) case kubetypes.REMOVE: glog.V(2).Infof("SyncLoop (REMOVE, %q): %q", u.Source, format.Pods(u.Pods)) - handler.HandlePodDeletions(u.Pods) + handler.HandlePodRemoves(u.Pods) case kubetypes.RECONCILE: glog.V(4).Infof("SyncLoop (RECONCILE, %q): %q", u.Source, format.Pods(u.Pods)) handler.HandlePodReconcile(u.Pods) + case kubetypes.DELETE: + glog.V(2).Infof("SyncLoop (DELETE, %q): %q", u.Source, format.Pods(u.Pods)) + // DELETE is treated as a UPDATE because of graceful deletion. + handler.HandlePodUpdates(u.Pods) case kubetypes.SET: // TODO: Do we want to support this? glog.Errorf("Kubelet does not support snapshot update") + } case e := <-plegCh: - // PLEG event for a pod; sync it. - pod, ok := kl.podManager.GetPodByUID(e.ID) - if !ok { - // If the pod no longer exists, ignore the event. - glog.V(4).Infof("SyncLoop (PLEG): ignore irrelevant event: %#v", e) - break + if isSyncPodWorthy(e) { + // PLEG event for a pod; sync it. + pod, ok := kl.podManager.GetPodByUID(e.ID) + if !ok { + // If the pod no longer exists, ignore the event. + glog.V(4).Infof("SyncLoop (PLEG): ignore irrelevant event: %#v", e) + break + } + glog.V(2).Infof("SyncLoop (PLEG): %q, event: %#v", format.Pod(pod), e) + handler.HandlePodSyncs([]*api.Pod{pod}) } - glog.V(2).Infof("SyncLoop (PLEG): %q, event: %#v", format.Pod(pod), e) - handler.HandlePodSyncs([]*api.Pod{pod}) case <-syncCh: // Sync pods waiting for sync podsToSync := kl.getPodsToSync() @@ -2631,7 +2238,7 @@ func (kl *Kubelet) dispatchWork(pod *api.Pod, syncType kubetypes.SyncPodType, mi } } -// TODO: Consider handling all mirror pods updates in a separate component. +// TODO: handle mirror pods in a separate component (issue #17251) func (kl *Kubelet) handleMirrorPod(mirrorPod *api.Pod, start time.Time) { // Mirror pod ADD/UPDATE/DELETE operations are considered an UPDATE to the // corresponding static pod. Send update to the pod worker if the static @@ -2647,22 +2254,22 @@ func (kl *Kubelet) HandlePodAdditions(pods []*api.Pod) { start := kl.clock.Now() sort.Sort(podsByCreationTime(pods)) for _, pod := range pods { - kl.podManager.AddPod(pod) if kubepod.IsMirrorPod(pod) { + kl.podManager.AddPod(pod) kl.handleMirrorPod(pod, start) continue } - // Note that allPods includes the new pod since we added at the - // beginning of the loop. + // Note that allPods excludes the new pod. allPods := kl.podManager.GetPods() // We failed pods that we rejected, so activePods include all admitted - // pods that are alive and the new pod. + // pods that are alive. activePods := kl.filterOutTerminatedPods(allPods) // Check if we can admit the pod; if not, reject it. if ok, reason, message := kl.canAdmitPod(activePods, pod); !ok { kl.rejectPod(pod, reason, message) continue } + kl.podManager.AddPod(pod) mirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod) kl.dispatchWork(pod, kubetypes.SyncPodCreate, mirrorPod, start) kl.probeManager.AddPod(pod) @@ -2686,9 +2293,9 @@ func (kl *Kubelet) HandlePodUpdates(pods []*api.Pod) { } } -// HandlePodDeletions is the callback in the SyncHandler interface for pods -// being deleted from a config source. -func (kl *Kubelet) HandlePodDeletions(pods []*api.Pod) { +// HandlePodRemoves is the callback in the SyncHandler interface for pods +// being removed from a config source. +func (kl *Kubelet) HandlePodRemoves(pods []*api.Pod) { start := kl.clock.Now() for _, pod := range pods { kl.podManager.DeletePod(pod) @@ -2776,9 +2383,9 @@ func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *api.Pod case waiting != nil: // output some info for the most common pending failures switch reason := waiting.Reason; reason { - case kubecontainer.ErrImagePull.Error(): + case images.ErrImagePull.Error(): return kubecontainer.ContainerID{}, fmt.Errorf("container %q in pod %q is waiting to start: image can't be pulled", containerName, podName) - case kubecontainer.ErrImagePullBackOff.Error(): + case images.ErrImagePullBackOff.Error(): return kubecontainer.ContainerID{}, fmt.Errorf("container %q in pod %q is waiting to start: trying and failing to pull image", containerName, podName) default: return kubecontainer.ContainerID{}, fmt.Errorf("container %q in pod %q is waiting to start: %v", containerName, podName, reason) @@ -2795,7 +2402,6 @@ func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *api.Pod // TODO: this method is returning logs of random container attempts, when it should be returning the most recent attempt // or all of them. func (kl *Kubelet) GetKubeletContainerLogs(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error { - // TODO(vmarmol): Refactor to not need the pod status and verification. // Pod workers periodically write status to statusManager. If status is not // cached there, something is wrong (or kubelet just restarted and hasn't // caught up yet). Just assume the pod is not ready yet. @@ -2841,160 +2447,6 @@ func (kl *Kubelet) updateRuntimeUp() { kl.runtimeState.setRuntimeSync(kl.clock.Now()) } -// TODO: remove when kubenet plugin is ready -// NOTE!!! if you make changes here, also make them to kubenet -func (kl *Kubelet) reconcileCBR0(podCIDR string) error { - if podCIDR == "" { - glog.V(5).Info("PodCIDR not set. Will not configure cbr0.") - return nil - } - glog.V(5).Infof("PodCIDR is set to %q", podCIDR) - _, cidr, err := net.ParseCIDR(podCIDR) - if err != nil { - return err - } - // Set cbr0 interface address to first address in IPNet - cidr.IP.To4()[3] += 1 - if err := ensureCbr0(cidr, kl.hairpinMode == componentconfig.PromiscuousBridge, kl.babysitDaemons); err != nil { - return err - } - if kl.shapingEnabled() { - if kl.shaper == nil { - glog.V(5).Info("Shaper is nil, creating") - kl.shaper = bandwidth.NewTCShaper("cbr0") - } - return kl.shaper.ReconcileInterface() - } - return nil -} - -// updateNodeStatus updates node status to master with retries. -func (kl *Kubelet) updateNodeStatus() error { - for i := 0; i < nodeStatusUpdateRetry; i++ { - if err := kl.tryUpdateNodeStatus(); err != nil { - glog.Errorf("Error updating node status, will retry: %v", err) - } else { - return nil - } - } - return fmt.Errorf("update node status exceeds retry count") -} - -// recordNodeStatusEvent records an event of the given type with the given -// message for the node. -func (kl *Kubelet) recordNodeStatusEvent(eventtype, event string) { - glog.V(2).Infof("Recording %s event message for node %s", event, kl.nodeName) - // TODO: This requires a transaction, either both node status is updated - // and event is recorded or neither should happen, see issue #6055. - kl.recorder.Eventf(kl.nodeRef, eventtype, event, "Node %s status is now: %s", kl.nodeName, event) -} - -// syncNetworkStatus updates the network state, ensuring that the network is -// configured correctly if the kubelet is set to configure cbr0: -// * handshake flannel helper if the flannel experimental overlay is being used. -// * ensure that iptables masq rules are setup -// * reconcile cbr0 with the pod CIDR -func (kl *Kubelet) syncNetworkStatus() { - var err error - if kl.configureCBR0 { - if kl.flannelExperimentalOverlay { - podCIDR, err := kl.flannelHelper.Handshake() - if err != nil { - glog.Infof("Flannel server handshake failed %v", err) - return - } - kl.updatePodCIDR(podCIDR) - } - if err := ensureIPTablesMasqRule(kl.nonMasqueradeCIDR); err != nil { - err = fmt.Errorf("Error on adding ip table rules: %v", err) - glog.Error(err) - kl.runtimeState.setNetworkState(err) - return - } - podCIDR := kl.runtimeState.podCIDR() - if len(podCIDR) == 0 { - err = fmt.Errorf("ConfigureCBR0 requested, but PodCIDR not set. Will not configure CBR0 right now") - glog.Warning(err) - } else if err = kl.reconcileCBR0(podCIDR); err != nil { - err = fmt.Errorf("Error configuring cbr0: %v", err) - glog.Error(err) - } - if err != nil { - kl.runtimeState.setNetworkState(err) - return - } - } - - kl.runtimeState.setNetworkState(kl.networkPlugin.Status()) -} - -// Set addresses for the node. -func (kl *Kubelet) setNodeAddress(node *api.Node) error { - // Set addresses for the node. - if kl.cloud != nil { - instances, ok := kl.cloud.Instances() - if !ok { - return fmt.Errorf("failed to get instances from cloud provider") - } - // TODO(roberthbailey): Can we do this without having credentials to talk - // to the cloud provider? - // TODO(justinsb): We can if CurrentNodeName() was actually CurrentNode() and returned an interface - nodeAddresses, err := instances.NodeAddresses(kl.nodeName) - if err != nil { - return fmt.Errorf("failed to get node address from cloud provider: %v", err) - } - node.Status.Addresses = nodeAddresses - } else { - if kl.nodeIP != nil { - node.Status.Addresses = []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: kl.nodeIP.String()}, - {Type: api.NodeInternalIP, Address: kl.nodeIP.String()}, - } - } else if addr := net.ParseIP(kl.hostname); addr != nil { - node.Status.Addresses = []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: addr.String()}, - {Type: api.NodeInternalIP, Address: addr.String()}, - } - } else { - addrs, err := net.LookupIP(node.Name) - if err != nil { - return fmt.Errorf("can't get ip address of node %s: %v", node.Name, err) - } else if len(addrs) == 0 { - return fmt.Errorf("no ip address for node %v", node.Name) - } else { - // check all ip addresses for this node.Name and try to find the first non-loopback IPv4 address. - // If no match is found, it uses the IP of the interface with gateway on it. - for _, ip := range addrs { - if ip.IsLoopback() { - continue - } - - if ip.To4() != nil { - node.Status.Addresses = []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: ip.String()}, - {Type: api.NodeInternalIP, Address: ip.String()}, - } - break - } - } - - if len(node.Status.Addresses) == 0 { - ip, err := utilnet.ChooseHostInterface() - if err != nil { - return err - } - - node.Status.Addresses = []api.NodeAddress{ - {Type: api.NodeLegacyHostIP, Address: ip.String()}, - {Type: api.NodeInternalIP, Address: ip.String()}, - } - } - } - } - } - return nil -} - func (kl *Kubelet) updateCloudProviderFromMachineInfo(node *api.Node, info *cadvisorapi.MachineInfo) { if info.CloudProvider != cadvisorapi.UnknownProvider && info.CloudProvider != cadvisorapi.Baremetal { @@ -3007,118 +2459,6 @@ func (kl *Kubelet) updateCloudProviderFromMachineInfo(node *api.Node, info *cadv } } -func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { - // TODO: Post NotReady if we cannot get MachineInfo from cAdvisor. This needs to start - // cAdvisor locally, e.g. for test-cmd.sh, and in integration test. - info, err := kl.GetCachedMachineInfo() - if err != nil { - // TODO(roberthbailey): This is required for test-cmd.sh to pass. - // See if the test should be updated instead. - node.Status.Capacity = api.ResourceList{ - api.ResourceCPU: *resource.NewMilliQuantity(0, resource.DecimalSI), - api.ResourceMemory: resource.MustParse("0Gi"), - api.ResourcePods: *resource.NewQuantity(int64(kl.maxPods), resource.DecimalSI), - api.ResourceNvidiaGPU: *resource.NewQuantity(int64(kl.nvidiaGPUs), resource.DecimalSI), - } - glog.Errorf("Error getting machine info: %v", err) - } else { - node.Status.NodeInfo.MachineID = info.MachineID - node.Status.NodeInfo.SystemUUID = info.SystemUUID - node.Status.Capacity = cadvisor.CapacityFromMachineInfo(info) - if kl.podsPerCore > 0 { - node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( - int64(math.Min(float64(info.NumCores*kl.podsPerCore), float64(kl.maxPods))), resource.DecimalSI) - } else { - node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( - int64(kl.maxPods), resource.DecimalSI) - } - node.Status.Capacity[api.ResourceNvidiaGPU] = *resource.NewQuantity( - int64(kl.nvidiaGPUs), resource.DecimalSI) - if node.Status.NodeInfo.BootID != "" && - node.Status.NodeInfo.BootID != info.BootID { - // TODO: This requires a transaction, either both node status is updated - // and event is recorded or neither should happen, see issue #6055. - kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, kubecontainer.NodeRebooted, - "Node %s has been rebooted, boot id: %s", kl.nodeName, info.BootID) - } - node.Status.NodeInfo.BootID = info.BootID - } - - // Set Allocatable. - node.Status.Allocatable = make(api.ResourceList) - for k, v := range node.Status.Capacity { - value := *(v.Copy()) - if kl.reservation.System != nil { - value.Sub(kl.reservation.System[k]) - } - if kl.reservation.Kubernetes != nil { - value.Sub(kl.reservation.Kubernetes[k]) - } - if value.Sign() < 0 { - // Negative Allocatable resources don't make sense. - value.Set(0) - } - node.Status.Allocatable[k] = value - } -} - -// Set versioninfo for the node. -func (kl *Kubelet) setNodeStatusVersionInfo(node *api.Node) { - verinfo, err := kl.cadvisor.VersionInfo() - if err != nil { - glog.Errorf("Error getting version info: %v", err) - } else { - node.Status.NodeInfo.KernelVersion = verinfo.KernelVersion - node.Status.NodeInfo.OSImage = verinfo.ContainerOsVersion - - runtimeVersion := "Unknown" - if runtimeVer, err := kl.containerRuntime.Version(); err == nil { - runtimeVersion = runtimeVer.String() - } - node.Status.NodeInfo.ContainerRuntimeVersion = fmt.Sprintf("%s://%s", kl.containerRuntime.Type(), runtimeVersion) - - node.Status.NodeInfo.KubeletVersion = version.Get().String() - // TODO: kube-proxy might be different version from kubelet in the future - node.Status.NodeInfo.KubeProxyVersion = version.Get().String() - } - -} - -// Set daemonEndpoints for the node. -func (kl *Kubelet) setNodeStatusDaemonEndpoints(node *api.Node) { - node.Status.DaemonEndpoints = *kl.daemonEndpoints -} - -// Set images list for the node -func (kl *Kubelet) setNodeStatusImages(node *api.Node) { - // Update image list of this node - var imagesOnNode []api.ContainerImage - containerImages, err := kl.imageManager.GetImageList() - if err != nil { - glog.Errorf("Error getting image list: %v", err) - } else { - // sort the images from max to min, and only set top N images into the node status. - sort.Sort(byImageSize(containerImages)) - if maxImagesInNodeStatus < len(containerImages) { - containerImages = containerImages[0:maxImagesInNodeStatus] - } - - for _, image := range containerImages { - imagesOnNode = append(imagesOnNode, api.ContainerImage{ - Names: append(image.RepoTags, image.RepoDigests...), - SizeBytes: image.Size, - }) - } - } - node.Status.Images = imagesOnNode -} - -// Set the GOOS and GOARCH for this node -func (kl *Kubelet) setNodeStatusGoRuntime(node *api.Node) { - node.Status.NodeInfo.OperatingSystem = goRuntime.GOOS - node.Status.NodeInfo.Architecture = goRuntime.GOARCH -} - type byImageSize []kubecontainer.Image // Sort from max to min @@ -3128,298 +2468,6 @@ func (a byImageSize) Less(i, j int) bool { func (a byImageSize) Len() int { return len(a) } func (a byImageSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -// Set status for the node. -func (kl *Kubelet) setNodeStatusInfo(node *api.Node) { - kl.setNodeStatusMachineInfo(node) - kl.setNodeStatusVersionInfo(node) - kl.setNodeStatusDaemonEndpoints(node) - kl.setNodeStatusImages(node) - kl.setNodeStatusGoRuntime(node) -} - -// Set Readycondition for the node. -func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { - // NOTE(aaronlevy): NodeReady condition needs to be the last in the list of node conditions. - // This is due to an issue with version skewed kubelet and master components. - // ref: https://github.com/kubernetes/kubernetes/issues/16961 - currentTime := unversioned.NewTime(kl.clock.Now()) - var newNodeReadyCondition api.NodeCondition - if rs := kl.runtimeState.errors(); len(rs) == 0 { - newNodeReadyCondition = api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionTrue, - Reason: "KubeletReady", - Message: "kubelet is posting ready status", - LastHeartbeatTime: currentTime, - } - } else { - newNodeReadyCondition = api.NodeCondition{ - Type: api.NodeReady, - Status: api.ConditionFalse, - Reason: "KubeletNotReady", - Message: strings.Join(rs, ","), - LastHeartbeatTime: currentTime, - } - } - - // Record any soft requirements that were not met in the container manager. - status := kl.containerManager.Status() - if status.SoftRequirements != nil { - newNodeReadyCondition.Message = fmt.Sprintf("%s. WARNING: %s", newNodeReadyCondition.Message, status.SoftRequirements.Error()) - } - - readyConditionUpdated := false - needToRecordEvent := false - for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeReady { - if node.Status.Conditions[i].Status == newNodeReadyCondition.Status { - newNodeReadyCondition.LastTransitionTime = node.Status.Conditions[i].LastTransitionTime - } else { - newNodeReadyCondition.LastTransitionTime = currentTime - needToRecordEvent = true - } - node.Status.Conditions[i] = newNodeReadyCondition - readyConditionUpdated = true - break - } - } - if !readyConditionUpdated { - newNodeReadyCondition.LastTransitionTime = currentTime - node.Status.Conditions = append(node.Status.Conditions, newNodeReadyCondition) - } - if needToRecordEvent { - if newNodeReadyCondition.Status == api.ConditionTrue { - kl.recordNodeStatusEvent(api.EventTypeNormal, kubecontainer.NodeReady) - } else { - kl.recordNodeStatusEvent(api.EventTypeNormal, kubecontainer.NodeNotReady) - } - } -} - -// setNodeMemoryPressureCondition for the node. -// TODO: this needs to move somewhere centralized... -func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { - currentTime := unversioned.NewTime(kl.clock.Now()) - var condition *api.NodeCondition - - // Check if NodeMemoryPressure condition already exists and if it does, just pick it up for update. - for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeMemoryPressure { - condition = &node.Status.Conditions[i] - } - } - - newCondition := false - // If the NodeMemoryPressure condition doesn't exist, create one - if condition == nil { - condition = &api.NodeCondition{ - Type: api.NodeMemoryPressure, - Status: api.ConditionUnknown, - } - // cannot be appended to node.Status.Conditions here because it gets - // copied to the slice. So if we append to the slice here none of the - // updates we make below are reflected in the slice. - newCondition = true - } - - // Update the heartbeat time - condition.LastHeartbeatTime = currentTime - - // Note: The conditions below take care of the case when a new NodeMemoryPressure condition is - // created and as well as the case when the condition already exists. When a new condition - // is created its status is set to api.ConditionUnknown which matches either - // condition.Status != api.ConditionTrue or - // condition.Status != api.ConditionFalse in the conditions below depending on whether - // the kubelet is under memory pressure or not. - if kl.evictionManager.IsUnderMemoryPressure() { - if condition.Status != api.ConditionTrue { - condition.Status = api.ConditionTrue - condition.Reason = "KubeletHasInsufficientMemory" - condition.Message = "kubelet has insufficient memory available" - condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasInsufficientMemory") - } - } else { - if condition.Status != api.ConditionFalse { - condition.Status = api.ConditionFalse - condition.Reason = "KubeletHasSufficientMemory" - condition.Message = "kubelet has sufficient memory available" - condition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientMemory") - } - } - - if newCondition { - node.Status.Conditions = append(node.Status.Conditions, *condition) - } -} - -// Set OODcondition for the node. -func (kl *Kubelet) setNodeOODCondition(node *api.Node) { - currentTime := unversioned.NewTime(kl.clock.Now()) - var nodeOODCondition *api.NodeCondition - - // Check if NodeOutOfDisk condition already exists and if it does, just pick it up for update. - for i := range node.Status.Conditions { - if node.Status.Conditions[i].Type == api.NodeOutOfDisk { - nodeOODCondition = &node.Status.Conditions[i] - } - } - - newOODCondition := false - // If the NodeOutOfDisk condition doesn't exist, create one. - if nodeOODCondition == nil { - nodeOODCondition = &api.NodeCondition{ - Type: api.NodeOutOfDisk, - Status: api.ConditionUnknown, - } - // nodeOODCondition cannot be appended to node.Status.Conditions here because it gets - // copied to the slice. So if we append nodeOODCondition to the slice here none of the - // updates we make to nodeOODCondition below are reflected in the slice. - newOODCondition = true - } - - // Update the heartbeat time irrespective of all the conditions. - nodeOODCondition.LastHeartbeatTime = currentTime - - // Note: The conditions below take care of the case when a new NodeOutOfDisk condition is - // created and as well as the case when the condition already exists. When a new condition - // is created its status is set to api.ConditionUnknown which matches either - // nodeOODCondition.Status != api.ConditionTrue or - // nodeOODCondition.Status != api.ConditionFalse in the conditions below depending on whether - // the kubelet is out of disk or not. - if kl.isOutOfDisk() { - if nodeOODCondition.Status != api.ConditionTrue { - nodeOODCondition.Status = api.ConditionTrue - nodeOODCondition.Reason = "KubeletOutOfDisk" - nodeOODCondition.Message = "out of disk space" - nodeOODCondition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeOutOfDisk") - } - } else { - if nodeOODCondition.Status != api.ConditionFalse { - // Update the out of disk condition when the condition status is unknown even if we - // are within the outOfDiskTransitionFrequency duration. We do this to set the - // condition status correctly at kubelet startup. - if nodeOODCondition.Status == api.ConditionUnknown || kl.clock.Since(nodeOODCondition.LastTransitionTime.Time) >= kl.outOfDiskTransitionFrequency { - nodeOODCondition.Status = api.ConditionFalse - nodeOODCondition.Reason = "KubeletHasSufficientDisk" - nodeOODCondition.Message = "kubelet has sufficient disk space available" - nodeOODCondition.LastTransitionTime = currentTime - kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientDisk") - } else { - glog.Infof("Node condition status for OutOfDisk is false, but last transition time is less than %s", kl.outOfDiskTransitionFrequency) - } - } - } - - if newOODCondition { - node.Status.Conditions = append(node.Status.Conditions, *nodeOODCondition) - } -} - -// Maintains Node.Spec.Unschedulable value from previous run of tryUpdateNodeStatus() -var oldNodeUnschedulable bool - -// record if node schedulable change. -func (kl *Kubelet) recordNodeSchedulableEvent(node *api.Node) { - if oldNodeUnschedulable != node.Spec.Unschedulable { - if node.Spec.Unschedulable { - kl.recordNodeStatusEvent(api.EventTypeNormal, kubecontainer.NodeNotSchedulable) - } else { - kl.recordNodeStatusEvent(api.EventTypeNormal, kubecontainer.NodeSchedulable) - } - oldNodeUnschedulable = node.Spec.Unschedulable - } -} - -// Update VolumesInUse field in Node Status -func (kl *Kubelet) setNodeVolumesInUseStatus(node *api.Node) { - node.Status.VolumesInUse = kl.volumeManager.GetVolumesInUse() -} - -// setNodeStatus fills in the Status fields of the given Node, overwriting -// any fields that are currently set. -// TODO(madhusudancs): Simplify the logic for setting node conditions and -// refactor the node status condtion code out to a different file. -func (kl *Kubelet) setNodeStatus(node *api.Node) error { - for _, f := range kl.setNodeStatusFuncs { - if err := f(node); err != nil { - return err - } - } - return nil -} - -// defaultNodeStatusFuncs is a factory that generates the default set of setNodeStatus funcs -func (kl *Kubelet) defaultNodeStatusFuncs() []func(*api.Node) error { - // initial set of node status update handlers, can be modified by Option's - withoutError := func(f func(*api.Node)) func(*api.Node) error { - return func(n *api.Node) error { - f(n) - return nil - } - } - return []func(*api.Node) error{ - kl.setNodeAddress, - withoutError(kl.setNodeStatusInfo), - withoutError(kl.setNodeOODCondition), - withoutError(kl.setNodeMemoryPressureCondition), - withoutError(kl.setNodeReadyCondition), - withoutError(kl.setNodeVolumesInUseStatus), - withoutError(kl.recordNodeSchedulableEvent), - } -} - -// SetNodeStatus returns a functional Option that adds the given node status update handler to the Kubelet -func SetNodeStatus(f func(*api.Node) error) Option { - return func(k *Kubelet) { - k.setNodeStatusFuncs = append(k.setNodeStatusFuncs, f) - } -} - -// tryUpdateNodeStatus tries to update node status to master. If ReconcileCBR0 -// is set, this function will also confirm that cbr0 is configured correctly. -func (kl *Kubelet) tryUpdateNodeStatus() error { - node, err := kl.kubeClient.Core().Nodes().Get(kl.nodeName) - if err != nil { - return fmt.Errorf("error getting node %q: %v", kl.nodeName, err) - } - if node == nil { - return fmt.Errorf("no node instance returned for %q", kl.nodeName) - } - - // Flannel is the authoritative source of pod CIDR, if it's running. - // This is a short term compromise till we get flannel working in - // reservation mode. - if kl.flannelExperimentalOverlay { - flannelPodCIDR := kl.runtimeState.podCIDR() - if node.Spec.PodCIDR != flannelPodCIDR { - node.Spec.PodCIDR = flannelPodCIDR - glog.Infof("Updating podcidr to %v", node.Spec.PodCIDR) - if updatedNode, err := kl.kubeClient.Core().Nodes().Update(node); err != nil { - glog.Warningf("Failed to update podCIDR: %v", err) - } else { - // Update the node resourceVersion so the status update doesn't fail. - node = updatedNode - } - } - } else if kl.reconcileCIDR { - kl.updatePodCIDR(node.Spec.PodCIDR) - } - - if err := kl.setNodeStatus(node); err != nil { - return err - } - // Update the current status on the API server - updatedNode, err := kl.kubeClient.Core().Nodes().UpdateStatus(node) - if err == nil { - kl.volumeManager.MarkVolumesAsReportedInUse( - updatedNode.Status.VolumesInUse) - } - return err -} - // GetPhase returns the phase of a pod given its container info. // This func is exported to simplify integration with 3rd party kubelet // integrations like kubernetes-mesos. @@ -3548,17 +2596,6 @@ func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.P } } - // TODO: Consider include the container information. - // TODO: move this into a sync/evictor - if kl.pastActiveDeadline(pod) { - reason := "DeadlineExceeded" - kl.recorder.Eventf(pod, api.EventTypeNormal, reason, "Pod was active on the node longer than specified deadline") - return api.PodStatus{ - Phase: api.PodFailed, - Reason: reason, - Message: "Pod was active on the node longer than specified deadline"} - } - s := kl.convertStatusToAPIStatus(pod, podStatus) // Assume info is ready to process @@ -3580,7 +2617,7 @@ func (kl *Kubelet) generateAPIPodStatus(pod *api.Pod, podStatus *kubecontainer.P }) if !kl.standaloneMode { - hostIP, err := kl.GetHostIP() + hostIP, err := kl.getHostIPAnyWay() if err != nil { glog.V(4).Infof("Cannot get host IP: %v", err) } else { @@ -3779,7 +2816,7 @@ func (kl *Kubelet) RunInContainer(podFullName string, podUID types.UID, containe var buffer bytes.Buffer output := ioutils.WriteCloserWrapper(&buffer) - err = kl.runner.ExecInContainer(container.ID, cmd, nil, output, output, false) + err = kl.runner.ExecInContainer(container.ID, cmd, nil, output, output, false, nil) if err != nil { return nil, err } @@ -3789,7 +2826,7 @@ func (kl *Kubelet) RunInContainer(podFullName string, podUID types.UID, containe // ExecInContainer executes a command in a container, connecting the supplied // stdin/stdout/stderr to the command's IO streams. -func (kl *Kubelet) ExecInContainer(podFullName string, podUID types.UID, containerName string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (kl *Kubelet) ExecInContainer(podFullName string, podUID types.UID, containerName string, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { podUID = kl.podManager.TranslatePodUID(podUID) container, err := kl.findContainer(podFullName, podUID, containerName) @@ -3799,12 +2836,12 @@ func (kl *Kubelet) ExecInContainer(podFullName string, podUID types.UID, contain if container == nil { return fmt.Errorf("container not found (%q)", containerName) } - return kl.runner.ExecInContainer(container.ID, cmd, stdin, stdout, stderr, tty) + return kl.runner.ExecInContainer(container.ID, cmd, stdin, stdout, stderr, tty, resize) } // AttachContainer uses the container runtime to attach the given streams to // the given container. -func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, containerName string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, containerName string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { podUID = kl.podManager.TranslatePodUID(podUID) container, err := kl.findContainer(podFullName, podUID, containerName) @@ -3814,7 +2851,7 @@ func (kl *Kubelet) AttachContainer(podFullName string, podUID types.UID, contain if container == nil { return fmt.Errorf("container not found (%q)", containerName) } - return kl.containerRuntime.AttachContainer(container.ID, stdin, stdout, stderr, tty) + return kl.containerRuntime.AttachContainer(container.ID, stdin, stdout, stderr, tty, resize) } // PortForward connects to the pod's port and copies data between the port @@ -3836,7 +2873,7 @@ func (kl *Kubelet) PortForward(podFullName string, podUID types.UID, port uint16 // BirthCry sends an event that the kubelet has started up. func (kl *Kubelet) BirthCry() { // Make an event that kubelet restarted. - kl.recorder.Eventf(kl.nodeRef, api.EventTypeNormal, kubecontainer.StartingKubelet, "Starting kubelet.") + kl.recorder.Eventf(kl.nodeRef, api.EventTypeNormal, events.StartingKubelet, "Starting kubelet.") } // StreamingConnectionIdleTimeout returns the timeout for streaming connections to the HTTP server. @@ -3859,28 +2896,8 @@ func (kl *Kubelet) ListenAndServeReadOnly(address net.IP, port uint) { server.ListenAndServeKubeletReadOnlyServer(kl, kl.resourceAnalyzer, address, port, kl.containerRuntime) } -// updatePodCIDR updates the pod CIDR in the runtime state if it is different -// from the current CIDR. -func (kl *Kubelet) updatePodCIDR(cidr string) { - if kl.runtimeState.podCIDR() == cidr { - return - } - - glog.Infof("Setting Pod CIDR: %v -> %v", kl.runtimeState.podCIDR(), cidr) - kl.runtimeState.setPodCIDR(cidr) - - if kl.networkPlugin != nil { - details := make(map[string]interface{}) - details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = cidr - kl.networkPlugin.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, details) - } -} - -// shapingEnabled returns whether traffic shaping is enabled. -func (kl *Kubelet) shapingEnabled() bool { - // Disable shaping if a network plugin is defined and supports shaping - if kl.networkPlugin != nil && kl.networkPlugin.Capabilities().Has(network.NET_PLUGIN_CAPABILITY_SHAPING) { - return false - } - return true +// Filter out events that are not worthy of pod syncing +func isSyncPodWorthy(event *pleg.PodLifecycleEvent) bool { + // ContatnerRemoved doesn't affect pod state + return event.Type != pleg.ContainerRemoved } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_cadvisor.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_cadvisor.go index 76bf6ceb343c..be1876a84a56 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_cadvisor.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_cadvisor.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -45,6 +45,19 @@ func (kl *Kubelet) GetContainerInfo(podFullName string, podUID types.UID, contai return &ci, nil } +// HasDedicatedImageFs returns true if the imagefs has a dedicated device. +func (kl *Kubelet) HasDedicatedImageFs() (bool, error) { + imageFsInfo, err := kl.ImagesFsInfo() + if err != nil { + return false, err + } + rootFsInfo, err := kl.RootFsInfo() + if err != nil { + return false, err + } + return imageFsInfo.Device != rootFsInfo.Device, nil +} + // GetContainerInfoV2 returns stats (from Cadvisor) for containers. func (kl *Kubelet) GetContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) { return kl.cadvisor.ContainerInfoV2(name, options) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters.go index 8d3377c0846c..8d8b6b870655 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network.go new file mode 100644 index 000000000000..59548dfe9fb1 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network.go @@ -0,0 +1,305 @@ +/* +Copyright 2016 The Kubernetes 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 kubelet + +import ( + "fmt" + "io" + "io/ioutil" + "net" + "strings" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/componentconfig" + "k8s.io/kubernetes/pkg/kubelet/network" + "k8s.io/kubernetes/pkg/util/bandwidth" + "k8s.io/kubernetes/pkg/util/sets" +) + +// effectiveHairpinMode determines the effective hairpin mode given the +// configured mode, container runtime, and whether cbr0 should be configured. +func effectiveHairpinMode(hairpinMode componentconfig.HairpinMode, containerRuntime string, configureCBR0 bool, networkPlugin string) (componentconfig.HairpinMode, error) { + // The hairpin mode setting doesn't matter if: + // - We're not using a bridge network. This is hard to check because we might + // be using a plugin. It matters if --configure-cbr0=true, and we currently + // don't pipe it down to any plugins. + // - It's set to hairpin-veth for a container runtime that doesn't know how + // to set the hairpin flag on the veth's of containers. Currently the + // docker runtime is the only one that understands this. + // - It's set to "none". + if hairpinMode == componentconfig.PromiscuousBridge || hairpinMode == componentconfig.HairpinVeth { + // Only on docker. + if containerRuntime != "docker" { + glog.Warningf("Hairpin mode set to %q but container runtime is %q, ignoring", hairpinMode, containerRuntime) + return componentconfig.HairpinNone, nil + } + if hairpinMode == componentconfig.PromiscuousBridge && !configureCBR0 && networkPlugin != "kubenet" { + // This is not a valid combination. Users might be using the + // default values (from before the hairpin-mode flag existed) and we + // should keep the old behavior. + glog.Warningf("Hairpin mode set to %q but configureCBR0 is false, falling back to %q", hairpinMode, componentconfig.HairpinVeth) + return componentconfig.HairpinVeth, nil + } + } else if hairpinMode == componentconfig.HairpinNone { + if configureCBR0 { + glog.Warningf("Hairpin mode set to %q and configureCBR0 is true, this might result in loss of hairpin packets", hairpinMode) + } + } else { + return "", fmt.Errorf("unknown value: %q", hairpinMode) + } + return hairpinMode, nil +} + +// Validate given node IP belongs to the current host +func (kl *Kubelet) validateNodeIP() error { + if kl.nodeIP == nil { + return nil + } + + // Honor IP limitations set in setNodeStatus() + if kl.nodeIP.IsLoopback() { + return fmt.Errorf("nodeIP can't be loopback address") + } + if kl.nodeIP.To4() == nil { + return fmt.Errorf("nodeIP must be IPv4 address") + } + + addrs, err := net.InterfaceAddrs() + if err != nil { + return err + } + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + if ip != nil && ip.Equal(kl.nodeIP) { + return nil + } + } + return fmt.Errorf("Node IP: %q not found in the host's network interfaces", kl.nodeIP.String()) +} + +// providerRequiresNetworkingConfiguration returns whether the cloud provider +// requires special networking configuration. +func (kl *Kubelet) providerRequiresNetworkingConfiguration() bool { + // TODO: We should have a mechanism to say whether native cloud provider + // is used or whether we are using overlay networking. We should return + // true for cloud providers if they implement Routes() interface and + // we are not using overlay networking. + if kl.cloud == nil || kl.cloud.ProviderName() != "gce" || kl.flannelExperimentalOverlay { + return false + } + _, supported := kl.cloud.Routes() + return supported +} + +// Returns the list of DNS servers and DNS search domains. +func (kl *Kubelet) parseResolvConf(reader io.Reader) (nameservers []string, searches []string, err error) { + var scrubber dnsScrubber + if kl.cloud != nil { + scrubber = kl.cloud + } + return parseResolvConf(reader, scrubber) +} + +// A helper for testing. +type dnsScrubber interface { + ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string) +} + +// parseResolveConf reads a resolv.conf file from the given reader, and parses +// it into nameservers and searches, possibly returning an error. The given +// dnsScrubber allows cloud providers to post-process dns names. +// TODO: move to utility package +func parseResolvConf(reader io.Reader, dnsScrubber dnsScrubber) (nameservers []string, searches []string, err error) { + file, err := ioutil.ReadAll(reader) + if err != nil { + return nil, nil, err + } + + // Lines of the form "nameserver 1.2.3.4" accumulate. + nameservers = []string{} + + // Lines of the form "search example.com" overrule - last one wins. + searches = []string{} + + lines := strings.Split(string(file), "\n") + for l := range lines { + trimmed := strings.TrimSpace(lines[l]) + if strings.HasPrefix(trimmed, "#") { + continue + } + fields := strings.Fields(trimmed) + if len(fields) == 0 { + continue + } + if fields[0] == "nameserver" { + nameservers = append(nameservers, fields[1:]...) + } + if fields[0] == "search" { + searches = fields[1:] + } + } + + // Give the cloud-provider a chance to post-process DNS settings. + if dnsScrubber != nil { + nameservers, searches = dnsScrubber.ScrubDNS(nameservers, searches) + } + return nameservers, searches, nil +} + +// cleanupBandwidthLimits updates the status of bandwidth-limited containers +// and ensures that only the the appropriate CIDRs are active on the node. +func (kl *Kubelet) cleanupBandwidthLimits(allPods []*api.Pod) error { + if kl.shaper == nil { + return nil + } + currentCIDRs, err := kl.shaper.GetCIDRs() + if err != nil { + return err + } + possibleCIDRs := sets.String{} + for ix := range allPods { + pod := allPods[ix] + ingress, egress, err := bandwidth.ExtractPodBandwidthResources(pod.Annotations) + if err != nil { + return err + } + if ingress == nil && egress == nil { + glog.V(8).Infof("Not a bandwidth limited container...") + continue + } + status, found := kl.statusManager.GetPodStatus(pod.UID) + if !found { + // TODO(random-liu): Cleanup status get functions. (issue #20477) + s, err := kl.containerRuntime.GetPodStatus(pod.UID, pod.Name, pod.Namespace) + if err != nil { + return err + } + status = kl.generateAPIPodStatus(pod, s) + } + if status.Phase == api.PodRunning { + possibleCIDRs.Insert(fmt.Sprintf("%s/32", status.PodIP)) + } + } + for _, cidr := range currentCIDRs { + if !possibleCIDRs.Has(cidr) { + glog.V(2).Infof("Removing CIDR: %s (%v)", cidr, possibleCIDRs) + if err := kl.shaper.Reset(cidr); err != nil { + return err + } + } + } + return nil +} + +// TODO: remove when kubenet plugin is ready +// NOTE!!! if you make changes here, also make them to kubenet +func (kl *Kubelet) reconcileCBR0(podCIDR string) error { + if podCIDR == "" { + glog.V(5).Info("PodCIDR not set. Will not configure cbr0.") + return nil + } + glog.V(5).Infof("PodCIDR is set to %q", podCIDR) + _, cidr, err := net.ParseCIDR(podCIDR) + if err != nil { + return err + } + // Set cbr0 interface address to first address in IPNet + cidr.IP.To4()[3] += 1 + if err := ensureCbr0(cidr, kl.hairpinMode == componentconfig.PromiscuousBridge, kl.babysitDaemons); err != nil { + return err + } + if kl.shapingEnabled() { + if kl.shaper == nil { + glog.V(5).Info("Shaper is nil, creating") + kl.shaper = bandwidth.NewTCShaper("cbr0") + } + return kl.shaper.ReconcileInterface() + } + return nil +} + +// syncNetworkStatus updates the network state, ensuring that the network is +// configured correctly if the kubelet is set to configure cbr0: +// * handshake flannel helper if the flannel experimental overlay is being used. +// * ensure that iptables masq rules are setup +// * reconcile cbr0 with the pod CIDR +func (kl *Kubelet) syncNetworkStatus() { + var err error + if kl.configureCBR0 { + if kl.flannelExperimentalOverlay { + podCIDR, err := kl.flannelHelper.Handshake() + if err != nil { + glog.Infof("Flannel server handshake failed %v", err) + return + } + kl.updatePodCIDR(podCIDR) + } + if err := ensureIPTablesMasqRule(kl.nonMasqueradeCIDR); err != nil { + err = fmt.Errorf("Error on adding ip table rules: %v", err) + glog.Error(err) + kl.runtimeState.setNetworkState(err) + return + } + podCIDR := kl.runtimeState.podCIDR() + if len(podCIDR) == 0 { + err = fmt.Errorf("ConfigureCBR0 requested, but PodCIDR not set. Will not configure CBR0 right now") + glog.Warning(err) + } else if err = kl.reconcileCBR0(podCIDR); err != nil { + err = fmt.Errorf("Error configuring cbr0: %v", err) + glog.Error(err) + } + if err != nil { + kl.runtimeState.setNetworkState(err) + return + } + } + + kl.runtimeState.setNetworkState(kl.networkPlugin.Status()) +} + +// updatePodCIDR updates the pod CIDR in the runtime state if it is different +// from the current CIDR. +func (kl *Kubelet) updatePodCIDR(cidr string) { + if kl.runtimeState.podCIDR() == cidr { + return + } + + glog.Infof("Setting Pod CIDR: %v -> %v", kl.runtimeState.podCIDR(), cidr) + kl.runtimeState.setPodCIDR(cidr) + + if kl.networkPlugin != nil { + details := make(map[string]interface{}) + details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = cidr + kl.networkPlugin.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, details) + } +} + +// shapingEnabled returns whether traffic shaping is enabled. +func (kl *Kubelet) shapingEnabled() bool { + // Disable shaping if a network plugin is defined and supports shaping + if kl.networkPlugin != nil && kl.networkPlugin.Capabilities().Has(network.NET_PLUGIN_CAPABILITY_SHAPING) { + return false + } + return true +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go new file mode 100644 index 000000000000..80182d4416b2 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go @@ -0,0 +1,774 @@ +/* +Copyright 2016 The Kubernetes 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 kubelet + +import ( + "fmt" + "math" + "net" + goRuntime "runtime" + "sort" + "strings" + "time" + + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api" + apierrors "k8s.io/kubernetes/pkg/api/errors" + "k8s.io/kubernetes/pkg/api/resource" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/cloudprovider" + "k8s.io/kubernetes/pkg/kubelet/cadvisor" + "k8s.io/kubernetes/pkg/kubelet/events" + utilnet "k8s.io/kubernetes/pkg/util/net" + "k8s.io/kubernetes/pkg/version" + "k8s.io/kubernetes/pkg/volume/util/volumehelper" +) + +// registerWithApiserver registers the node with the cluster master. It is safe +// to call multiple times, but not concurrently (kl.registrationCompleted is +// not locked). +func (kl *Kubelet) registerWithApiserver() { + if kl.registrationCompleted { + return + } + step := 100 * time.Millisecond + for { + time.Sleep(step) + step = step * 2 + if step >= 7*time.Second { + step = 7 * time.Second + } + + node, err := kl.initialNodeStatus() + if err != nil { + glog.Errorf("Unable to construct api.Node object for kubelet: %v", err) + continue + } + + glog.V(2).Infof("Attempting to register node %s", node.Name) + if _, err := kl.kubeClient.Core().Nodes().Create(node); err != nil { + if !apierrors.IsAlreadyExists(err) { + glog.V(2).Infof("Unable to register %s with the apiserver: %v", node.Name, err) + continue + } + currentNode, err := kl.kubeClient.Core().Nodes().Get(kl.nodeName) + if err != nil { + glog.Errorf("error getting node %q: %v", kl.nodeName, err) + continue + } + if currentNode == nil { + glog.Errorf("no node instance returned for %q", kl.nodeName) + continue + } + if currentNode.Spec.ExternalID == node.Spec.ExternalID { + glog.Infof("Node %s was previously registered", node.Name) + kl.registrationCompleted = true + return + } + glog.Errorf( + "Previously %q had externalID %q; now it is %q; will delete and recreate.", + kl.nodeName, node.Spec.ExternalID, currentNode.Spec.ExternalID, + ) + if err := kl.kubeClient.Core().Nodes().Delete(node.Name, nil); err != nil { + glog.Errorf("Unable to delete old node: %v", err) + } else { + glog.Errorf("Deleted old node object %q", kl.nodeName) + } + continue + } + glog.Infof("Successfully registered node %s", node.Name) + kl.registrationCompleted = true + return + } +} + +// initialNodeStatus determines the initial node status, incorporating node +// labels and information from the cloud provider. +func (kl *Kubelet) initialNodeStatus() (*api.Node, error) { + node := &api.Node{ + ObjectMeta: api.ObjectMeta{ + Name: kl.nodeName, + Labels: map[string]string{ + unversioned.LabelHostname: kl.hostname, + unversioned.LabelOS: goRuntime.GOOS, + unversioned.LabelArch: goRuntime.GOARCH, + }, + }, + Spec: api.NodeSpec{ + Unschedulable: !kl.registerSchedulable, + }, + } + // Initially, set NodeNetworkUnavailable to true. + if kl.providerRequiresNetworkingConfiguration() { + node.Status.Conditions = append(node.Status.Conditions, api.NodeCondition{ + Type: api.NodeNetworkUnavailable, + Status: api.ConditionTrue, + Reason: "NoRouteCreated", + Message: "Node created without a route", + LastTransitionTime: unversioned.NewTime(kl.clock.Now()), + }) + } + + if kl.enableControllerAttachDetach { + if node.Annotations == nil { + node.Annotations = make(map[string]string) + } + + node.Annotations[volumehelper.ControllerManagedAttachAnnotation] = "true" + } + + // @question: should this be place after the call to the cloud provider? which also applies labels + for k, v := range kl.nodeLabels { + if cv, found := node.ObjectMeta.Labels[k]; found { + glog.Warningf("the node label %s=%s will overwrite default setting %s", k, v, cv) + } + node.ObjectMeta.Labels[k] = v + } + + if kl.cloud != nil { + instances, ok := kl.cloud.Instances() + if !ok { + return nil, fmt.Errorf("failed to get instances from cloud provider") + } + + // TODO(roberthbailey): Can we do this without having credentials to talk + // to the cloud provider? + // TODO: ExternalID is deprecated, we'll have to drop this code + externalID, err := instances.ExternalID(kl.nodeName) + if err != nil { + return nil, fmt.Errorf("failed to get external ID from cloud provider: %v", err) + } + node.Spec.ExternalID = externalID + + // TODO: We can't assume that the node has credentials to talk to the + // cloudprovider from arbitrary nodes. At most, we should talk to a + // local metadata server here. + node.Spec.ProviderID, err = cloudprovider.GetInstanceProviderID(kl.cloud, kl.nodeName) + if err != nil { + return nil, err + } + + instanceType, err := instances.InstanceType(kl.nodeName) + if err != nil { + return nil, err + } + if instanceType != "" { + glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelInstanceType, instanceType) + node.ObjectMeta.Labels[unversioned.LabelInstanceType] = instanceType + } + // If the cloud has zone information, label the node with the zone information + zones, ok := kl.cloud.Zones() + if ok { + zone, err := zones.GetZone() + if err != nil { + return nil, fmt.Errorf("failed to get zone from cloud provider: %v", err) + } + if zone.FailureDomain != "" { + glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelZoneFailureDomain, zone.FailureDomain) + node.ObjectMeta.Labels[unversioned.LabelZoneFailureDomain] = zone.FailureDomain + } + if zone.Region != "" { + glog.Infof("Adding node label from cloud provider: %s=%s", unversioned.LabelZoneRegion, zone.Region) + node.ObjectMeta.Labels[unversioned.LabelZoneRegion] = zone.Region + } + } + } else { + node.Spec.ExternalID = kl.hostname + if kl.autoDetectCloudProvider { + // If no cloud provider is defined - use the one detected by cadvisor + info, err := kl.GetCachedMachineInfo() + if err == nil { + kl.updateCloudProviderFromMachineInfo(node, info) + } + } + } + if err := kl.setNodeStatus(node); err != nil { + return nil, err + } + + return node, nil +} + +// syncNodeStatus should be called periodically from a goroutine. +// It synchronizes node status to master, registering the kubelet first if +// necessary. +func (kl *Kubelet) syncNodeStatus() { + if kl.kubeClient == nil { + return + } + if kl.registerNode { + // This will exit immediately if it doesn't need to do anything. + kl.registerWithApiserver() + } + if err := kl.updateNodeStatus(); err != nil { + glog.Errorf("Unable to update node status: %v", err) + } +} + +// updateNodeStatus updates node status to master with retries. +func (kl *Kubelet) updateNodeStatus() error { + for i := 0; i < nodeStatusUpdateRetry; i++ { + if err := kl.tryUpdateNodeStatus(); err != nil { + glog.Errorf("Error updating node status, will retry: %v", err) + } else { + return nil + } + } + return fmt.Errorf("update node status exceeds retry count") +} + +// tryUpdateNodeStatus tries to update node status to master. If ReconcileCBR0 +// is set, this function will also confirm that cbr0 is configured correctly. +func (kl *Kubelet) tryUpdateNodeStatus() error { + node, err := kl.kubeClient.Core().Nodes().Get(kl.nodeName) + if err != nil { + return fmt.Errorf("error getting node %q: %v", kl.nodeName, err) + } + if node == nil { + return fmt.Errorf("no node instance returned for %q", kl.nodeName) + } + + // Flannel is the authoritative source of pod CIDR, if it's running. + // This is a short term compromise till we get flannel working in + // reservation mode. + if kl.flannelExperimentalOverlay { + flannelPodCIDR := kl.runtimeState.podCIDR() + if node.Spec.PodCIDR != flannelPodCIDR { + node.Spec.PodCIDR = flannelPodCIDR + glog.Infof("Updating podcidr to %v", node.Spec.PodCIDR) + if updatedNode, err := kl.kubeClient.Core().Nodes().Update(node); err != nil { + glog.Warningf("Failed to update podCIDR: %v", err) + } else { + // Update the node resourceVersion so the status update doesn't fail. + node = updatedNode + } + } + } else if kl.reconcileCIDR { + kl.updatePodCIDR(node.Spec.PodCIDR) + } + + if err := kl.setNodeStatus(node); err != nil { + return err + } + // Update the current status on the API server + updatedNode, err := kl.kubeClient.Core().Nodes().UpdateStatus(node) + if err == nil { + kl.volumeManager.MarkVolumesAsReportedInUse( + updatedNode.Status.VolumesInUse) + } + return err +} + +// recordNodeStatusEvent records an event of the given type with the given +// message for the node. +func (kl *Kubelet) recordNodeStatusEvent(eventtype, event string) { + glog.V(2).Infof("Recording %s event message for node %s", event, kl.nodeName) + // TODO: This requires a transaction, either both node status is updated + // and event is recorded or neither should happen, see issue #6055. + kl.recorder.Eventf(kl.nodeRef, eventtype, event, "Node %s status is now: %s", kl.nodeName, event) +} + +// Set addresses for the node. +func (kl *Kubelet) setNodeAddress(node *api.Node) error { + // Set addresses for the node. + if kl.cloud != nil { + instances, ok := kl.cloud.Instances() + if !ok { + return fmt.Errorf("failed to get instances from cloud provider") + } + // TODO(roberthbailey): Can we do this without having credentials to talk + // to the cloud provider? + // TODO(justinsb): We can if CurrentNodeName() was actually CurrentNode() and returned an interface + nodeAddresses, err := instances.NodeAddresses(kl.nodeName) + if err != nil { + return fmt.Errorf("failed to get node address from cloud provider: %v", err) + } + node.Status.Addresses = nodeAddresses + } else { + if kl.nodeIP != nil { + node.Status.Addresses = []api.NodeAddress{ + {Type: api.NodeLegacyHostIP, Address: kl.nodeIP.String()}, + {Type: api.NodeInternalIP, Address: kl.nodeIP.String()}, + } + } else if addr := net.ParseIP(kl.hostname); addr != nil { + node.Status.Addresses = []api.NodeAddress{ + {Type: api.NodeLegacyHostIP, Address: addr.String()}, + {Type: api.NodeInternalIP, Address: addr.String()}, + } + } else { + addrs, err := net.LookupIP(node.Name) + if err != nil { + return fmt.Errorf("can't get ip address of node %s: %v", node.Name, err) + } else if len(addrs) == 0 { + return fmt.Errorf("no ip address for node %v", node.Name) + } else { + // check all ip addresses for this node.Name and try to find the first non-loopback IPv4 address. + // If no match is found, it uses the IP of the interface with gateway on it. + for _, ip := range addrs { + if ip.IsLoopback() { + continue + } + + if ip.To4() != nil { + node.Status.Addresses = []api.NodeAddress{ + {Type: api.NodeLegacyHostIP, Address: ip.String()}, + {Type: api.NodeInternalIP, Address: ip.String()}, + } + break + } + } + + if len(node.Status.Addresses) == 0 { + ip, err := utilnet.ChooseHostInterface() + if err != nil { + return err + } + + node.Status.Addresses = []api.NodeAddress{ + {Type: api.NodeLegacyHostIP, Address: ip.String()}, + {Type: api.NodeInternalIP, Address: ip.String()}, + } + } + } + } + } + return nil +} + +func (kl *Kubelet) setNodeStatusMachineInfo(node *api.Node) { + // TODO: Post NotReady if we cannot get MachineInfo from cAdvisor. This needs to start + // cAdvisor locally, e.g. for test-cmd.sh, and in integration test. + info, err := kl.GetCachedMachineInfo() + if err != nil { + // TODO(roberthbailey): This is required for test-cmd.sh to pass. + // See if the test should be updated instead. + node.Status.Capacity = api.ResourceList{ + api.ResourceCPU: *resource.NewMilliQuantity(0, resource.DecimalSI), + api.ResourceMemory: resource.MustParse("0Gi"), + api.ResourcePods: *resource.NewQuantity(int64(kl.maxPods), resource.DecimalSI), + api.ResourceNvidiaGPU: *resource.NewQuantity(int64(kl.nvidiaGPUs), resource.DecimalSI), + } + glog.Errorf("Error getting machine info: %v", err) + } else { + node.Status.NodeInfo.MachineID = info.MachineID + node.Status.NodeInfo.SystemUUID = info.SystemUUID + node.Status.Capacity = cadvisor.CapacityFromMachineInfo(info) + if kl.podsPerCore > 0 { + node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( + int64(math.Min(float64(info.NumCores*kl.podsPerCore), float64(kl.maxPods))), resource.DecimalSI) + } else { + node.Status.Capacity[api.ResourcePods] = *resource.NewQuantity( + int64(kl.maxPods), resource.DecimalSI) + } + node.Status.Capacity[api.ResourceNvidiaGPU] = *resource.NewQuantity( + int64(kl.nvidiaGPUs), resource.DecimalSI) + if node.Status.NodeInfo.BootID != "" && + node.Status.NodeInfo.BootID != info.BootID { + // TODO: This requires a transaction, either both node status is updated + // and event is recorded or neither should happen, see issue #6055. + kl.recorder.Eventf(kl.nodeRef, api.EventTypeWarning, events.NodeRebooted, + "Node %s has been rebooted, boot id: %s", kl.nodeName, info.BootID) + } + node.Status.NodeInfo.BootID = info.BootID + } + + // Set Allocatable. + node.Status.Allocatable = make(api.ResourceList) + for k, v := range node.Status.Capacity { + value := *(v.Copy()) + if kl.reservation.System != nil { + value.Sub(kl.reservation.System[k]) + } + if kl.reservation.Kubernetes != nil { + value.Sub(kl.reservation.Kubernetes[k]) + } + if value.Sign() < 0 { + // Negative Allocatable resources don't make sense. + value.Set(0) + } + node.Status.Allocatable[k] = value + } +} + +// Set versioninfo for the node. +func (kl *Kubelet) setNodeStatusVersionInfo(node *api.Node) { + verinfo, err := kl.cadvisor.VersionInfo() + if err != nil { + glog.Errorf("Error getting version info: %v", err) + } else { + node.Status.NodeInfo.KernelVersion = verinfo.KernelVersion + node.Status.NodeInfo.OSImage = verinfo.ContainerOsVersion + + runtimeVersion := "Unknown" + if runtimeVer, err := kl.containerRuntime.Version(); err == nil { + runtimeVersion = runtimeVer.String() + } + node.Status.NodeInfo.ContainerRuntimeVersion = fmt.Sprintf("%s://%s", kl.containerRuntime.Type(), runtimeVersion) + + node.Status.NodeInfo.KubeletVersion = version.Get().String() + // TODO: kube-proxy might be different version from kubelet in the future + node.Status.NodeInfo.KubeProxyVersion = version.Get().String() + } + +} + +// Set daemonEndpoints for the node. +func (kl *Kubelet) setNodeStatusDaemonEndpoints(node *api.Node) { + node.Status.DaemonEndpoints = *kl.daemonEndpoints +} + +// Set images list for the node +func (kl *Kubelet) setNodeStatusImages(node *api.Node) { + // Update image list of this node + var imagesOnNode []api.ContainerImage + containerImages, err := kl.imageManager.GetImageList() + if err != nil { + glog.Errorf("Error getting image list: %v", err) + } else { + // sort the images from max to min, and only set top N images into the node status. + sort.Sort(byImageSize(containerImages)) + if maxImagesInNodeStatus < len(containerImages) { + containerImages = containerImages[0:maxImagesInNodeStatus] + } + + for _, image := range containerImages { + imagesOnNode = append(imagesOnNode, api.ContainerImage{ + Names: append(image.RepoTags, image.RepoDigests...), + SizeBytes: image.Size, + }) + } + } + node.Status.Images = imagesOnNode +} + +// Set the GOOS and GOARCH for this node +func (kl *Kubelet) setNodeStatusGoRuntime(node *api.Node) { + node.Status.NodeInfo.OperatingSystem = goRuntime.GOOS + node.Status.NodeInfo.Architecture = goRuntime.GOARCH +} + +// Set status for the node. +func (kl *Kubelet) setNodeStatusInfo(node *api.Node) { + kl.setNodeStatusMachineInfo(node) + kl.setNodeStatusVersionInfo(node) + kl.setNodeStatusDaemonEndpoints(node) + kl.setNodeStatusImages(node) + kl.setNodeStatusGoRuntime(node) +} + +// Set Ready condition for the node. +func (kl *Kubelet) setNodeReadyCondition(node *api.Node) { + // NOTE(aaronlevy): NodeReady condition needs to be the last in the list of node conditions. + // This is due to an issue with version skewed kubelet and master components. + // ref: https://github.com/kubernetes/kubernetes/issues/16961 + currentTime := unversioned.NewTime(kl.clock.Now()) + var newNodeReadyCondition api.NodeCondition + if rs := kl.runtimeState.errors(); len(rs) == 0 { + newNodeReadyCondition = api.NodeCondition{ + Type: api.NodeReady, + Status: api.ConditionTrue, + Reason: "KubeletReady", + Message: "kubelet is posting ready status", + LastHeartbeatTime: currentTime, + } + } else { + newNodeReadyCondition = api.NodeCondition{ + Type: api.NodeReady, + Status: api.ConditionFalse, + Reason: "KubeletNotReady", + Message: strings.Join(rs, ","), + LastHeartbeatTime: currentTime, + } + } + + // Record any soft requirements that were not met in the container manager. + status := kl.containerManager.Status() + if status.SoftRequirements != nil { + newNodeReadyCondition.Message = fmt.Sprintf("%s. WARNING: %s", newNodeReadyCondition.Message, status.SoftRequirements.Error()) + } + + readyConditionUpdated := false + needToRecordEvent := false + for i := range node.Status.Conditions { + if node.Status.Conditions[i].Type == api.NodeReady { + if node.Status.Conditions[i].Status == newNodeReadyCondition.Status { + newNodeReadyCondition.LastTransitionTime = node.Status.Conditions[i].LastTransitionTime + } else { + newNodeReadyCondition.LastTransitionTime = currentTime + needToRecordEvent = true + } + node.Status.Conditions[i] = newNodeReadyCondition + readyConditionUpdated = true + break + } + } + if !readyConditionUpdated { + newNodeReadyCondition.LastTransitionTime = currentTime + node.Status.Conditions = append(node.Status.Conditions, newNodeReadyCondition) + } + if needToRecordEvent { + if newNodeReadyCondition.Status == api.ConditionTrue { + kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeReady) + } else { + kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeNotReady) + } + } +} + +// setNodeMemoryPressureCondition for the node. +// TODO: this needs to move somewhere centralized... +func (kl *Kubelet) setNodeMemoryPressureCondition(node *api.Node) { + currentTime := unversioned.NewTime(kl.clock.Now()) + var condition *api.NodeCondition + + // Check if NodeMemoryPressure condition already exists and if it does, just pick it up for update. + for i := range node.Status.Conditions { + if node.Status.Conditions[i].Type == api.NodeMemoryPressure { + condition = &node.Status.Conditions[i] + } + } + + newCondition := false + // If the NodeMemoryPressure condition doesn't exist, create one + if condition == nil { + condition = &api.NodeCondition{ + Type: api.NodeMemoryPressure, + Status: api.ConditionUnknown, + } + // cannot be appended to node.Status.Conditions here because it gets + // copied to the slice. So if we append to the slice here none of the + // updates we make below are reflected in the slice. + newCondition = true + } + + // Update the heartbeat time + condition.LastHeartbeatTime = currentTime + + // Note: The conditions below take care of the case when a new NodeMemoryPressure condition is + // created and as well as the case when the condition already exists. When a new condition + // is created its status is set to api.ConditionUnknown which matches either + // condition.Status != api.ConditionTrue or + // condition.Status != api.ConditionFalse in the conditions below depending on whether + // the kubelet is under memory pressure or not. + if kl.evictionManager.IsUnderMemoryPressure() { + if condition.Status != api.ConditionTrue { + condition.Status = api.ConditionTrue + condition.Reason = "KubeletHasInsufficientMemory" + condition.Message = "kubelet has insufficient memory available" + condition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasInsufficientMemory") + } + } else { + if condition.Status != api.ConditionFalse { + condition.Status = api.ConditionFalse + condition.Reason = "KubeletHasSufficientMemory" + condition.Message = "kubelet has sufficient memory available" + condition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientMemory") + } + } + + if newCondition { + node.Status.Conditions = append(node.Status.Conditions, *condition) + } +} + +// setNodeDiskPressureCondition for the node. +// TODO: this needs to move somewhere centralized... +func (kl *Kubelet) setNodeDiskPressureCondition(node *api.Node) { + currentTime := unversioned.NewTime(kl.clock.Now()) + var condition *api.NodeCondition + + // Check if NodeDiskPressure condition already exists and if it does, just pick it up for update. + for i := range node.Status.Conditions { + if node.Status.Conditions[i].Type == api.NodeDiskPressure { + condition = &node.Status.Conditions[i] + } + } + + newCondition := false + // If the NodeDiskPressure condition doesn't exist, create one + if condition == nil { + condition = &api.NodeCondition{ + Type: api.NodeDiskPressure, + Status: api.ConditionUnknown, + } + // cannot be appended to node.Status.Conditions here because it gets + // copied to the slice. So if we append to the slice here none of the + // updates we make below are reflected in the slice. + newCondition = true + } + + // Update the heartbeat time + condition.LastHeartbeatTime = currentTime + + // Note: The conditions below take care of the case when a new NodeDiskressure condition is + // created and as well as the case when the condition already exists. When a new condition + // is created its status is set to api.ConditionUnknown which matches either + // condition.Status != api.ConditionTrue or + // condition.Status != api.ConditionFalse in the conditions below depending on whether + // the kubelet is under disk pressure or not. + if kl.evictionManager.IsUnderDiskPressure() { + if condition.Status != api.ConditionTrue { + condition.Status = api.ConditionTrue + condition.Reason = "KubeletHasDiskPressure" + condition.Message = "kubelet has disk pressure" + condition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasDiskPressure") + } + } else { + if condition.Status != api.ConditionFalse { + condition.Status = api.ConditionFalse + condition.Reason = "KubeletHasNoDiskPressure" + condition.Message = "kubelet has no disk pressure" + condition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasNoDiskPressure") + } + } + + if newCondition { + node.Status.Conditions = append(node.Status.Conditions, *condition) + } +} + +// Set OODcondition for the node. +func (kl *Kubelet) setNodeOODCondition(node *api.Node) { + currentTime := unversioned.NewTime(kl.clock.Now()) + var nodeOODCondition *api.NodeCondition + + // Check if NodeOutOfDisk condition already exists and if it does, just pick it up for update. + for i := range node.Status.Conditions { + if node.Status.Conditions[i].Type == api.NodeOutOfDisk { + nodeOODCondition = &node.Status.Conditions[i] + } + } + + newOODCondition := false + // If the NodeOutOfDisk condition doesn't exist, create one. + if nodeOODCondition == nil { + nodeOODCondition = &api.NodeCondition{ + Type: api.NodeOutOfDisk, + Status: api.ConditionUnknown, + } + // nodeOODCondition cannot be appended to node.Status.Conditions here because it gets + // copied to the slice. So if we append nodeOODCondition to the slice here none of the + // updates we make to nodeOODCondition below are reflected in the slice. + newOODCondition = true + } + + // Update the heartbeat time irrespective of all the conditions. + nodeOODCondition.LastHeartbeatTime = currentTime + + // Note: The conditions below take care of the case when a new NodeOutOfDisk condition is + // created and as well as the case when the condition already exists. When a new condition + // is created its status is set to api.ConditionUnknown which matches either + // nodeOODCondition.Status != api.ConditionTrue or + // nodeOODCondition.Status != api.ConditionFalse in the conditions below depending on whether + // the kubelet is out of disk or not. + if kl.isOutOfDisk() { + if nodeOODCondition.Status != api.ConditionTrue { + nodeOODCondition.Status = api.ConditionTrue + nodeOODCondition.Reason = "KubeletOutOfDisk" + nodeOODCondition.Message = "out of disk space" + nodeOODCondition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeOutOfDisk") + } + } else { + if nodeOODCondition.Status != api.ConditionFalse { + // Update the out of disk condition when the condition status is unknown even if we + // are within the outOfDiskTransitionFrequency duration. We do this to set the + // condition status correctly at kubelet startup. + if nodeOODCondition.Status == api.ConditionUnknown || kl.clock.Since(nodeOODCondition.LastTransitionTime.Time) >= kl.outOfDiskTransitionFrequency { + nodeOODCondition.Status = api.ConditionFalse + nodeOODCondition.Reason = "KubeletHasSufficientDisk" + nodeOODCondition.Message = "kubelet has sufficient disk space available" + nodeOODCondition.LastTransitionTime = currentTime + kl.recordNodeStatusEvent(api.EventTypeNormal, "NodeHasSufficientDisk") + } else { + glog.Infof("Node condition status for OutOfDisk is false, but last transition time is less than %s", kl.outOfDiskTransitionFrequency) + } + } + } + + if newOODCondition { + node.Status.Conditions = append(node.Status.Conditions, *nodeOODCondition) + } +} + +// Maintains Node.Spec.Unschedulable value from previous run of tryUpdateNodeStatus() +// TODO: why is this a package var? +var oldNodeUnschedulable bool + +// record if node schedulable change. +func (kl *Kubelet) recordNodeSchedulableEvent(node *api.Node) { + if oldNodeUnschedulable != node.Spec.Unschedulable { + if node.Spec.Unschedulable { + kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeNotSchedulable) + } else { + kl.recordNodeStatusEvent(api.EventTypeNormal, events.NodeSchedulable) + } + oldNodeUnschedulable = node.Spec.Unschedulable + } +} + +// Update VolumesInUse field in Node Status +func (kl *Kubelet) setNodeVolumesInUseStatus(node *api.Node) { + node.Status.VolumesInUse = kl.volumeManager.GetVolumesInUse() +} + +// setNodeStatus fills in the Status fields of the given Node, overwriting +// any fields that are currently set. +// TODO(madhusudancs): Simplify the logic for setting node conditions and +// refactor the node status condtion code out to a different file. +func (kl *Kubelet) setNodeStatus(node *api.Node) error { + for _, f := range kl.setNodeStatusFuncs { + if err := f(node); err != nil { + return err + } + } + return nil +} + +// defaultNodeStatusFuncs is a factory that generates the default set of +// setNodeStatus funcs +func (kl *Kubelet) defaultNodeStatusFuncs() []func(*api.Node) error { + // initial set of node status update handlers, can be modified by Option's + withoutError := func(f func(*api.Node)) func(*api.Node) error { + return func(n *api.Node) error { + f(n) + return nil + } + } + return []func(*api.Node) error{ + kl.setNodeAddress, + withoutError(kl.setNodeStatusInfo), + withoutError(kl.setNodeOODCondition), + withoutError(kl.setNodeMemoryPressureCondition), + withoutError(kl.setNodeDiskPressureCondition), + withoutError(kl.setNodeReadyCondition), + withoutError(kl.setNodeVolumesInUseStatus), + withoutError(kl.recordNodeSchedulableEvent), + } +} + +// SetNodeStatus returns a functional Option that adds the given node status +// update handler to the Kubelet +func SetNodeStatus(f func(*api.Node) error) Option { + return func(k *Kubelet) { + k.setNodeStatusFuncs = append(k.setNodeStatusFuncs, f) + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources.go index b21d840ef3b7..2868f9928707 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes.go index 13323acdbf85..f92d7e363aea 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/leaky/leaky.go b/vendor/k8s.io/kubernetes/pkg/kubelet/leaky/leaky.go index dd4e6efb0345..4e3e1e1f27ca 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/leaky/leaky.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/leaky/leaky.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/doc.go index f398ca060cce..16c90b6899f4 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/fake_handler_runner.go b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/fake_handler_runner.go index 501fb79caa2e..3979204e4255 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/fake_handler_runner.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/fake_handler_runner.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/handlers.go b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/handlers.go index 011a264ad000..6ba3effc6ea6 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/handlers.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/handlers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod msg string ) output := ioutils.WriteCloserWrapper(&buffer) - err := hr.commandRunner.ExecInContainer(containerID, handler.Exec.Command, nil, output, output, false) + err := hr.commandRunner.ExecInContainer(containerID, handler.Exec.Command, nil, output, output, false, nil) if err != nil { msg := fmt.Sprintf("Exec lifecycle hook (%v) for Container %q in Pod %q failed - %q", handler.Exec.Command, container.Name, format.Pod(pod), buffer.String()) glog.V(1).Infof(msg) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/interfaces.go b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/interfaces.go index 0dedd4510a71..38ee01825fe1 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/lifecycle/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/metrics/metrics.go b/vendor/k8s.io/kubernetes/pkg/kubelet/metrics/metrics.go index 7d8294c1503b..7461a7365778 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/metrics/metrics.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/metrics/metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/cni/cni.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/cni/cni.go index cb45c2b20d85..13d1e91653f1 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/cni/cni.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/cni/cni.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,8 +17,11 @@ limitations under the License. package cni import ( + "errors" "fmt" "sort" + "sync" + "time" "github.com/appc/cni/libcni" cnitypes "github.com/appc/cni/pkg/types" @@ -27,6 +30,7 @@ import ( kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/network" utilexec "k8s.io/kubernetes/pkg/util/exec" + "k8s.io/kubernetes/pkg/util/wait" ) const ( @@ -39,11 +43,14 @@ const ( type cniNetworkPlugin struct { network.NoopNetworkPlugin - loNetwork *cniNetwork + loNetwork *cniNetwork + + sync.RWMutex defaultNetwork *cniNetwork - host network.Host - execer utilexec.Interface - nsenterPath string + + host network.Host + execer utilexec.Interface + nsenterPath string } type cniNetwork struct { @@ -53,16 +60,19 @@ type cniNetwork struct { } func probeNetworkPluginsWithVendorCNIDirPrefix(pluginDir, vendorCNIDirPrefix string) []network.NetworkPlugin { - configList := make([]network.NetworkPlugin, 0) - network, err := getDefaultCNINetwork(pluginDir, vendorCNIDirPrefix) - if err != nil { - return configList - } - return append(configList, &cniNetworkPlugin{ - defaultNetwork: network, + plugin := &cniNetworkPlugin{ + defaultNetwork: nil, loNetwork: getLoNetwork(vendorCNIDirPrefix), execer: utilexec.New(), - }) + } + + plugin.syncNetworkConfig(pluginDir, vendorCNIDirPrefix) + // sync network config from pluginDir periodically to detect network config updates + go wait.Forever(func() { + plugin.syncNetworkConfig(pluginDir, vendorCNIDirPrefix) + }, 10*time.Second) + + return []network.NetworkPlugin{plugin} } func ProbeNetworkPlugins(pluginDir string) []network.NetworkPlugin { @@ -137,11 +147,42 @@ func (plugin *cniNetworkPlugin) Init(host network.Host, hairpinMode componentcon return nil } +func (plugin *cniNetworkPlugin) syncNetworkConfig(pluginDir, vendorCNIDirPrefix string) { + network, err := getDefaultCNINetwork(pluginDir, vendorCNIDirPrefix) + if err != nil { + glog.Errorf("error updating cni config: %s", err) + return + } + plugin.setDefaultNetwork(network) +} + +func (plugin *cniNetworkPlugin) getDefaultNetwork() *cniNetwork { + plugin.RLock() + defer plugin.RUnlock() + return plugin.defaultNetwork +} + +func (plugin *cniNetworkPlugin) setDefaultNetwork(n *cniNetwork) { + plugin.Lock() + defer plugin.Unlock() + plugin.defaultNetwork = n +} + +func (plugin *cniNetworkPlugin) checkInitialized() error { + if plugin.getDefaultNetwork() == nil { + return errors.New("cni config unintialized") + } + return nil +} + func (plugin *cniNetworkPlugin) Name() string { return CNIPluginName } func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubecontainer.ContainerID) error { + if err := plugin.checkInitialized(); err != nil { + return err + } netnsPath, err := plugin.host.GetRuntime().GetNetNS(id) if err != nil { return fmt.Errorf("CNI failed to retrieve network namespace path: %v", err) @@ -153,7 +194,7 @@ func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubec return err } - _, err = plugin.defaultNetwork.addToNetwork(name, namespace, id, netnsPath) + _, err = plugin.getDefaultNetwork().addToNetwork(name, namespace, id, netnsPath) if err != nil { glog.Errorf("Error while adding to cni network: %s", err) return err @@ -163,12 +204,15 @@ func (plugin *cniNetworkPlugin) SetUpPod(namespace string, name string, id kubec } func (plugin *cniNetworkPlugin) TearDownPod(namespace string, name string, id kubecontainer.ContainerID) error { + if err := plugin.checkInitialized(); err != nil { + return err + } netnsPath, err := plugin.host.GetRuntime().GetNetNS(id) if err != nil { return fmt.Errorf("CNI failed to retrieve network namespace path: %v", err) } - return plugin.defaultNetwork.deleteFromNetwork(name, namespace, id, netnsPath) + return plugin.getDefaultNetwork().deleteFromNetwork(name, namespace, id, netnsPath) } // TODO: Use the addToNetwork function to obtain the IP of the Pod. That will assume idempotent ADD call to the plugin. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec.go index 83d934b57cec..98819740c4bd 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unix.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unix.go index 26847fe768d6..0c97e254b1ff 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unix.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unix.go @@ -1,7 +1,7 @@ // +build !windows /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unsupported.go index e2d4969f7594..126c8151dcc0 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/exec/exec_unsupported.go @@ -1,7 +1,7 @@ // +build windows /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hairpin/hairpin.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hairpin/hairpin.go index b725fbba3af9..1bbcc4969494 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hairpin/hairpin.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hairpin/hairpin.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/fake_iptables.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/fake_iptables.go index 12c7f8bb6184..5b1a1367ae6d 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/fake_iptables.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/fake_iptables.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/hostport.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/hostport.go index 10ce366ec820..86d9594fa400 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/hostport.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/hostport/hostport.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_linux.go index e91b74889cfe..b7de8e68ae33 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_unsupported.go index 50ceb2af088a..28bc88227ed8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/kubenet/kubenet_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/network.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/network.go index 1396d4155853..9f9d4f0b230e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/network.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/network.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/network/plugins.go b/vendor/k8s.io/kubernetes/pkg/kubelet/network/plugins.go index 25c14937e975..e5045824cbea 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/network/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/network/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/networks.go b/vendor/k8s.io/kubernetes/pkg/kubelet/networks.go index 43674f804103..9ab4a137e6ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/networks.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/networks.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher.go b/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher.go index 12dd2c48f5d0..ca4c53d9432c 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/doc.go index c8782ee89835..cda634061c4f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/generic.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/generic.go index e0340bdd106f..1babc45bc7f2 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/generic.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/generic.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import ( kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/metrics" "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" ) @@ -59,7 +59,7 @@ type GenericPLEG struct { // Cache for storing the runtime states required for syncing pods. cache kubecontainer.Cache // For testability. - clock util.Clock + clock clock.Clock // Pods that failed to have their status retrieved during a relist. These pods will be // retried during the next relisting. podsToReinspect map[types.UID]*kubecontainer.Pod @@ -98,7 +98,7 @@ type podRecord struct { type podRecords map[types.UID]*podRecord func NewGenericPLEG(runtime kubecontainer.Runtime, channelCapacity int, - relistPeriod time.Duration, cache kubecontainer.Cache, clock util.Clock) PodLifecycleEventGenerator { + relistPeriod time.Duration, cache kubecontainer.Cache, clock clock.Clock) PodLifecycleEventGenerator { return &GenericPLEG{ relistPeriod: relistPeriod, runtime: runtime, @@ -134,29 +134,25 @@ func (g *GenericPLEG) Healthy() (bool, error) { return true, nil } -func generateEvent(podID types.UID, cid string, oldState, newState plegContainerState) *PodLifecycleEvent { +func generateEvents(podID types.UID, cid string, oldState, newState plegContainerState) []*PodLifecycleEvent { if newState == oldState { return nil } glog.V(4).Infof("GenericPLEG: %v/%v: %v -> %v", podID, cid, oldState, newState) switch newState { case plegContainerRunning: - return &PodLifecycleEvent{ID: podID, Type: ContainerStarted, Data: cid} + return []*PodLifecycleEvent{{ID: podID, Type: ContainerStarted, Data: cid}} case plegContainerExited: - return &PodLifecycleEvent{ID: podID, Type: ContainerDied, Data: cid} + return []*PodLifecycleEvent{{ID: podID, Type: ContainerDied, Data: cid}} case plegContainerUnknown: - return &PodLifecycleEvent{ID: podID, Type: ContainerChanged, Data: cid} + return []*PodLifecycleEvent{{ID: podID, Type: ContainerChanged, Data: cid}} case plegContainerNonExistent: - // We report "ContainerDied" when container was stopped OR removed. We - // may want to distinguish the two cases in the future. switch oldState { case plegContainerExited: // We already reported that the container died before. - return &PodLifecycleEvent{ID: podID, Type: ContainerRemoved, Data: cid} + return []*PodLifecycleEvent{{ID: podID, Type: ContainerRemoved, Data: cid}} default: - // TODO: We may want to generate a ContainerRemoved event as well. - // It's ok now because no one relies on the ContainerRemoved event. - return &PodLifecycleEvent{ID: podID, Type: ContainerDied, Data: cid} + return []*PodLifecycleEvent{{ID: podID, Type: ContainerDied, Data: cid}, {ID: podID, Type: ContainerRemoved, Data: cid}} } default: panic(fmt.Sprintf("unrecognized container state: %v", newState)) @@ -208,8 +204,10 @@ func (g *GenericPLEG) relist() { // Get all containers in the old and the new pod. allContainers := getContainersFromPods(oldPod, pod) for _, container := range allContainers { - e := computeEvent(oldPod, pod, &container.ID) - updateEvents(eventsByPodID, e) + events := computeEvents(oldPod, pod, &container.ID) + for _, e := range events { + updateEvents(eventsByPodID, e) + } } } @@ -250,7 +248,7 @@ func (g *GenericPLEG) relist() { g.podRecords.update(pid) for i := range events { // Filter out events that are not reliable and no other components use yet. - if events[i].Type == ContainerChanged || events[i].Type == ContainerRemoved { + if events[i].Type == ContainerChanged { continue } g.eventChannel <- events[i] @@ -297,7 +295,7 @@ func getContainersFromPods(pods ...*kubecontainer.Pod) []*kubecontainer.Containe return containers } -func computeEvent(oldPod, newPod *kubecontainer.Pod, cid *kubecontainer.ContainerID) *PodLifecycleEvent { +func computeEvents(oldPod, newPod *kubecontainer.Pod, cid *kubecontainer.ContainerID) []*PodLifecycleEvent { var pid types.UID if oldPod != nil { pid = oldPod.ID @@ -306,7 +304,7 @@ func computeEvent(oldPod, newPod *kubecontainer.Pod, cid *kubecontainer.Containe } oldState := getContainerState(oldPod, cid) newState := getContainerState(newPod, cid) - return generateEvent(pid, cid.ID, oldState, newState) + return generateEvents(pid, cid.ID, oldState, newState) } func (g *GenericPLEG) cacheEnabled() bool { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/pleg.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/pleg.go index 01798237286e..78900e4e4b09 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/pleg.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pleg/pleg.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,11 +25,11 @@ type PodLifeCycleEventType string const ( ContainerStarted PodLifeCycleEventType = "ContainerStarted" ContainerDied PodLifeCycleEventType = "ContainerDied" + ContainerRemoved PodLifeCycleEventType = "ContainerRemoved" // PodSync is used to trigger syncing of a pod when the observed change of // the state of the pod cannot be captured by any single event above. PodSync PodLifeCycleEventType = "PodSync" // Do not use the events below because they are disabled in GenericPLEG. - ContainerRemoved PodLifeCycleEventType = "ContainerRemoved" ContainerChanged PodLifeCycleEventType = "ContainerChanged" ) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pod/mirror_client.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pod/mirror_client.go index 94af3250cdd9..f19bc240bcf2 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pod/mirror_client.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pod/mirror_client.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pod/pod_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pod/pod_manager.go index e4241ceb7d00..5fc0603408db 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pod/pod_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pod/pod_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -199,11 +199,6 @@ func (pm *basicManager) GetPodsAndMirrorPods() ([]*api.Pod, []*api.Pod) { return pods, mirrorPods } -// Returns all pods (including mirror pods). -func (pm *basicManager) getAllPods() []*api.Pod { - return append(podsMapToPods(pm.podByUID), podsMapToPods(pm.mirrorPodByUID)...) -} - func (pm *basicManager) GetPodByUID(uid types.UID) (*api.Pod, bool) { pm.lock.RLock() defer pm.lock.RUnlock() diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers.go index 90d1c2c3d842..2c493dde5451 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/kubelet/eviction" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/kubelet/util/queue" @@ -181,7 +182,7 @@ func (p *podWorkers) managePodLoop(podUpdates <-chan UpdatePodOptions) { } if err != nil { glog.Errorf("Error syncing pod %s, skipping: %v", update.Pod.UID, err) - p.recorder.Eventf(update.Pod, api.EventTypeWarning, kubecontainer.FailedSync, "Error syncing pod, skipping: %v", err) + p.recorder.Eventf(update.Pod, api.EventTypeWarning, events.FailedSync, "Error syncing pod, skipping: %v", err) } p.wrapUp(update.Pod.UID, err) } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober.go b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober.go index 82d2eb54689c..5675af15eeed 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/record" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" "k8s.io/kubernetes/pkg/kubelet/prober/results" "k8s.io/kubernetes/pkg/kubelet/util/format" "k8s.io/kubernetes/pkg/kubelet/util/ioutils" @@ -100,12 +101,12 @@ func (pb *prober) probe(probeType probeType, pod *api.Pod, status api.PodStatus, if err != nil { glog.V(1).Infof("%s probe for %q errored: %v", probeType, ctrName, err) if hasRef { - pb.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.ContainerUnhealthy, "%s probe errored: %v", probeType, err) + pb.recorder.Eventf(ref, api.EventTypeWarning, events.ContainerUnhealthy, "%s probe errored: %v", probeType, err) } } else { // result != probe.Success glog.V(1).Infof("%s probe for %q failed (%v): %s", probeType, ctrName, result, output) if hasRef { - pb.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.ContainerUnhealthy, "%s probe failed: %s", probeType, output) + pb.recorder.Eventf(ref, api.EventTypeWarning, events.ContainerUnhealthy, "%s probe failed: %s", probeType, output) } } return results.Failure, err @@ -228,7 +229,7 @@ func (p *prober) newExecInContainer(container api.Container, containerID kubecon return execInContainer{func() ([]byte, error) { var buffer bytes.Buffer output := ioutils.WriteCloserWrapper(&buffer) - err := p.runner.ExecInContainer(containerID, cmd, nil, output, output, false) + err := p.runner.ExecInContainer(containerID, cmd, nil, output, output, false, nil) if err != nil { return nil, err } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober_manager.go index 01218a75df15..389c2d1d621b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/prober_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/results/results_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/results/results_manager.go index 9f9b1938d6fe..28703c6c6bf7 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/results/results_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/results/results_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/worker.go b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/worker.go index 6edd3daa38e7..1bb2e57353bd 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/prober/worker.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/prober/worker.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -138,6 +138,7 @@ func (w *worker) stop() { // doProbe probes the container once and records the result. // Returns whether the worker should continue. func (w *worker) doProbe() (keepGoing bool) { + defer func() { recover() }() // Actually eat panics (HandleCrash takes care of logging) defer runtime.HandleCrash(func(_ interface{}) { keepGoing = true }) status, ok := w.probeManager.statusManager.GetPodStatus(w.pod.UID) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/doc.go index 04a25c907961..ebc1cc598b31 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/policy.go b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/policy.go index 511e629fadfe..ad696f361098 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/policy.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/policy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package qos import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/kubelet/qos/util" ) const ( @@ -36,11 +35,11 @@ const ( // and 1000. Containers with higher OOM scores are killed if the system runs out of memory. // See https://lwn.net/Articles/391222/ for more information. func GetContainerOOMScoreAdjust(pod *api.Pod, container *api.Container, memoryCapacity int64) int { - switch util.GetPodQos(pod) { - case util.Guaranteed: + switch GetPodQOS(pod) { + case Guaranteed: // Guaranteed containers should be the last to get killed. return guaranteedOOMScoreAdj - case util.BestEffort: + case BestEffort: return besteffortOOMScoreAdj } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/util/qos.go b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/qos.go similarity index 86% rename from vendor/k8s.io/kubernetes/pkg/kubelet/qos/util/qos.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/qos/qos.go index 9d7a5786a3b3..2c0d19d044b6 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/util/qos.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/qos.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,19 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -package util +package qos import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" ) -const ( - Guaranteed = "Guaranteed" - Burstable = "Burstable" - BestEffort = "BestEffort" -) - // isResourceGuaranteed returns true if the container's resource requirements are Guaranteed. func isResourceGuaranteed(container *api.Container, resource api.ResourceName) bool { // A container resource is guaranteed if its request == limit. @@ -47,11 +41,11 @@ func isResourceBestEffort(container *api.Container, resource api.ResourceName) b return !hasReq || req.Value() == 0 } -// GetPodQos returns the QoS class of a pod. +// GetPodQOS returns the QoS class of a pod. // A pod is besteffort if none of its containers have specified any requests or limits. // A pod is guaranteed only when requests and limits are specified for all the containers and they are equal. // A pod is burstable if limits and requests do not match across all containers. -func GetPodQos(pod *api.Pod) string { +func GetPodQOS(pod *api.Pod) QOSClass { requests := api.ResourceList{} limits := api.ResourceList{} zeroQuantity := resource.MustParse("0") @@ -105,23 +99,23 @@ func GetPodQos(pod *api.Pod) string { return Burstable } -// QoSList is a set of (resource name, QoS class) pairs. -type QoSList map[api.ResourceName]string +// QOSList is a set of (resource name, QoS class) pairs. +type QOSList map[api.ResourceName]QOSClass -// GetQoS returns a mapping of resource name to QoS class of a container -func GetQoS(container *api.Container) QoSList { - resourceToQoS := QoSList{} +// GetQOS returns a mapping of resource name to QoS class of a container +func GetQOS(container *api.Container) QOSList { + resourceToQOS := QOSList{} for resource := range allResources(container) { switch { case isResourceGuaranteed(container, resource): - resourceToQoS[resource] = Guaranteed + resourceToQOS[resource] = Guaranteed case isResourceBestEffort(container, resource): - resourceToQoS[resource] = BestEffort + resourceToQOS[resource] = BestEffort default: - resourceToQoS[resource] = Burstable + resourceToQOS[resource] = Burstable } } - return resourceToQoS + return resourceToQOS } // supportedComputeResources is the list of supported compute resources diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/qos/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/types.go new file mode 100644 index 000000000000..e52dece45a18 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/qos/types.go @@ -0,0 +1,29 @@ +/* +Copyright 2016 The Kubernetes 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 qos + +// QOSClass defines the supported qos classes of Pods/Containers. +type QOSClass string + +const ( + // Guaranteed is the Guaranteed qos class. + Guaranteed QOSClass = "Guaranteed" + // Burstable is the Burstable qos class. + Burstable QOSClass = "Burstable" + // BestEffort is the BestEffort qos class. + BestEffort QOSClass = "BestEffort" +) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache.go b/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache.go index 2374f159e051..59f2da35633f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/cap.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/cap.go index a00057f9e1c7..bbf7cdb552f9 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/cap.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/cap.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/config.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/config.go index d978847f080d..3af07a3541f3 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/config.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/config.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/container_id.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/container_id.go index 73810ed70a54..ac37c1815c16 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/container_id.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/container_id.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/doc.go index d45fb3f0e190..71fdac61c13f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/image.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/image.go index 0cad258c4fba..e8be07e9c51a 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/image.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/image.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/log.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/log.go index 4213f591fa87..46543820b68f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/log.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/log.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/rkt.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/rkt.go index 969c06ceb007..b71eb2c9b209 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/rkt.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/rkt.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -45,6 +45,8 @@ import ( "k8s.io/kubernetes/pkg/client/record" "k8s.io/kubernetes/pkg/credentialprovider" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" + "k8s.io/kubernetes/pkg/kubelet/events" + "k8s.io/kubernetes/pkg/kubelet/images" "k8s.io/kubernetes/pkg/kubelet/leaky" "k8s.io/kubernetes/pkg/kubelet/lifecycle" "k8s.io/kubernetes/pkg/kubelet/network" @@ -60,6 +62,7 @@ import ( "k8s.io/kubernetes/pkg/util/flowcontrol" "k8s.io/kubernetes/pkg/util/selinux" utilstrings "k8s.io/kubernetes/pkg/util/strings" + "k8s.io/kubernetes/pkg/util/term" utilwait "k8s.io/kubernetes/pkg/util/wait" ) @@ -150,7 +153,7 @@ type Runtime struct { runtimeHelper kubecontainer.RuntimeHelper recorder record.EventRecorder livenessManager proberesults.Manager - imagePuller kubecontainer.ImagePuller + imagePuller images.ImageManager runner kubecontainer.HandlerRunner execer utilexec.Interface os kubecontainer.OSInterface @@ -269,11 +272,7 @@ func New( rkt.runner = lifecycle.NewHandlerRunner(httpClient, rkt, rkt) - if serializeImagePulls { - rkt.imagePuller = kubecontainer.NewSerializedImagePuller(recorder, rkt, imageBackOff) - } else { - rkt.imagePuller = kubecontainer.NewImagePuller(recorder, rkt, imageBackOff) - } + rkt.imagePuller = images.NewImageManager(recorder, rkt, imageBackOff, serializeImagePulls) if err := rkt.getVersions(); err != nil { return nil, fmt.Errorf("rkt: error getting version info: %v", err) @@ -660,7 +659,7 @@ func copyfile(src, dst string) error { if err != nil { return err } - return ioutil.WriteFile(dst, data, 0640) + return ioutil.WriteFile(dst, data, 0644) } // TODO(yifan): Can make rkt handle this when '--net=host'. See https://github.com/coreos/rkt/issues/2430. @@ -756,7 +755,7 @@ func (r *Runtime) newAppcRuntimeApp(pod *api.Pod, podIP string, c api.Container, if requiresPrivileged && !securitycontext.HasPrivilegedRequest(&c) { return fmt.Errorf("cannot make %q: running a custom stage1 requires a privileged security context", format.Pod(pod)) } - if err, _ := r.imagePuller.PullImage(pod, &c, pullSecrets); err != nil { + if err, _ := r.imagePuller.EnsureImageExists(pod, &c, pullSecrets); err != nil { return nil } imgManifest, err := r.getImageManifest(c.Image) @@ -1227,13 +1226,13 @@ func (r *Runtime) generateEvents(runtimePod *kubecontainer.Pod, reason string, f uuid := utilstrings.ShortenString(id.uuid, 8) switch reason { case "Created": - r.recorder.Eventf(ref, api.EventTypeNormal, kubecontainer.CreatedContainer, "Created with rkt id %v", uuid) + r.recorder.Eventf(ref, api.EventTypeNormal, events.CreatedContainer, "Created with rkt id %v", uuid) case "Started": - r.recorder.Eventf(ref, api.EventTypeNormal, kubecontainer.StartedContainer, "Started with rkt id %v", uuid) + r.recorder.Eventf(ref, api.EventTypeNormal, events.StartedContainer, "Started with rkt id %v", uuid) case "Failed": - r.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedToStartContainer, "Failed to start with rkt id %v with error %v", uuid, failure) + r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToStartContainer, "Failed to start with rkt id %v with error %v", uuid, failure) case "Killing": - r.recorder.Eventf(ref, api.EventTypeNormal, kubecontainer.KillingContainer, "Killing with rkt id %v", uuid) + r.recorder.Eventf(ref, api.EventTypeNormal, events.KillingContainer, "Killing with rkt id %v", uuid) default: glog.Errorf("rkt: Unexpected event %q", reason) } @@ -1319,7 +1318,7 @@ func (r *Runtime) RunPod(pod *api.Pod, pullSecrets []api.Secret) error { continue } if prepareErr != nil { - r.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedToCreateContainer, "Failed to create rkt container with error: %v", prepareErr) + r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedToCreateContainer, "Failed to create rkt container with error: %v", prepareErr) continue } containerID := runtimePod.Containers[i].ID @@ -1374,7 +1373,7 @@ func (r *Runtime) runPreStopHook(containerID kubecontainer.ContainerID, pod *api if !ok { glog.Warningf("No ref for container %q", containerID) } else { - r.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedPreStopHook, msg) + r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedPreStopHook, msg) } } return err @@ -1416,7 +1415,7 @@ func (r *Runtime) runPostStartHook(containerID kubecontainer.ContainerID, pod *a if !ok { glog.Warningf("No ref for container %q", containerID) } else { - r.recorder.Eventf(ref, api.EventTypeWarning, kubecontainer.FailedPostStartHook, msg) + r.recorder.Eventf(ref, api.EventTypeWarning, events.FailedPostStartHook, msg) } } return err @@ -1529,9 +1528,10 @@ func (r *Runtime) convertRktPod(rktpod *rktapi.Pod) (*kubecontainer.Pod, error) ID: buildContainerID(&containerID{rktpod.Id, app.Name}), Name: app.Name, // By default, the version returned by rkt API service will be "latest" if not specified. - Image: fmt.Sprintf("%s:%s", app.Image.Name, app.Image.Version), - Hash: containerHash, - State: appStateToContainerState(app.State), + Image: fmt.Sprintf("%s:%s", app.Image.Name, app.Image.Version), + ImageID: app.Image.Id, + Hash: containerHash, + State: appStateToContainerState(app.State), }) } @@ -1855,6 +1855,10 @@ func podDetailsFromServiceFile(serviceFilePath string) (string, string, string, return "", "", "", false, fmt.Errorf("failed to parse pod from file %s", serviceFilePath) } +func (r *Runtime) DeleteContainer(containerID kubecontainer.ContainerID) error { + return fmt.Errorf("unimplemented") +} + // GarbageCollect collects the pods/containers. // After one GC iteration: // - The deleted pods will be removed. @@ -2006,7 +2010,7 @@ func (r *Runtime) removePod(uuid string) error { return errors.NewAggregate(errlist) } -// rktExitError implemets /pkg/util/exec.ExitError interface. +// rktExitError implements /pkg/util/exec.ExitError interface. type rktExitError struct{ *exec.ExitError } var _ utilexec.ExitError = &rktExitError{} @@ -2025,14 +2029,14 @@ func newRktExitError(e error) error { return e } -func (r *Runtime) AttachContainer(containerID kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (r *Runtime) AttachContainer(containerID kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { return fmt.Errorf("unimplemented") } // Note: In rkt, the container ID is in the form of "UUID:appName", where UUID is // the rkt UUID, and appName is the container name. // TODO(yifan): If the rkt is using lkvm as the stage1 image, then this function will fail. -func (r *Runtime) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool) error { +func (r *Runtime) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error { glog.V(4).Infof("Rkt execing in container.") id, err := parseContainerID(containerID) @@ -2053,6 +2057,10 @@ func (r *Runtime) ExecInContainer(containerID kubecontainer.ContainerID, cmd []s // make sure to close the stdout stream defer stdout.Close() + kubecontainer.HandleResizing(resize, func(size term.Size) { + term.SetSize(p.Fd(), size) + }) + if stdin != nil { go io.Copy(p, stdin) } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/systemd.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/systemd.go index aee6998df03c..8655df92a96a 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/systemd.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/systemd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/version.go b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/version.go index 2cf7a6346164..ee8ff11f382d 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/version.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/rkt/version.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_linux.go b/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_linux.go index a694d71ba119..6f74ebb35877 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_unsupported.go b/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_unsupported.go index 826ac34f0489..5e2ee3075230 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/root_context_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/runonce.go b/vendor/k8s.io/kubernetes/pkg/kubelet/runonce.go index bf7ee7fcc57e..9caf530a6a3c 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/runonce.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/runonce.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ func (kl *Kubelet) runOnce(pods []*api.Pod, retryDelay time.Duration) (results [ admitted := []*api.Pod{} for _, pod := range pods { // Check if we can admit the pod. - if ok, reason, message := kl.canAdmitPod(append(admitted, pod), pod); !ok { + if ok, reason, message := kl.canAdmitPod(admitted, pod); !ok { kl.rejectPod(pod, reason, message) } else { admitted = append(admitted, pod) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/runtime.go b/vendor/k8s.io/kubernetes/pkg/kubelet/runtime.go index 63dd0136363f..0f1acbf47c2c 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/runtime.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/runtime.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/auth.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/auth.go index 0ab25512c049..a153ff4e4f3e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/auth.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/auth.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/doc.go index edb357a8e1ae..22774d20d05b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/portforward/constants.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/portforward/constants.go index f438670675fe..1b73be299b4b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/portforward/constants.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/portforward/constants.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/attach.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/attach.go index 0f9ba7ff5e30..372ae54a2106 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/attach.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/attach.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,13 +25,14 @@ import ( "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/term" ) // Attacher knows how to attach to a running container in a pod. type Attacher interface { // AttachContainer attaches to the running container in the pod, copying data between in/out/err // and the container's stdin/stdout/stderr. - AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool) error + AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error } // ServeAttach handles requests to attach to a container. After creating/receiving the required @@ -44,7 +45,7 @@ func ServeAttach(w http.ResponseWriter, req *http.Request, attacher Attacher, po } defer ctx.conn.Close() - err := attacher.AttachContainer(podName, uid, container, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty) + err := attacher.AttachContainer(podName, uid, container, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty, ctx.resizeChan) if err != nil { msg := fmt.Sprintf("error attaching to container: %v", err) runtime.HandleError(errors.New(msg)) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/contants.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/constants.go similarity index 74% rename from vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/contants.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/constants.go index f45cc644032a..33e0dce29a40 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/contants.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/constants.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -31,6 +31,11 @@ const ( // attachment/execution. It is the second version of the subprotocol and // resolves the issues present in the first version. StreamProtocolV2Name = "v2.channel.k8s.io" + + // The SPDY subprotocol "v3.channel.k8s.io" is used for remote command + // attachment/execution. It is the third version of the subprotocol and + // adds support for resizing container terminals. + StreamProtocolV3Name = "v3.channel.k8s.io" ) -var SupportedStreamingProtocols = []string{StreamProtocolV2Name, StreamProtocolV1Name} +var SupportedStreamingProtocols = []string{StreamProtocolV3Name, StreamProtocolV2Name, StreamProtocolV1Name} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/doc.go index 482e9afc1f62..34d8f40eff09 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/exec.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/exec.go index df9a4b5854e0..fcc4c230bf95 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/exec.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/exec.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,13 +26,14 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/types" "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/term" ) // Executor knows how to execute a command in a container in a pod. type Executor interface { // ExecInContainer executes a command in a container in the pod, copying data // between in/out/err and the container's stdin/stdout/stderr. - ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error + ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error } // ServeExec handles requests to execute a command in a container. After @@ -48,7 +49,7 @@ func ServeExec(w http.ResponseWriter, req *http.Request, executor Executor, podN cmd := req.URL.Query()[api.ExecCommandParamm] - err := executor.ExecInContainer(podName, uid, container, cmd, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty) + err := executor.ExecInContainer(podName, uid, container, cmd, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty, ctx.resizeChan) if err != nil { msg := fmt.Sprintf("error executing command in container: %v", err) runtime.HandleError(errors.New(msg)) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/httpstream.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/httpstream.go index 4b0c588e9fa7..ccd0c3f00769 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/httpstream.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/httpstream.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ limitations under the License. package remotecommand import ( + "encoding/json" "errors" "fmt" "io" @@ -27,6 +28,7 @@ import ( "k8s.io/kubernetes/pkg/util/httpstream" "k8s.io/kubernetes/pkg/util/httpstream/spdy" "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/term" "k8s.io/kubernetes/pkg/util/wsstream" "github.com/golang/glog" @@ -87,6 +89,8 @@ type context struct { stdoutStream io.WriteCloser stderrStream io.WriteCloser errorStream io.WriteCloser + resizeStream io.ReadCloser + resizeChan chan term.Size tty bool } @@ -118,10 +122,26 @@ func createStreams(req *http.Request, w http.ResponseWriter, supportedStreamProt return nil, false } + var ctx *context + var ok bool if wsstream.IsWebSocketRequest(req) { - return createWebSocketStreams(req, w, opts, idleTimeout) + ctx, ok = createWebSocketStreams(req, w, opts, idleTimeout) + } else { + ctx, ok = createHttpStreamStreams(req, w, opts, supportedStreamProtocols, idleTimeout, streamCreationTimeout) + } + if !ok { + return nil, false + } + + if ctx.resizeStream != nil { + ctx.resizeChan = make(chan term.Size) + go handleResizeEvents(ctx.resizeStream, ctx.resizeChan) } + return ctx, true +} + +func createHttpStreamStreams(req *http.Request, w http.ResponseWriter, opts *options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*context, bool) { protocol, err := httpstream.Handshake(req, w, supportedStreamProtocols) if err != nil { w.WriteHeader(http.StatusBadRequest) @@ -148,6 +168,8 @@ func createStreams(req *http.Request, w http.ResponseWriter, supportedStreamProt var handler protocolHandler switch protocol { + case StreamProtocolV3Name: + handler = &v3ProtocolHandler{} case StreamProtocolV2Name: handler = &v2ProtocolHandler{} case "": @@ -157,6 +179,10 @@ func createStreams(req *http.Request, w http.ResponseWriter, supportedStreamProt handler = &v1ProtocolHandler{} } + if opts.tty && handler.supportsTerminalResizing() { + opts.expectedStreams++ + } + expired := time.NewTimer(streamCreationTimeout) ctx, err := handler.waitForStreams(streamCh, opts.expectedStreams, expired.C) @@ -167,6 +193,7 @@ func createStreams(req *http.Request, w http.ResponseWriter, supportedStreamProt ctx.conn = conn ctx.tty = opts.tty + return ctx, true } @@ -174,8 +201,61 @@ type protocolHandler interface { // waitForStreams waits for the expected streams or a timeout, returning a // remoteCommandContext if all the streams were received, or an error if not. waitForStreams(streams <-chan streamAndReply, expectedStreams int, expired <-chan time.Time) (*context, error) + // supportsTerminalResizing returns true if the protocol handler supports terminal resizing + supportsTerminalResizing() bool +} + +// v3ProtocolHandler implements the V3 protocol version for streaming command execution. +type v3ProtocolHandler struct{} + +func (*v3ProtocolHandler) waitForStreams(streams <-chan streamAndReply, expectedStreams int, expired <-chan time.Time) (*context, error) { + ctx := &context{} + receivedStreams := 0 + replyChan := make(chan struct{}) + stop := make(chan struct{}) + defer close(stop) +WaitForStreams: + for { + select { + case stream := <-streams: + streamType := stream.Headers().Get(api.StreamType) + switch streamType { + case api.StreamTypeError: + ctx.errorStream = stream + go waitStreamReply(stream.replySent, replyChan, stop) + case api.StreamTypeStdin: + ctx.stdinStream = stream + go waitStreamReply(stream.replySent, replyChan, stop) + case api.StreamTypeStdout: + ctx.stdoutStream = stream + go waitStreamReply(stream.replySent, replyChan, stop) + case api.StreamTypeStderr: + ctx.stderrStream = stream + go waitStreamReply(stream.replySent, replyChan, stop) + case api.StreamTypeResize: + ctx.resizeStream = stream + go waitStreamReply(stream.replySent, replyChan, stop) + default: + runtime.HandleError(fmt.Errorf("Unexpected stream type: %q", streamType)) + } + case <-replyChan: + receivedStreams++ + if receivedStreams == expectedStreams { + break WaitForStreams + } + case <-expired: + // TODO find a way to return the error to the user. Maybe use a separate + // stream to report errors? + return nil, errors.New("timed out waiting for client to create streams") + } + } + + return ctx, nil } +// supportsTerminalResizing returns true because v3ProtocolHandler supports it +func (*v3ProtocolHandler) supportsTerminalResizing() bool { return true } + // v2ProtocolHandler implements the V2 protocol version for streaming command execution. type v2ProtocolHandler struct{} @@ -221,6 +301,9 @@ WaitForStreams: return ctx, nil } +// supportsTerminalResizing returns false because v2ProtocolHandler doesn't support it. +func (*v2ProtocolHandler) supportsTerminalResizing() bool { return false } + // v1ProtocolHandler implements the V1 protocol version for streaming command execution. type v1ProtocolHandler struct{} @@ -275,3 +358,19 @@ WaitForStreams: return ctx, nil } + +// supportsTerminalResizing returns false because v1ProtocolHandler doesn't support it. +func (*v1ProtocolHandler) supportsTerminalResizing() bool { return false } + +func handleResizeEvents(stream io.Reader, channel chan<- term.Size) { + defer runtime.HandleCrash() + + decoder := json.NewDecoder(stream) + for { + size := term.Size{} + if err := decoder.Decode(&size); err != nil { + break + } + channel <- size + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/websocket.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/websocket.go index 06a84c8e7d9e..efeb1b6646e9 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/websocket.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/remotecommand/websocket.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,61 +17,82 @@ limitations under the License. package remotecommand import ( + "fmt" "net/http" "time" "k8s.io/kubernetes/pkg/httplog" + "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/wsstream" +) - "github.com/golang/glog" +const ( + stdinChannel = iota + stdoutChannel + stderrChannel + errorChannel + resizeChannel ) -// standardShellChannels returns the standard channel types for a shell connection (STDIN 0, STDOUT 1, STDERR 2) -// along with the approximate duplex value. Supported subprotocols are "channel.k8s.io" and -// "base64.channel.k8s.io". -func standardShellChannels(stdin, stdout, stderr bool) []wsstream.ChannelType { - // open three half-duplex channels - channels := []wsstream.ChannelType{wsstream.ReadChannel, wsstream.WriteChannel, wsstream.WriteChannel} - if !stdin { - channels[0] = wsstream.IgnoreChannel - } - if !stdout { - channels[1] = wsstream.IgnoreChannel +// createChannels returns the standard channel types for a shell connection (STDIN 0, STDOUT 1, STDERR 2) +// along with the approximate duplex value. It also creates the error (3) and resize (4) channels. +func createChannels(opts *options) []wsstream.ChannelType { + // open the requested channels, and always open the error channel + channels := make([]wsstream.ChannelType, 5) + channels[stdinChannel] = readChannel(opts.stdin) + channels[stdoutChannel] = writeChannel(opts.stdout) + channels[stderrChannel] = writeChannel(opts.stderr) + channels[errorChannel] = wsstream.WriteChannel + channels[resizeChannel] = wsstream.ReadChannel + return channels +} + +// readChannel returns wsstream.ReadChannel if real is true, or wsstream.IgnoreChannel. +func readChannel(real bool) wsstream.ChannelType { + if real { + return wsstream.ReadChannel } - if !stderr { - channels[2] = wsstream.IgnoreChannel + return wsstream.IgnoreChannel +} + +// writeChannel returns wsstream.WriteChannel if real is true, or wsstream.IgnoreChannel. +func writeChannel(real bool) wsstream.ChannelType { + if real { + return wsstream.WriteChannel } - return channels + return wsstream.IgnoreChannel } -// createWebSocketStreams returns a remoteCommandContext containing the websocket connection and +// createWebSocketStreams returns a context containing the websocket connection and // streams needed to perform an exec or an attach. func createWebSocketStreams(req *http.Request, w http.ResponseWriter, opts *options, idleTimeout time.Duration) (*context, bool) { - // open the requested channels, and always open the error channel - channels := append(standardShellChannels(opts.stdin, opts.stdout, opts.stderr), wsstream.WriteChannel) + channels := createChannels(opts) conn := wsstream.NewConn(channels...) conn.SetIdleTimeout(idleTimeout) streams, err := conn.Open(httplog.Unlogged(w), req) if err != nil { - glog.Errorf("Unable to upgrade websocket connection: %v", err) + runtime.HandleError(fmt.Errorf("Unable to upgrade websocket connection: %v", err)) return nil, false } + // Send an empty message to the lowest writable channel to notify the client the connection is established // TODO: make generic to SPDY and WebSockets and do it outside of this method? switch { case opts.stdout: - streams[1].Write([]byte{}) + streams[stdoutChannel].Write([]byte{}) case opts.stderr: - streams[2].Write([]byte{}) + streams[stderrChannel].Write([]byte{}) default: - streams[3].Write([]byte{}) + streams[errorChannel].Write([]byte{}) } + return &context{ conn: conn, - stdinStream: streams[0], - stdoutStream: streams[1], - stderrStream: streams[2], - errorStream: streams[3], + stdinStream: streams[stdinChannel], + stdoutStream: streams[stdoutChannel], + stderrStream: streams[stderrChannel], + errorStream: streams[errorChannel], tty: opts.tty, + resizeStream: streams[resizeChannel], }, true } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/server.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/server.go index f490a5075b11..38b4dad0b0f2 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/server.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/server.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -58,6 +58,7 @@ import ( "k8s.io/kubernetes/pkg/util/httpstream/spdy" "k8s.io/kubernetes/pkg/util/limitwriter" utilruntime "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/util/term" "k8s.io/kubernetes/pkg/volume" ) @@ -160,8 +161,8 @@ type HostInterface interface { GetRunningPods() ([]*api.Pod, error) GetPodByName(namespace, name string) (*api.Pod, bool) RunInContainer(name string, uid types.UID, container string, cmd []string) ([]byte, error) - ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool) error - AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool) error + ExecInContainer(name string, uid types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error + AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error GetKubeletContainerLogs(podFullName, containerName string, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error ServeLogs(w http.ResponseWriter, req *http.Request) PortForward(name string, uid types.UID, port uint16, stream io.ReadWriteCloser) error @@ -220,8 +221,15 @@ func (s *Server) InstallAuthFilter() { attrs := s.auth.GetRequestAttributes(u, req.Request) // Authorize - if err := s.auth.Authorize(attrs); err != nil { - msg := fmt.Sprintf("Forbidden (user=%s, verb=%s, namespace=%s, resource=%s)", u.GetName(), attrs.GetVerb(), attrs.GetNamespace(), attrs.GetResource()) + authorized, reason, err := s.auth.Authorize(attrs) + if err != nil { + msg := fmt.Sprintf("Error (user=%s, verb=%s, namespace=%s, resource=%s)", u.GetName(), attrs.GetVerb(), attrs.GetNamespace(), attrs.GetResource()) + glog.Errorf(msg, err) + resp.WriteErrorString(http.StatusInternalServerError, msg) + return + } + if !authorized { + msg := fmt.Sprintf("Forbidden (reason=%s, user=%s, verb=%s, namespace=%s, resource=%s)", reason, u.GetName(), attrs.GetVerb(), attrs.GetNamespace(), attrs.GetResource()) glog.V(2).Info(msg) resp.WriteErrorString(http.StatusForbidden, msg) return diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/doc.go index 289fdae7064f..f8d987c1ee9d 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/fs_resource_analyzer.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/fs_resource_analyzer.go index c45e34694ada..4cc5c68518f5 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/fs_resource_analyzer.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/fs_resource_analyzer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/handler.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/handler.go index 531d55350a0f..3102d03d455b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/handler.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/handler.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/resource_analyzer.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/resource_analyzer.go index a9e9dbbf0ace..670e7a751aca 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/resource_analyzer.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/resource_analyzer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/summary.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/summary.go index 4b8f326dca54..b0ad72590ca8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/summary.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/summary.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package stats import ( "fmt" - "runtime" "strings" "time" @@ -53,8 +52,6 @@ var _ SummaryProvider = &summaryProviderImpl{} // NewSummaryProvider returns a new SummaryProvider func NewSummaryProvider(statsProvider StatsProvider, fsResourceAnalyzer fsResourceAnalyzerInterface, cruntime container.Runtime) SummaryProvider { - stackBuff := []byte{} - runtime.Stack(stackBuff, false) return &summaryProviderImpl{statsProvider, fsResourceAnalyzer, cruntime} } @@ -127,13 +124,15 @@ func (sb *summaryBuilder) build() (*stats.Summary, error) { Fs: &stats.FsStats{ AvailableBytes: &sb.rootFsInfo.Available, CapacityBytes: &sb.rootFsInfo.Capacity, - UsedBytes: &sb.rootFsInfo.Usage}, + UsedBytes: &sb.rootFsInfo.Usage, + InodesFree: &sb.rootFsInfo.InodesFree}, StartTime: rootStats.StartTime, Runtime: &stats.RuntimeStats{ ImageFs: &stats.FsStats{ AvailableBytes: &sb.imageFsInfo.Available, CapacityBytes: &sb.imageFsInfo.Capacity, UsedBytes: &sb.imageStats.TotalStorageBytes, + InodesFree: &sb.imageFsInfo.InodesFree, }, }, } @@ -165,12 +164,14 @@ func (sb *summaryBuilder) containerInfoV2FsStats( cs.Logs = &stats.FsStats{ AvailableBytes: &sb.rootFsInfo.Available, CapacityBytes: &sb.rootFsInfo.Capacity, + InodesFree: &sb.rootFsInfo.InodesFree, } // The container rootFs lives on the imageFs devices (which may not be the node root fs) cs.Rootfs = &stats.FsStats{ AvailableBytes: &sb.imageFsInfo.Available, CapacityBytes: &sb.imageFsInfo.Capacity, + InodesFree: &sb.imageFsInfo.InodesFree, } lcs, found := sb.latestContainerStats(info) if !found { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_caculator.go b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_calculator.go similarity index 98% rename from vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_caculator.go rename to vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_calculator.go index 65bc6254ce1f..8cdc9f4ea5e1 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_caculator.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/server/stats/volume_stat_calculator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/status/generate.go b/vendor/k8s.io/kubernetes/pkg/kubelet/status/generate.go index cc000929a073..aca89076e282 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/status/generate.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/status/generate.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/status/status_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/status/status_manager.go index 337058df676c..382f18d0035c 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/status/status_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/status/status_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -66,16 +66,22 @@ type manager struct { apiStatusVersions map[types.UID]uint64 } -// status.Manager is the Source of truth for kubelet pod status, and should be kept up-to-date with +// PodStatusProvider knows how to provide status for a pod. It's intended to be used by other components +// that need to introspect status. +type PodStatusProvider interface { + // GetPodStatus returns the cached status for the provided pod UID, as well as whether it + // was a cache hit. + GetPodStatus(uid types.UID) (api.PodStatus, bool) +} + +// Manager is the Source of truth for kubelet pod status, and should be kept up-to-date with // the latest api.PodStatus. It also syncs updates back to the API server. type Manager interface { + PodStatusProvider + // Start the API server status sync loop. Start() - // GetPodStatus returns the cached status for the provided pod UID, as well as whether it - // was a cache hit. - GetPodStatus(uid types.UID) (api.PodStatus, bool) - // SetPodStatus caches updates the cached status for the given pod, and triggers a status update. SetPodStatus(pod *api.Pod, status api.PodStatus) diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/constants.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/constants.go index 060fec752abf..eeabba0174a8 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/constants.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/types/constants.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/doc.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/doc.go index 104ff4e356f8..0d9efe50f029 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/types/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels.go index 24f91f94978d..c4dad6302e55 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update.go index 88bcb54b32e1..e98489df6b1d 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -35,6 +35,8 @@ const ( SET PodOperation = iota // Pods with the given ids are new to this source ADD + // Pods with the given ids are gracefully deleted from this source + DELETE // Pods with the given ids have been removed from this source REMOVE // Pods with the given ids have been updated in this source diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/types.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/types.go index d9102a592f0c..017c3c8cb311 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/types.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/types/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util.go index ae2d94bfa12d..0ddb76a86c56 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package kubelet import ( "fmt" + "os" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/capabilities" @@ -27,7 +28,24 @@ import ( // Check whether we have the capabilities to run the specified pod. func canRunPod(pod *api.Pod) error { - if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork { + if !capabilities.Get().AllowPrivileged { + for _, container := range pod.Spec.Containers { + if securitycontext.HasPrivilegedRequest(&container) { + return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID) + } + } + for _, container := range pod.Spec.InitContainers { + if securitycontext.HasPrivilegedRequest(&container) { + return fmt.Errorf("pod with UID %q specified privileged init container, but is disallowed", pod.UID) + } + } + } + + if pod.Spec.SecurityContext == nil { + return nil + } + + if pod.Spec.SecurityContext.HostNetwork { allowed, err := allowHostNetwork(pod) if err != nil { return err @@ -37,7 +55,7 @@ func canRunPod(pod *api.Pod) error { } } - if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostPID { + if pod.Spec.SecurityContext.HostPID { allowed, err := allowHostPID(pod) if err != nil { return err @@ -47,7 +65,7 @@ func canRunPod(pod *api.Pod) error { } } - if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostIPC { + if pod.Spec.SecurityContext.HostIPC { allowed, err := allowHostIPC(pod) if err != nil { return err @@ -57,18 +75,6 @@ func canRunPod(pod *api.Pod) error { } } - if !capabilities.Get().AllowPrivileged { - for _, container := range pod.Spec.Containers { - if securitycontext.HasPrivilegedRequest(&container) { - return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID) - } - } - for _, container := range pod.Spec.InitContainers { - if securitycontext.HasPrivilegedRequest(&container) { - return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID) - } - } - } return nil } @@ -113,3 +119,12 @@ func allowHostIPC(pod *api.Pod) (bool, error) { } return false, nil } + +// dirExists returns true if the path exists and represents a directory. +func dirExists(path string) bool { + s, err := os.Stat(path) + if err != nil { + return false + } + return s.IsDir() +} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/cache/object_cache.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/cache/object_cache.go index 9bb809c0d06d..a87592122a8c 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/cache/object_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util/cache/object_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/pod.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/pod.go index da69f0e5d3e9..1ec764551808 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/pod.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/pod.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources.go index 4e90c295c86a..f37c4335604f 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/ioutils/ioutils.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/ioutils/ioutils.go index fa700396ecf0..42f1998c794e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/ioutils/ioutils.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util/ioutils/ioutils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/queue/work_queue.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/queue/work_queue.go index 48d0919d9b1f..5ac45c3f2a3a 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/queue/work_queue.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/util/queue/work_queue.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ( "time" "k8s.io/kubernetes/pkg/types" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" ) // WorkQueue allows queuing items with a timestamp. An item is @@ -34,14 +34,14 @@ type WorkQueue interface { } type basicWorkQueue struct { - clock util.Clock + clock clock.Clock lock sync.Mutex queue map[types.UID]time.Time } var _ WorkQueue = &basicWorkQueue{} -func NewBasicWorkQueue(clock util.Clock) WorkQueue { +func NewBasicWorkQueue(clock clock.Clock) WorkQueue { queue := make(map[types.UID]time.Time) return &basicWorkQueue{queue: queue, clock: clock} } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volume_host.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volume_host.go index c12f973b5829..5d48a760b495 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volume_host.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volume_host.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/actual_state_of_world.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/actual_state_of_world.go index 8c23e59e4121..d3906a52e3f0 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/actual_state_of_world.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/actual_state_of_world.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -580,7 +580,8 @@ func (asw *actualStateOfWorld) newAttachedVolume( VolumeName: attachedVolume.volumeName, VolumeSpec: attachedVolume.spec, NodeName: asw.nodeName, - PluginIsAttachable: attachedVolume.pluginIsAttachable}, + PluginIsAttachable: attachedVolume.pluginIsAttachable, + DevicePath: attachedVolume.devicePath}, GloballyMounted: attachedVolume.globallyMounted} } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/desired_state_of_world.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/desired_state_of_world.go index 51cc7900c9d2..24edd5906c0b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/desired_state_of_world.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/cache/desired_state_of_world.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go index 0991c66a8113..66ce288cc61b 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler/reconciler.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler/reconciler.go index 5063379acde1..38e11e231aa7 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler/reconciler.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler/reconciler.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/kubelet/volumemanager/cache" "k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff" + "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations" "k8s.io/kubernetes/pkg/volume/util/operationexecutor" @@ -63,6 +64,7 @@ type Reconciler interface { // operationExecutor - used to trigger attach/detach/mount/unmount operations // safely (prevents more than one operation from being triggered on the same // volume) +// mounter - mounter passed in from kubelet, passed down unmount path func NewReconciler( kubeClient internalclientset.Interface, controllerAttachDetachEnabled bool, @@ -71,7 +73,8 @@ func NewReconciler( hostName string, desiredStateOfWorld cache.DesiredStateOfWorld, actualStateOfWorld cache.ActualStateOfWorld, - operationExecutor operationexecutor.OperationExecutor) Reconciler { + operationExecutor operationexecutor.OperationExecutor, + mounter mount.Interface) Reconciler { return &reconciler{ kubeClient: kubeClient, controllerAttachDetachEnabled: controllerAttachDetachEnabled, @@ -81,6 +84,7 @@ func NewReconciler( desiredStateOfWorld: desiredStateOfWorld, actualStateOfWorld: actualStateOfWorld, operationExecutor: operationExecutor, + mounter: mounter, } } @@ -93,6 +97,7 @@ type reconciler struct { desiredStateOfWorld cache.DesiredStateOfWorld actualStateOfWorld cache.ActualStateOfWorld operationExecutor operationexecutor.OperationExecutor + mounter mount.Interface } func (rc *reconciler) Run(stopCh <-chan struct{}) { @@ -265,7 +270,7 @@ func (rc *reconciler) reconciliationLoopFunc() func() { attachedVolume.VolumeName, attachedVolume.VolumeSpec.Name()) err := rc.operationExecutor.UnmountDevice( - attachedVolume.AttachedVolume, rc.actualStateOfWorld) + attachedVolume.AttachedVolume, rc.actualStateOfWorld, rc.mounter) if err != nil && !nestedpendingoperations.IsAlreadyExists(err) && !exponentialbackoff.IsExponentialBackoff(err) { diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/volume_manager.go b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/volume_manager.go index c3293327f0d6..e4c6b2aa7dcc 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/volume_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/volumemanager/volume_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import ( "k8s.io/kubernetes/pkg/kubelet/volumemanager/cache" "k8s.io/kubernetes/pkg/kubelet/volumemanager/populator" "k8s.io/kubernetes/pkg/kubelet/volumemanager/reconciler" + "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" @@ -136,7 +137,8 @@ func NewVolumeManager( podManager pod.Manager, kubeClient internalclientset.Interface, volumePluginMgr *volume.VolumePluginMgr, - kubeContainerRuntime kubecontainer.Runtime) (VolumeManager, error) { + kubeContainerRuntime kubecontainer.Runtime, + mounter mount.Interface) (VolumeManager, error) { vm := &volumeManager{ kubeClient: kubeClient, volumePluginMgr: volumePluginMgr, @@ -155,7 +157,8 @@ func NewVolumeManager( hostName, vm.desiredStateOfWorld, vm.actualStateOfWorld, - vm.operationExecutor) + vm.operationExecutor, + mounter) vm.desiredStateOfWorldPopulator = populator.NewDesiredStateOfWorldPopulator( kubeClient, desiredStateOfWorldPopulatorLoopSleepPeriod, diff --git a/vendor/k8s.io/kubernetes/pkg/labels/doc.go b/vendor/k8s.io/kubernetes/pkg/labels/doc.go index 0e0282c3579c..35ba78809446 100644 --- a/vendor/k8s.io/kubernetes/pkg/labels/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/labels/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/labels/labels.go b/vendor/k8s.io/kubernetes/pkg/labels/labels.go index 73324ba2bc3d..637a45fd38dc 100644 --- a/vendor/k8s.io/kubernetes/pkg/labels/labels.go +++ b/vendor/k8s.io/kubernetes/pkg/labels/labels.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/labels/selector.go b/vendor/k8s.io/kubernetes/pkg/labels/selector.go index ab64ecc80904..861b6eab8959 100644 --- a/vendor/k8s.io/kubernetes/pkg/labels/selector.go +++ b/vendor/k8s.io/kubernetes/pkg/labels/selector.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -108,7 +108,7 @@ type Requirement struct { // (2) If the operator is In or NotIn, the values set must be non-empty. // (3) If the operator is Equals, DoubleEquals, or NotEquals, the values set must contain one value. // (4) If the operator is Exists or DoesNotExist, the value set must be empty. -// (5) If the operator is Gt or Lt, the values set must contain only one value. +// (5) If the operator is Gt or Lt, the values set must contain only one value, which will be interpreted as an integer. // (6) The key is invalid due to its length, or sequence // of characters. See validateLabelKey for more details. // @@ -135,8 +135,8 @@ func NewRequirement(key string, op Operator, vals sets.String) (*Requirement, er return nil, fmt.Errorf("for 'Gt', 'Lt' operators, exactly one value is required") } for val := range vals { - if _, err := strconv.ParseFloat(val, 64); err != nil { - return nil, fmt.Errorf("for 'Gt', 'Lt' operators, the value must be a number") + if _, err := strconv.ParseInt(val, 10, 64); err != nil { + return nil, fmt.Errorf("for 'Gt', 'Lt' operators, the value must be an integer") } } default: @@ -160,6 +160,8 @@ func NewRequirement(key string, op Operator, vals sets.String) (*Requirement, er // Labels' value for that key is not in Requirement's value set. // (4) The operator is DoesNotExist or NotIn and Labels does not have the // Requirement's key. +// (5) The operator is GreaterThanOperator or LessThanOperator, and Labels has +// the Requirement's key and the corresponding value satisfies mathematical inequality. func (r *Requirement) Matches(ls Labels) bool { switch r.operator { case InOperator, EqualsOperator, DoubleEqualsOperator: @@ -180,23 +182,23 @@ func (r *Requirement) Matches(ls Labels) bool { if !ls.Has(r.key) { return false } - lsValue, err := strconv.ParseFloat(ls.Get(r.key), 64) + lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64) if err != nil { - glog.V(10).Infof("Parse float failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err) + glog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err) return false } - // There should be only one strValue in r.strValues, and can be converted to a float number. + // There should be only one strValue in r.strValues, and can be converted to a integer. if len(r.strValues) != 1 { glog.V(10).Infof("Invalid values count %+v of requirement %+v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r) return false } - var rValue float64 + var rValue int64 for strValue := range r.strValues { - rValue, err = strconv.ParseFloat(strValue, 64) + rValue, err = strconv.ParseInt(strValue, 10, 64) if err != nil { - glog.V(10).Infof("Parse float failed for value %+v in requirement %+v, for 'Gt', 'Lt' operators, the value must be a number", strValue, r) + glog.V(10).Infof("ParseInt failed for value %+v in requirement %+v, for 'Gt', 'Lt' operators, the value must be an integer", strValue, r) return false } } @@ -467,7 +469,7 @@ func (l *Lexer) Lex() (tok Token, lit string) { } } -// Parser data structure contains the label selector parser data strucutre +// Parser data structure contains the label selector parser data structure type Parser struct { l *Lexer scannedItems []ScannedItem diff --git a/vendor/k8s.io/kubernetes/pkg/master/controller.go b/vendor/k8s.io/kubernetes/pkg/master/controller.go index e0482e65f687..6fad85f94c09 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/controller.go +++ b/vendor/k8s.io/kubernetes/pkg/master/controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -294,6 +294,14 @@ func (r *masterCountEndpointReconciler) ReconcileEndpoints(serviceName string, i }, } } + if errors.IsNotFound(err) { + // Simply create non-existing endpoints for the service. + e.Subsets = []api.EndpointSubset{{ + Addresses: []api.EndpointAddress{{IP: ip.String()}}, + Ports: endpointPorts, + }} + return r.endpointRegistry.UpdateEndpoints(ctx, e) + } // First, determine if the endpoint is in the format we expect (one // subset, ports matching endpointPorts, N IP addresses). @@ -304,7 +312,7 @@ func (r *masterCountEndpointReconciler) ReconcileEndpoints(serviceName string, i Addresses: []api.EndpointAddress{{IP: ip.String()}}, Ports: endpointPorts, }} - glog.Warningf("Resetting endpoints for master service %q to %v", serviceName, e) + glog.Warningf("Resetting endpoints for master service %q to %#v", serviceName, e) return r.endpointRegistry.UpdateEndpoints(ctx, e) } if ipCorrect && portsCorrect { diff --git a/vendor/k8s.io/kubernetes/pkg/master/doc.go b/vendor/k8s.io/kubernetes/pkg/master/doc.go index cc21977b8009..1c0ae1ed8f58 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/master/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/master/import_known_versions.go b/vendor/k8s.io/kubernetes/pkg/master/import_known_versions.go index f7ad207fae30..21873a0afb86 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/import_known_versions.go +++ b/vendor/k8s.io/kubernetes/pkg/master/import_known_versions.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( _ "k8s.io/kubernetes/pkg/apis/authorization/install" _ "k8s.io/kubernetes/pkg/apis/autoscaling/install" _ "k8s.io/kubernetes/pkg/apis/batch/install" + _ "k8s.io/kubernetes/pkg/apis/certificates/install" _ "k8s.io/kubernetes/pkg/apis/componentconfig/install" _ "k8s.io/kubernetes/pkg/apis/extensions/install" _ "k8s.io/kubernetes/pkg/apis/policy/install" diff --git a/vendor/k8s.io/kubernetes/pkg/master/master.go b/vendor/k8s.io/kubernetes/pkg/master/master.go index 56821462291b..13de194f164e 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/master.go +++ b/vendor/k8s.io/kubernetes/pkg/master/master.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -40,6 +40,8 @@ import ( "k8s.io/kubernetes/pkg/apis/batch" batchapiv1 "k8s.io/kubernetes/pkg/apis/batch/v1" batchapiv2alpha1 "k8s.io/kubernetes/pkg/apis/batch/v2alpha1" + "k8s.io/kubernetes/pkg/apis/certificates" + certificatesapiv1alpha1 "k8s.io/kubernetes/pkg/apis/certificates/v1alpha1" "k8s.io/kubernetes/pkg/apis/extensions" extensionsapiv1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/apis/policy" @@ -53,6 +55,7 @@ import ( "k8s.io/kubernetes/pkg/healthz" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" "k8s.io/kubernetes/pkg/master/ports" + certificateetcd "k8s.io/kubernetes/pkg/registry/certificates/etcd" "k8s.io/kubernetes/pkg/registry/clusterrole" clusterroleetcd "k8s.io/kubernetes/pkg/registry/clusterrole/etcd" clusterrolepolicybased "k8s.io/kubernetes/pkg/registry/clusterrole/policybased" @@ -97,6 +100,7 @@ import ( serviceetcd "k8s.io/kubernetes/pkg/registry/service/etcd" ipallocator "k8s.io/kubernetes/pkg/registry/service/ipallocator" serviceaccountetcd "k8s.io/kubernetes/pkg/registry/serviceaccount/etcd" + storageclassetcd "k8s.io/kubernetes/pkg/registry/storageclass/etcd" thirdpartyresourceetcd "k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd" "k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata" thirdpartyresourcedataetcd "k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd" @@ -104,6 +108,7 @@ import ( "k8s.io/kubernetes/pkg/storage" etcdmetrics "k8s.io/kubernetes/pkg/storage/etcd/metrics" etcdutil "k8s.io/kubernetes/pkg/storage/etcd/util" + "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" daemonetcd "k8s.io/kubernetes/pkg/registry/daemonset/etcd" @@ -115,19 +120,35 @@ import ( "k8s.io/kubernetes/pkg/registry/service/portallocator" ) +const ( + // DefaultEndpointReconcilerInterval is the default amount of time for how often the endpoints for + // the kubernetes Service are reconciled. + DefaultEndpointReconcilerInterval = 10 * time.Second +) + type Config struct { *genericapiserver.Config - EnableCoreControllers bool - DeleteCollectionWorkers int - EventTTL time.Duration - KubeletClient kubeletclient.KubeletClient + EnableCoreControllers bool + EndpointReconcilerConfig EndpointReconcilerConfig + DeleteCollectionWorkers int + EventTTL time.Duration + KubeletClient kubeletclient.KubeletClient + // RESTStorageProviders provides RESTStorage building methods keyed by groupName + RESTStorageProviders map[string]RESTStorageProvider // Used to start and monitor tunneling Tunneler genericapiserver.Tunneler disableThirdPartyControllerForTesting bool } +// EndpointReconcilerConfig holds the endpoint reconciler and endpoint reconciliation interval to be +// used by the master. +type EndpointReconcilerConfig struct { + Reconciler EndpointReconciler + Interval time.Duration +} + // Master contains state for a Kubernetes cluster master/api server. type Master struct { *genericapiserver.GenericAPIServer @@ -167,6 +188,9 @@ type thirdPartyEntry struct { group unversioned.APIGroup } +type RESTOptionsGetter func(resource unversioned.GroupResource) generic.RESTOptions +type RESTStorageProvider func(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) + // New returns a new instance of Master from the given config. // Certain config fields will be set to a default value if unset. // Certain config fields must be specified, including: @@ -189,11 +213,22 @@ func New(c *Config) (*Master, error) { disableThirdPartyControllerForTesting: c.disableThirdPartyControllerForTesting, } + + // Add some hardcoded storage for now. Append to the map. + if c.RESTStorageProviders == nil { + c.RESTStorageProviders = map[string]RESTStorageProvider{} + } + c.RESTStorageProviders[autoscaling.GroupName] = buildAutoscalingResources + c.RESTStorageProviders[batch.GroupName] = buildBatchResources + c.RESTStorageProviders[policy.GroupName] = buildPolicyResources + c.RESTStorageProviders[appsapi.GroupName] = buildAppsResources + c.RESTStorageProviders[rbac.GroupName] = buildRBACResources(c.AuthorizerRBACSuperUser) + c.RESTStorageProviders[certificates.GroupName] = buildCertificateResources m.InstallAPIs(c) // TODO: Attempt clean shutdown? if m.enableCoreControllers { - m.NewBootstrapController().Start() + m.NewBootstrapController(c.EndpointReconcilerConfig).Start() } return m, nil @@ -255,9 +290,6 @@ func (m *Master) InstallAPIs(c *Config) { m.MuxHelper.HandleFunc("/metrics", defaultMetricsHandler) } - // allGroups records all supported groups at /apis - allGroups := []unversioned.APIGroup{} - // Install extensions unless disabled. if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(extensionsapiv1beta1.SchemeGroupVersion) { var err error @@ -281,183 +313,25 @@ func (m *Master) InstallAPIs(c *Config) { NegotiatedSerializer: api.Codecs, } apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - extensionsGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: extensionsGroupMeta.GroupVersion.String(), - Version: extensionsGroupMeta.GroupVersion.Version, - } - group := unversioned.APIGroup{ - Name: extensionsGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{extensionsGVForDiscovery}, - PreferredVersion: extensionsGVForDiscovery, - } - allGroups = append(allGroups, group) } - // Install autoscaling unless disabled. - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(autoscalingapiv1.SchemeGroupVersion) { - autoscalingResources := m.getAutoscalingResources(c) - autoscalingGroupMeta := registered.GroupOrDie(autoscaling.GroupName) - - // Hard code preferred group version to autoscaling/v1 - autoscalingGroupMeta.GroupVersion = autoscalingapiv1.SchemeGroupVersion - - apiGroupInfo := genericapiserver.APIGroupInfo{ - GroupMeta: *autoscalingGroupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - "v1": autoscalingResources, - }, - OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, - Scheme: api.Scheme, - ParameterCodec: api.ParameterCodec, - NegotiatedSerializer: api.Codecs, - } - apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - autoscalingGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: autoscalingGroupMeta.GroupVersion.String(), - Version: autoscalingGroupMeta.GroupVersion.Version, - } - group := unversioned.APIGroup{ - Name: autoscalingGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{autoscalingGVForDiscovery}, - PreferredVersion: autoscalingGVForDiscovery, - } - allGroups = append(allGroups, group) + restOptionsGetter := func(resource unversioned.GroupResource) generic.RESTOptions { + return m.GetRESTOptionsOrDie(c, resource) } - // Install batch unless disabled. - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv1.SchemeGroupVersion) || - c.APIResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv2alpha1.SchemeGroupVersion) { - batchv1Resources := m.getBatchResources(c, batchapiv1.SchemeGroupVersion) - batchGroupMeta := registered.GroupOrDie(batch.GroupName) - - // Hard code preferred group version to batch/v1 - batchGroupMeta.GroupVersion = batchapiv1.SchemeGroupVersion - - apiGroupInfo := genericapiserver.APIGroupInfo{ - GroupMeta: *batchGroupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - "v1": batchv1Resources, - }, - OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, - Scheme: api.Scheme, - ParameterCodec: api.ParameterCodec, - NegotiatedSerializer: api.Codecs, - } - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv2alpha1.SchemeGroupVersion) { - batchv2alpha1Resources := m.getBatchResources(c, batchapiv2alpha1.SchemeGroupVersion) - apiGroupInfo.VersionedResourcesStorageMap["v2alpha1"] = batchv2alpha1Resources - } - - apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - batchGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: batchGroupMeta.GroupVersion.String(), - Version: batchGroupMeta.GroupVersion.Version, - } - group := unversioned.APIGroup{ - Name: batchGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{batchGVForDiscovery}, - PreferredVersion: batchGVForDiscovery, - } - allGroups = append(allGroups, group) - } - - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(policyapiv1alpha1.SchemeGroupVersion) { - policyResources := m.getPolicyResources(c) - policyGroupMeta := registered.GroupOrDie(policy.GroupName) - - // Hard code preferred group version to policy/v1alpha1 - policyGroupMeta.GroupVersion = policyapiv1alpha1.SchemeGroupVersion - - apiGroupInfo := genericapiserver.APIGroupInfo{ - GroupMeta: *policyGroupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - "v1alpha1": policyResources, - }, - OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, - Scheme: api.Scheme, - ParameterCodec: api.ParameterCodec, - NegotiatedSerializer: api.Codecs, - } - apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - policyGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: policyGroupMeta.GroupVersion.String(), - Version: policyGroupMeta.GroupVersion.Version, - } - group := unversioned.APIGroup{ - Name: policyGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{policyGVForDiscovery}, - PreferredVersion: policyGVForDiscovery, - } - allGroups = append(allGroups, group) - - } - - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(appsapi.SchemeGroupVersion) { - appsResources := m.getAppsResources(c) - appsGroupMeta := registered.GroupOrDie(apps.GroupName) - - // Hard code preferred group version to apps/v1alpha1 - appsGroupMeta.GroupVersion = appsapi.SchemeGroupVersion - - apiGroupInfo := genericapiserver.APIGroupInfo{ - GroupMeta: *appsGroupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - "v1alpha1": appsResources, - }, - OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, - Scheme: api.Scheme, - ParameterCodec: api.ParameterCodec, - NegotiatedSerializer: api.Codecs, - } - apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - appsGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: appsGroupMeta.GroupVersion.String(), - Version: appsGroupMeta.GroupVersion.Version, + // stabilize order. + // TODO find a better way to configure priority of groups + for _, group := range sets.StringKeySet(c.RESTStorageProviders).List() { + if !c.APIResourceConfigSource.AnyResourcesForGroupEnabled(group) { + continue } - group := unversioned.APIGroup{ - Name: appsGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{appsGVForDiscovery}, - PreferredVersion: appsGVForDiscovery, + restStorageBuilder := c.RESTStorageProviders[group] + apiGroupInfo, enabled := restStorageBuilder(c.APIResourceConfigSource, restOptionsGetter) + if !enabled { + continue } - allGroups = append(allGroups, group) - } - - if c.APIResourceConfigSource.AnyResourcesForVersionEnabled(rbacapi.SchemeGroupVersion) { - rbacResources := m.getRBACResources(c) - rbacGroupMeta := registered.GroupOrDie(rbac.GroupName) - - // Hard code preferred group version to rbac/v1alpha1 - rbacGroupMeta.GroupVersion = rbacapi.SchemeGroupVersion - - apiGroupInfo := genericapiserver.APIGroupInfo{ - GroupMeta: *rbacGroupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - "v1alpha1": rbacResources, - }, - OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, - Scheme: api.Scheme, - ParameterCodec: api.ParameterCodec, - NegotiatedSerializer: api.Codecs, - } apiGroupsInfo = append(apiGroupsInfo, apiGroupInfo) - - rbacGVForDiscovery := unversioned.GroupVersionForDiscovery{ - GroupVersion: rbacGroupMeta.GroupVersion.String(), - Version: rbacGroupMeta.GroupVersion.Version, - } - group := unversioned.APIGroup{ - Name: rbacGroupMeta.GroupVersion.Group, - Versions: []unversioned.GroupVersionForDiscovery{rbacGVForDiscovery}, - PreferredVersion: rbacGVForDiscovery, - } - allGroups = append(allGroups, group) - } if err := m.InstallAPIGroups(apiGroupsInfo); err != nil { @@ -585,14 +459,27 @@ func (m *Master) initV1ResourcesStorage(c *Config) { } } -// NewBootstrapController returns a controller for watching the core capabilities of the master. -func (m *Master) NewBootstrapController() *Controller { +// NewBootstrapController returns a controller for watching the core capabilities of the master. If +// endpointReconcilerConfig.Interval is 0, the default value of DefaultEndpointReconcilerInterval +// will be used instead. If endpointReconcilerConfig.Reconciler is nil, the default +// MasterCountEndpointReconciler will be used. +func (m *Master) NewBootstrapController(endpointReconcilerConfig EndpointReconcilerConfig) *Controller { + if endpointReconcilerConfig.Interval == 0 { + endpointReconcilerConfig.Interval = DefaultEndpointReconcilerInterval + } + + if endpointReconcilerConfig.Reconciler == nil { + // use a default endpoint reconciler if nothing is set + // m.endpointRegistry is set via m.InstallAPIs -> m.initV1ResourcesStorage + endpointReconcilerConfig.Reconciler = NewMasterCountEndpointReconciler(m.MasterCount, m.endpointRegistry) + } + return &Controller{ NamespaceRegistry: m.namespaceRegistry, ServiceRegistry: m.serviceRegistry, - EndpointReconciler: NewMasterCountEndpointReconciler(m.MasterCount, m.endpointRegistry), - EndpointInterval: 10 * time.Second, + EndpointReconciler: endpointReconcilerConfig.Reconciler, + EndpointInterval: endpointReconcilerConfig.Interval, SystemNamespaces: []string{api.NamespaceSystem}, SystemNamespacesInterval: 1 * time.Minute, @@ -730,6 +617,13 @@ func (m *Master) ListThirdPartyResources() []string { return result } +func (m *Master) hasThirdPartyResourceStorage(path string) bool { + m.thirdPartyResourcesLock.Lock() + defer m.thirdPartyResourcesLock.Unlock() + _, found := m.thirdPartyResources[path] + return found +} + func (m *Master) addThirdPartyResourceStorage(path string, storage *thirdpartyresourcedataetcd.REST, apiGroup unversioned.APIGroup) { m.thirdPartyResourcesLock.Lock() defer m.thirdPartyResourcesLock.Unlock() @@ -754,12 +648,19 @@ func (m *Master) InstallThirdPartyResource(rsrc *extensions.ThirdPartyResource) Version: rsrc.Versions[0].Name, Kind: kind, }) + path := makeThirdPartyPath(group) thirdparty := m.thirdpartyapi(group, kind, rsrc.Versions[0].Name, plural.Resource) + + // If storage exists, this group has already been added, just update + // the group with the new API + if m.hasThirdPartyResourceStorage(path) { + return thirdparty.UpdateREST(m.HandlerContainer) + } + if err := thirdparty.InstallREST(m.HandlerContainer); err != nil { - glog.Fatalf("Unable to setup thirdparty api: %v", err) + glog.Errorf("Unable to setup thirdparty api: %v", err) } - path := makeThirdPartyPath(group) groupVersion := unversioned.GroupVersionForDiscovery{ GroupVersion: group + "/" + rsrc.Versions[0].Name, Version: rsrc.Versions[0].Name, @@ -831,6 +732,7 @@ func (m *Master) GetRESTOptionsOrDie(c *Config, resource unversioned.GroupResour Storage: storage, Decorator: m.StorageDecorator(), DeleteCollectionWorkers: m.deleteCollectionWorkers, + ResourcePrefix: c.StorageFactory.ResourcePrefix(resource), } } @@ -906,98 +808,185 @@ func (m *Master) getExtensionResources(c *Config) map[string]rest.Storage { if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("networkpolicies")) { storage["networkpolicies"] = networkPolicyStorage } + storageClassStorage := storageclassetcd.NewREST(restOptions("storageclasses")) + if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("storageclasses")) { + storage["storageclasses"] = storageClassStorage + } return storage } -// getAutoscalingResources returns the resources for autoscaling api -func (m *Master) getAutoscalingResources(c *Config) map[string]rest.Storage { - // TODO update when we support more than one version of this group - version := autoscalingapiv1.SchemeGroupVersion +// NewDefaultAPIGroupInfo returns a complete APIGroupInfo stubbed with "normal" values +// exposed for easier composition from other packages +func NewDefaultAPIGroupInfo(group string) genericapiserver.APIGroupInfo { + groupMeta := registered.GroupOrDie(group) - storage := map[string]rest.Storage{} - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("horizontalpodautoscalers")) { - hpaStorage, hpaStatusStorage := horizontalpodautoscaleretcd.NewREST(m.GetRESTOptionsOrDie(c, autoscaling.Resource("horizontalpodautoscalers"))) - storage["horizontalpodautoscalers"] = hpaStorage - storage["horizontalpodautoscalers/status"] = hpaStatusStorage + return genericapiserver.APIGroupInfo{ + GroupMeta: *groupMeta, + VersionedResourcesStorageMap: map[string]map[string]rest.Storage{}, + OptionsExternalVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion, + Scheme: api.Scheme, + ParameterCodec: api.ParameterCodec, + NegotiatedSerializer: api.Codecs, } - return storage } -// getBatchResources returns the resources for batch api -func (m *Master) getBatchResources(c *Config, version unversioned.GroupVersion) map[string]rest.Storage { - storage := map[string]rest.Storage{} - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) { - jobsStorage, jobsStatusStorage := jobetcd.NewREST(m.GetRESTOptionsOrDie(c, batch.Resource("jobs"))) - storage["jobs"] = jobsStorage - storage["jobs/status"] = jobsStatusStorage +func buildCertificateResources(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(certificates.GroupName) + + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("certificatesigningrequests")) { + csrStorage, csrStatusStorage, csrApprovalStorage := certificateetcd.NewREST(restOptionsGetter(certificates.Resource("certificatesigningrequests"))) + storage["certificatesigningrequests"] = csrStorage + storage["certificatesigningrequests/status"] = csrStatusStorage + storage["certificatesigningrequests/approval"] = csrApprovalStorage + } + return storage } - return storage + + if apiResourceConfigSource.AnyResourcesForVersionEnabled(certificatesapiv1alpha1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[certificatesapiv1alpha1.SchemeGroupVersion.Version] = storageForVersion(certificatesapiv1alpha1.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = certificatesapiv1alpha1.SchemeGroupVersion + } + + return apiGroupInfo, true } -// getPolicyResources returns the resources for policy api -func (m *Master) getPolicyResources(c *Config) map[string]rest.Storage { - // TODO update when we support more than one version of this group - version := policyapiv1alpha1.SchemeGroupVersion +func buildAutoscalingResources(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(autoscaling.GroupName) - storage := map[string]rest.Storage{} - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("poddisruptionbudgets")) { - poddisruptionbudgetStorage, poddisruptionbudgetStatusStorage := poddisruptionbudgetetcd.NewREST(m.GetRESTOptionsOrDie(c, policy.Resource("poddisruptionbudgets"))) - storage["poddisruptionbudgets"] = poddisruptionbudgetStorage - storage["poddisruptionbudgets/status"] = poddisruptionbudgetStatusStorage + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("horizontalpodautoscalers")) { + hpaStorage, hpaStatusStorage := horizontalpodautoscaleretcd.NewREST(restOptionsGetter(autoscaling.Resource("horizontalpodautoscalers"))) + storage["horizontalpodautoscalers"] = hpaStorage + storage["horizontalpodautoscalers/status"] = hpaStatusStorage + } + return storage } - return storage + + if apiResourceConfigSource.AnyResourcesForVersionEnabled(autoscalingapiv1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv1.SchemeGroupVersion.Version] = storageForVersion(autoscalingapiv1.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = autoscalingapiv1.SchemeGroupVersion + } + + return apiGroupInfo, true } -// getAppsResources returns the resources for apps api -func (m *Master) getAppsResources(c *Config) map[string]rest.Storage { - // TODO update when we support more than one version of this group - version := appsapi.SchemeGroupVersion +func buildBatchResources(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(batch.GroupName) - storage := map[string]rest.Storage{} - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("petsets")) { - petsetStorage, petsetStatusStorage := petsetetcd.NewREST(m.GetRESTOptionsOrDie(c, apps.Resource("petsets"))) - storage["petsets"] = petsetStorage - storage["petsets/status"] = petsetStatusStorage + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("jobs")) { + jobsStorage, jobsStatusStorage := jobetcd.NewREST(restOptionsGetter(batch.Resource("jobs"))) + storage["jobs"] = jobsStorage + storage["jobs/status"] = jobsStatusStorage + } + return storage } - return storage + + if apiResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv2alpha1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[batchapiv2alpha1.SchemeGroupVersion.Version] = storageForVersion(batchapiv2alpha1.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = batchapiv2alpha1.SchemeGroupVersion + } + if apiResourceConfigSource.AnyResourcesForVersionEnabled(batchapiv1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[batchapiv1.SchemeGroupVersion.Version] = storageForVersion(batchapiv1.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = batchapiv1.SchemeGroupVersion + } + + return apiGroupInfo, true } -func (m *Master) getRBACResources(c *Config) map[string]rest.Storage { - version := rbacapi.SchemeGroupVersion +func buildPolicyResources(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(policy.GroupName) - once := new(sync.Once) - var authorizationRuleResolver rbacvalidation.AuthorizationRuleResolver - newRuleValidator := func() rbacvalidation.AuthorizationRuleResolver { - once.Do(func() { - authorizationRuleResolver = rbacvalidation.NewDefaultRuleResolver( - role.NewRegistry(roleetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("roles")))), - rolebinding.NewRegistry(rolebindingetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("rolebindings")))), - clusterrole.NewRegistry(clusterroleetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("clusterroles")))), - clusterrolebinding.NewRegistry(clusterrolebindingetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("clusterrolebindings")))), - ) - }) - return authorizationRuleResolver + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("poddisruptionbudgets")) { + poddisruptionbudgetStorage, poddisruptionbudgetStatusStorage := poddisruptionbudgetetcd.NewREST(restOptionsGetter(policy.Resource("poddisruptionbudgets"))) + storage["poddisruptionbudgets"] = poddisruptionbudgetStorage + storage["poddisruptionbudgets/status"] = poddisruptionbudgetStatusStorage + } + return storage } - storage := map[string]rest.Storage{} - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("roles")) { - rolesStorage := roleetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("roles"))) - storage["roles"] = rolepolicybased.NewStorage(rolesStorage, newRuleValidator(), c.AuthorizerRBACSuperUser) + if apiResourceConfigSource.AnyResourcesForVersionEnabled(policyapiv1alpha1.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[policyapiv1alpha1.SchemeGroupVersion.Version] = storageForVersion(policyapiv1alpha1.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = policyapiv1alpha1.SchemeGroupVersion } - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("rolebindings")) { - roleBindingsStorage := rolebindingetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("rolebindings"))) - storage["rolebindings"] = rolebindingpolicybased.NewStorage(roleBindingsStorage, newRuleValidator(), c.AuthorizerRBACSuperUser) + + return apiGroupInfo, true +} + +func buildAppsResources(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(appsapi.GroupName) + + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("petsets")) { + petsetStorage, petsetStatusStorage := petsetetcd.NewREST(restOptionsGetter(apps.Resource("petsets"))) + storage["petsets"] = petsetStorage + storage["petsets/status"] = petsetStatusStorage + } + return storage } - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("clusterroles")) { - clusterRolesStorage := clusterroleetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("clusterroles"))) - storage["clusterroles"] = clusterrolepolicybased.NewStorage(clusterRolesStorage, newRuleValidator(), c.AuthorizerRBACSuperUser) + + if apiResourceConfigSource.AnyResourcesForVersionEnabled(appsapi.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[appsapi.SchemeGroupVersion.Version] = storageForVersion(appsapi.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = appsapi.SchemeGroupVersion } - if c.APIResourceConfigSource.ResourceEnabled(version.WithResource("clusterrolebindings")) { - clusterRoleBindingsStorage := clusterrolebindingetcd.NewREST(m.GetRESTOptionsOrDie(c, rbac.Resource("clusterrolebindings"))) - storage["clusterrolebindings"] = clusterrolebindingpolicybased.NewStorage(clusterRoleBindingsStorage, newRuleValidator(), c.AuthorizerRBACSuperUser) + + return apiGroupInfo, true +} + +func buildRBACResources(authorizerRBACSuperUser string) RESTStorageProvider { + return func(apiResourceConfigSource genericapiserver.APIResourceConfigSource, restOptionsGetter RESTOptionsGetter) (genericapiserver.APIGroupInfo, bool) { + apiGroupInfo := NewDefaultAPIGroupInfo(rbac.GroupName) + + storageForVersion := func(version unversioned.GroupVersion) map[string]rest.Storage { + once := new(sync.Once) + var authorizationRuleResolver rbacvalidation.AuthorizationRuleResolver + newRuleValidator := func() rbacvalidation.AuthorizationRuleResolver { + once.Do(func() { + authorizationRuleResolver = rbacvalidation.NewDefaultRuleResolver( + role.NewRegistry(roleetcd.NewREST(restOptionsGetter(rbac.Resource("roles")))), + rolebinding.NewRegistry(rolebindingetcd.NewREST(restOptionsGetter(rbac.Resource("rolebindings")))), + clusterrole.NewRegistry(clusterroleetcd.NewREST(restOptionsGetter(rbac.Resource("clusterroles")))), + clusterrolebinding.NewRegistry(clusterrolebindingetcd.NewREST(restOptionsGetter(rbac.Resource("clusterrolebindings")))), + ) + }) + return authorizationRuleResolver + } + + storage := map[string]rest.Storage{} + if apiResourceConfigSource.ResourceEnabled(version.WithResource("roles")) { + rolesStorage := roleetcd.NewREST(restOptionsGetter(rbac.Resource("roles"))) + storage["roles"] = rolepolicybased.NewStorage(rolesStorage, newRuleValidator(), authorizerRBACSuperUser) + } + if apiResourceConfigSource.ResourceEnabled(version.WithResource("rolebindings")) { + roleBindingsStorage := rolebindingetcd.NewREST(restOptionsGetter(rbac.Resource("rolebindings"))) + storage["rolebindings"] = rolebindingpolicybased.NewStorage(roleBindingsStorage, newRuleValidator(), authorizerRBACSuperUser) + } + if apiResourceConfigSource.ResourceEnabled(version.WithResource("clusterroles")) { + clusterRolesStorage := clusterroleetcd.NewREST(restOptionsGetter(rbac.Resource("clusterroles"))) + storage["clusterroles"] = clusterrolepolicybased.NewStorage(clusterRolesStorage, newRuleValidator(), authorizerRBACSuperUser) + } + if apiResourceConfigSource.ResourceEnabled(version.WithResource("clusterrolebindings")) { + clusterRoleBindingsStorage := clusterrolebindingetcd.NewREST(restOptionsGetter(rbac.Resource("clusterrolebindings"))) + storage["clusterrolebindings"] = clusterrolebindingpolicybased.NewStorage(clusterRoleBindingsStorage, newRuleValidator(), authorizerRBACSuperUser) + } + return storage + } + + if apiResourceConfigSource.AnyResourcesForVersionEnabled(rbacapi.SchemeGroupVersion) { + apiGroupInfo.VersionedResourcesStorageMap[rbacapi.SchemeGroupVersion.Version] = storageForVersion(rbacapi.SchemeGroupVersion) + apiGroupInfo.GroupMeta.GroupVersion = rbacapi.SchemeGroupVersion + } + + return apiGroupInfo, true } - return storage } // findExternalAddress returns ExternalIP of provided node with fallback to LegacyHostIP. @@ -1052,7 +1041,16 @@ func (m *Master) IsTunnelSyncHealthy(req *http.Request) error { func DefaultAPIResourceConfigSource() *genericapiserver.ResourceConfig { ret := genericapiserver.NewResourceConfig() - ret.EnableVersions(apiv1.SchemeGroupVersion, extensionsapiv1beta1.SchemeGroupVersion, batchapiv1.SchemeGroupVersion, autoscalingapiv1.SchemeGroupVersion, appsapi.SchemeGroupVersion, policyapiv1alpha1.SchemeGroupVersion, rbacapi.SchemeGroupVersion) + ret.EnableVersions( + apiv1.SchemeGroupVersion, + extensionsapiv1beta1.SchemeGroupVersion, + batchapiv1.SchemeGroupVersion, + autoscalingapiv1.SchemeGroupVersion, + appsapi.SchemeGroupVersion, + policyapiv1alpha1.SchemeGroupVersion, + rbacapi.SchemeGroupVersion, + certificatesapiv1alpha1.SchemeGroupVersion, + ) // all extensions resources except these are disabled by default ret.EnableResources( @@ -1064,6 +1062,7 @@ func DefaultAPIResourceConfigSource() *genericapiserver.ResourceConfig { extensionsapiv1beta1.SchemeGroupVersion.WithResource("networkpolicies"), extensionsapiv1beta1.SchemeGroupVersion.WithResource("replicasets"), extensionsapiv1beta1.SchemeGroupVersion.WithResource("thirdpartyresources"), + extensionsapiv1beta1.SchemeGroupVersion.WithResource("storageclasses"), ) return ret diff --git a/vendor/k8s.io/kubernetes/pkg/master/ports/doc.go b/vendor/k8s.io/kubernetes/pkg/master/ports/doc.go index dc6c989e8288..a2a002101ca3 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/ports/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/master/ports/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/master/ports/ports.go b/vendor/k8s.io/kubernetes/pkg/master/ports/ports.go index 246a1a562d3a..9c597ba47b4d 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/ports/ports.go +++ b/vendor/k8s.io/kubernetes/pkg/master/ports/ports.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/master/thirdparty_controller.go b/vendor/k8s.io/kubernetes/pkg/master/thirdparty_controller.go index 15b44dfc452e..ed49257350a6 100644 --- a/vendor/k8s.io/kubernetes/pkg/master/thirdparty_controller.go +++ b/vendor/k8s.io/kubernetes/pkg/master/thirdparty_controller.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/probe/doc.go b/vendor/k8s.io/kubernetes/pkg/probe/doc.go index dbdfe44db38f..89c70b2c16af 100644 --- a/vendor/k8s.io/kubernetes/pkg/probe/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/probe/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/probe/exec/exec.go b/vendor/k8s.io/kubernetes/pkg/probe/exec/exec.go index a8ea0f6e3cda..2507ca438911 100644 --- a/vendor/k8s.io/kubernetes/pkg/probe/exec/exec.go +++ b/vendor/k8s.io/kubernetes/pkg/probe/exec/exec.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/probe/http/http.go b/vendor/k8s.io/kubernetes/pkg/probe/http/http.go index a5fce49fa7fd..50659556a021 100644 --- a/vendor/k8s.io/kubernetes/pkg/probe/http/http.go +++ b/vendor/k8s.io/kubernetes/pkg/probe/http/http.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/probe/probe.go b/vendor/k8s.io/kubernetes/pkg/probe/probe.go index f175860d7a13..ebbb607c46df 100644 --- a/vendor/k8s.io/kubernetes/pkg/probe/probe.go +++ b/vendor/k8s.io/kubernetes/pkg/probe/probe.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/probe/tcp/tcp.go b/vendor/k8s.io/kubernetes/pkg/probe/tcp/tcp.go index 8e3676fbd669..cce3be9935e9 100644 --- a/vendor/k8s.io/kubernetes/pkg/probe/tcp/tcp.go +++ b/vendor/k8s.io/kubernetes/pkg/probe/tcp/tcp.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/config/api.go b/vendor/k8s.io/kubernetes/pkg/proxy/config/api.go index 51f8abf4a23f..4159022ed6c1 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/config/api.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/config/api.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/config/config.go b/vendor/k8s.io/kubernetes/pkg/proxy/config/config.go index 2181ca93f78d..9f5bbd3fa2ae 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/config/config.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/config/config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/config/doc.go b/vendor/k8s.io/kubernetes/pkg/proxy/config/doc.go index 035d99c4ec7a..632d1618b82b 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/config/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/config/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/doc.go b/vendor/k8s.io/kubernetes/pkg/proxy/doc.go index 05b801a2bad1..a69b3082cd89 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/iptables/proxier.go b/vendor/k8s.io/kubernetes/pkg/proxy/iptables/proxier.go index 83ee6e5babf7..7ef1c0ce4cb2 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/iptables/proxier.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/iptables/proxier.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import ( "encoding/base32" "fmt" "net" - "os" "reflect" "strconv" "strings" @@ -198,15 +197,8 @@ func NewProxier(ipt utiliptables.Interface, exec utilexec.Interface, syncPeriod // Proxy needs br_netfilter and bridge-nf-call-iptables=1 when containers // are connected to a Linux bridge (but not SDN bridges). Until most // plugins handle this, log when config is missing - warnBrNetfilter := false - if _, err := os.Stat("/sys/module/br_netfilter"); os.IsNotExist(err) { - warnBrNetfilter = true - } if val, err := utilsysctl.GetSysctl(sysctlBridgeCallIptables); err == nil && val != 1 { - warnBrNetfilter = true - } - if warnBrNetfilter { - glog.Infof("missing br-netfilter module or unset br-nf-call-iptables; proxy may not work as intended") + glog.Infof("missing br-netfilter module or unset sysctl br-nf-call-iptables; proxy may not work as intended") } // Generate the masquerade mark to use for SNAT rules. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/types.go b/vendor/k8s.io/kubernetes/pkg/proxy/types.go index 15b227f1cc5e..4d2ead275e20 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/types.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/loadbalancer.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/loadbalancer.go index 33085fe0400f..dee5cb843de1 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/loadbalancer.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/loadbalancer.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/port_allocator.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/port_allocator.go index 22182f9c98b0..8ae6e9779b60 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/port_allocator.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/port_allocator.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxier.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxier.go index fb5d00e1eb62..d4a13df910ce 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxier.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxier.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxysocket.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxysocket.go index 3cab4444d288..e690efbae59b 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxysocket.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/proxysocket.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit.go index 0f634e051cba..d3f52b6defe9 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit.go @@ -1,7 +1,7 @@ // +build !windows /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit_windows.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit_windows.go index 346ee18bb934..b0a1dd2e3ed0 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit_windows.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/rlimit_windows.go @@ -1,7 +1,7 @@ // +build windows /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/roundrobin.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/roundrobin.go index a67dbf55d6ad..bb553f3a7747 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/roundrobin.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/roundrobin.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/udp_server.go b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/udp_server.go index fdc85b47df17..49e8d603f252 100644 --- a/vendor/k8s.io/kubernetes/pkg/proxy/userspace/udp_server.go +++ b/vendor/k8s.io/kubernetes/pkg/proxy/userspace/udp_server.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/configmap.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/configmap.go index 879beb1b935e..46ee974292b8 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/configmap.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/configmap.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/doc.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/doc.go index 3fdfaa773bdb..f80963bcf305 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/persistent_volume_claims.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/persistent_volume_claims.go index 4edfffdd0d39..a00e44f100d5 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/persistent_volume_claims.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/persistent_volume_claims.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/pods.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/pods.go index 9fa480b797a4..abad5950f7c9 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/pods.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/pods.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import ( "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/validation" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" - "k8s.io/kubernetes/pkg/kubelet/qos/util" + "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/generic" "k8s.io/kubernetes/pkg/runtime" @@ -79,8 +79,11 @@ func PodConstraintsFunc(required []api.ResourceName, object runtime.Object) erro allErrs := field.ErrorList{} fldPath := field.NewPath("spec").Child("containers") for i, ctr := range pod.Spec.Containers { - idxPath := fldPath.Index(i) - allErrs = append(allErrs, validation.ValidateResourceRequirements(&ctr.Resources, idxPath.Child("resources"))...) + allErrs = append(allErrs, validation.ValidateResourceRequirements(&ctr.Resources, fldPath.Index(i).Child("resources"))...) + } + fldPath = field.NewPath("spec").Child("initContainers") + for i, ctr := range pod.Spec.InitContainers { + allErrs = append(allErrs, validation.ValidateResourceRequirements(&ctr.Resources, fldPath.Index(i).Child("resources"))...) } if len(allErrs) > 0 { return allErrs.ToAggregate() @@ -92,14 +95,10 @@ func PodConstraintsFunc(required []api.ResourceName, object runtime.Object) erro requiredSet := quota.ToSet(required) missingSet := sets.NewString() for i := range pod.Spec.Containers { - requests := pod.Spec.Containers[i].Resources.Requests - limits := pod.Spec.Containers[i].Resources.Limits - containerUsage := podUsageHelper(requests, limits) - containerSet := quota.ToSet(quota.ResourceNames(containerUsage)) - if !containerSet.Equal(requiredSet) { - difference := requiredSet.Difference(containerSet) - missingSet.Insert(difference.List()...) - } + enforcePodContainerConstraints(&pod.Spec.Containers[i], requiredSet, missingSet) + } + for i := range pod.Spec.InitContainers { + enforcePodContainerConstraints(&pod.Spec.InitContainers[i], requiredSet, missingSet) } if len(missingSet) == 0 { return nil @@ -107,6 +106,19 @@ func PodConstraintsFunc(required []api.ResourceName, object runtime.Object) erro return fmt.Errorf("must specify %s", strings.Join(missingSet.List(), ",")) } +// enforcePodContainerConstraints checks for required resources that are not set on this container and +// adds them to missingSet. +func enforcePodContainerConstraints(container *api.Container, requiredSet, missingSet sets.String) { + requests := container.Resources.Requests + limits := container.Resources.Limits + containerUsage := podUsageHelper(requests, limits) + containerSet := quota.ToSet(quota.ResourceNames(containerUsage)) + if !containerSet.Equal(requiredSet) { + difference := requiredSet.Difference(containerSet) + missingSet.Insert(difference.List()...) + } +} + // podUsageHelper can summarize the pod quota usage based on requests and limits func podUsageHelper(requests api.ResourceList, limits api.ResourceList) api.ResourceList { result := api.ResourceList{} @@ -144,10 +156,18 @@ func PodUsageFunc(object runtime.Object) api.ResourceList { // when we have pod level cgroups, we can just read pod level requests/limits requests := api.ResourceList{} limits := api.ResourceList{} + for i := range pod.Spec.Containers { requests = quota.Add(requests, pod.Spec.Containers[i].Resources.Requests) limits = quota.Add(limits, pod.Spec.Containers[i].Resources.Limits) } + // InitContainers are run sequentially before other containers start, so the highest + // init container resource is compared against the sum of app containers to determine + // the effective usage for both requests and limits. + for i := range pod.Spec.InitContainers { + requests = quota.Max(requests, pod.Spec.InitContainers[i].Resources.Requests) + limits = quota.Max(limits, pod.Spec.InitContainers[i].Resources.Limits) + } return podUsageHelper(requests, limits) } @@ -172,7 +192,7 @@ func PodMatchesScopeFunc(scope api.ResourceQuotaScope, object runtime.Object) bo } func isBestEffort(pod *api.Pod) bool { - return util.GetPodQos(pod) == util.BestEffort + return qos.GetPodQOS(pod) == qos.BestEffort } func isTerminating(pod *api.Pod) bool { diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/registry.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/registry.go index 69d148455941..814e9d473711 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/replication_controllers.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/replication_controllers.go index 7d4b44337c1d..c99f33d25df9 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/replication_controllers.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/replication_controllers.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/resource_quotas.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/resource_quotas.go index 6d52e70e1421..51bc04c9dd96 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/resource_quotas.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/resource_quotas.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/secrets.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/secrets.go index d3d79f293dc9..c3785973244b 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/secrets.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/secrets.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/services.go b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/services.go index 818a5b1c2109..60fda367b753 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/services.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/evaluator/core/services.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -57,7 +57,8 @@ func ServiceUsageFunc(object runtime.Object) api.ResourceList { result[api.ResourceServices] = resource.MustParse("1") switch service.Spec.Type { case api.ServiceTypeNodePort: - result[api.ResourceServicesNodePorts] = resource.MustParse("1") + value := resource.NewQuantity(int64(len(service.Spec.Ports)), resource.DecimalSI) + result[api.ResourceServicesNodePorts] = *value case api.ServiceTypeLoadBalancer: result[api.ResourceServicesLoadBalancers] = resource.MustParse("1") } diff --git a/vendor/k8s.io/kubernetes/pkg/quota/generic/evaluator.go b/vendor/k8s.io/kubernetes/pkg/quota/generic/evaluator.go index 629b6fed7130..96dc4878f33f 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/generic/evaluator.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/generic/evaluator.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -175,9 +175,9 @@ func (g *GenericEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.Us if err != nil { return result, fmt.Errorf("%s: Failed to list %v: %v", g.Name, g.GroupKind(), err) } - _, err = meta.Accessor(list) + _, err = meta.ListAccessor(list) if err != nil { - return result, fmt.Errorf("%s: Unable to understand list result %#v", g.Name, list) + return result, fmt.Errorf("%s: Unable to understand list result, does not appear to be a list %#v", g.Name, list) } items, err := meta.ExtractList(list) if err != nil { diff --git a/vendor/k8s.io/kubernetes/pkg/quota/generic/registry.go b/vendor/k8s.io/kubernetes/pkg/quota/generic/registry.go index 0609d73cfa93..2a0600a5a007 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/generic/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/generic/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/install/registry.go b/vendor/k8s.io/kubernetes/pkg/quota/install/registry.go index 109b57484b3e..46c46dd878c1 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/install/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/install/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/interfaces.go b/vendor/k8s.io/kubernetes/pkg/quota/interfaces.go index da7e4a18fe14..728f8e5b83e2 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/quota/resources.go b/vendor/k8s.io/kubernetes/pkg/quota/resources.go index 0d5a75034176..c22cc2cd2803 100644 --- a/vendor/k8s.io/kubernetes/pkg/quota/resources.go +++ b/vendor/k8s.io/kubernetes/pkg/quota/resources.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -61,6 +61,26 @@ func LessThanOrEqual(a api.ResourceList, b api.ResourceList) (bool, []api.Resour return result, resourceNames } +// Max returns the result of Max(a, b) for each named resource +func Max(a api.ResourceList, b api.ResourceList) api.ResourceList { + result := api.ResourceList{} + for key, value := range a { + if other, found := b[key]; found { + if value.Cmp(other) <= 0 { + result[key] = *other.Copy() + continue + } + } + result[key] = *value.Copy() + } + for key, value := range b { + if _, found := result[key]; !found { + result[key] = *value.Copy() + } + } + return result +} + // Add returns the result of a + b for each named resource func Add(a api.ResourceList, b api.ResourceList) api.ResourceList { result := api.ResourceList{} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/cachesize/cachesize.go b/vendor/k8s.io/kubernetes/pkg/registry/cachesize/cachesize.go index 9bc360ff84f3..f3d05196ab75 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/cachesize/cachesize.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/cachesize/cachesize.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -28,39 +28,41 @@ import ( type Resource string const ( - ClusterRoles Resource = "clusterroles" - ClusterRoleBindings Resource = "clusterrolebindings" - Controllers Resource = "controllers" - Daemonsets Resource = "daemonsets" - Deployments Resource = "deployments" - Endpoints Resource = "endpoints" - HorizontalPodAutoscalers Resource = "horizontalpodautoscalers" - Ingress Resource = "ingress" - PodDisruptionBudget Resource = "poddisruptionbudgets" - PetSet Resource = "petset" - Jobs Resource = "jobs" - LimitRanges Resource = "limitranges" - Namespaces Resource = "namespaces" - NetworkPolicys Resource = "networkpolicies" - Nodes Resource = "nodes" - PersistentVolumes Resource = "persistentvolumes" - PersistentVolumeClaims Resource = "persistentvolumeclaims" - Pods Resource = "pods" - PodTemplates Resource = "podtemplates" - Replicasets Resource = "replicasets" - ResourceQuotas Resource = "resourcequotas" - ScheduledJobs Resource = "scheduledjobs" - Roles Resource = "roles" - RoleBindings Resource = "rolebindings" - Secrets Resource = "secrets" - ServiceAccounts Resource = "serviceaccounts" - Services Resource = "services" + CertificateSigningRequests Resource = "certificatesigningrequests" + ClusterRoles Resource = "clusterroles" + ClusterRoleBindings Resource = "clusterrolebindings" + Controllers Resource = "controllers" + Daemonsets Resource = "daemonsets" + Deployments Resource = "deployments" + Endpoints Resource = "endpoints" + HorizontalPodAutoscalers Resource = "horizontalpodautoscalers" + Ingress Resource = "ingress" + PodDisruptionBudget Resource = "poddisruptionbudgets" + PetSet Resource = "petset" + Jobs Resource = "jobs" + LimitRanges Resource = "limitranges" + Namespaces Resource = "namespaces" + NetworkPolicys Resource = "networkpolicies" + Nodes Resource = "nodes" + PersistentVolumes Resource = "persistentvolumes" + PersistentVolumeClaims Resource = "persistentvolumeclaims" + Pods Resource = "pods" + PodTemplates Resource = "podtemplates" + Replicasets Resource = "replicasets" + ResourceQuotas Resource = "resourcequotas" + ScheduledJobs Resource = "scheduledjobs" + Roles Resource = "roles" + RoleBindings Resource = "rolebindings" + Secrets Resource = "secrets" + ServiceAccounts Resource = "serviceaccounts" + Services Resource = "services" ) var watchCacheSizes map[Resource]int func init() { watchCacheSizes = make(map[Resource]int) + watchCacheSizes[CertificateSigningRequests] = 1000 watchCacheSizes[ClusterRoles] = 100 watchCacheSizes[ClusterRoleBindings] = 100 watchCacheSizes[Controllers] = 100 diff --git a/vendor/k8s.io/kubernetes/pkg/registry/certificates/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/certificates/doc.go new file mode 100644 index 000000000000..8f69902f2eab --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/certificates/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 certificates provides Registry interface and its RESTStorage +// implementation for storing CertificateSigningRequest objects. +package certificates diff --git a/vendor/k8s.io/kubernetes/pkg/registry/certificates/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/certificates/etcd/etcd.go new file mode 100644 index 000000000000..561d81c2c650 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/certificates/etcd/etcd.go @@ -0,0 +1,115 @@ +/* +Copyright 2016 The Kubernetes 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 etcd + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/rest" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/fields" + "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/registry/cachesize" + csrregistry "k8s.io/kubernetes/pkg/registry/certificates" + "k8s.io/kubernetes/pkg/registry/generic" + "k8s.io/kubernetes/pkg/registry/generic/registry" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" +) + +// REST implements a RESTStorage for CertificateSigningRequest against etcd +type REST struct { + *registry.Store +} + +// NewREST returns a registry which will store CertificateSigningRequest in the given helper +func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *ApprovalREST) { + prefix := "/certificatesigningrequests" + + newListFunc := func() runtime.Object { return &certificates.CertificateSigningRequestList{} } + storageInterface := opts.Decorator( + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.CertificateSigningRequests), + &certificates.CertificateSigningRequest{}, + prefix, + csrregistry.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) + + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &certificates.CertificateSigningRequest{} }, + NewListFunc: newListFunc, + KeyRootFunc: func(ctx api.Context) string { + return prefix + }, + KeyFunc: func(ctx api.Context, id string) (string, error) { + return registry.NoNamespaceKeyFunc(ctx, prefix, id) + }, + ObjectNameFunc: func(obj runtime.Object) (string, error) { + return obj.(*certificates.CertificateSigningRequest).Name, nil + }, + PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { + return csrregistry.Matcher(label, field) + }, + QualifiedResource: certificates.Resource("certificatesigningrequests"), + DeleteCollectionWorkers: opts.DeleteCollectionWorkers, + + CreateStrategy: csrregistry.Strategy, + UpdateStrategy: csrregistry.Strategy, + + Storage: storageInterface, + } + + // Subresources use the same store and creation strategy, which only + // allows empty subs. Updates to an existing subresource are handled by + // dedicated strategies. + statusStore := *store + statusStore.UpdateStrategy = csrregistry.StatusStrategy + + approvalStore := *store + approvalStore.UpdateStrategy = csrregistry.ApprovalStrategy + + return &REST{store}, &StatusREST{store: &statusStore}, &ApprovalREST{store: &approvalStore} +} + +// StatusREST implements the REST endpoint for changing the status of a CSR. +type StatusREST struct { + store *registry.Store +} + +func (r *StatusREST) New() runtime.Object { + return &certificates.CertificateSigningRequest{} +} + +// Update alters the status subset of an object. +func (r *StatusREST) Update(ctx api.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { + return r.store.Update(ctx, name, objInfo) +} + +// ApprovalREST implements the REST endpoint for changing the approval state of a CSR. +type ApprovalREST struct { + store *registry.Store +} + +func (r *ApprovalREST) New() runtime.Object { + return &certificates.CertificateSigningRequest{} +} + +// Update alters the approval subset of an object. +func (r *ApprovalREST) Update(ctx api.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) { + return r.store.Update(ctx, name, objInfo) +} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/certificates/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/certificates/registry.go new file mode 100644 index 000000000000..59142125c643 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/certificates/registry.go @@ -0,0 +1,92 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/rest" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/watch" +) + +// Registry is an interface for things that know how to store CSRs. +type Registry interface { + ListCSRs(ctx api.Context, options *api.ListOptions) (*certificates.CertificateSigningRequestList, error) + CreateCSR(ctx api.Context, csr *certificates.CertificateSigningRequest) error + UpdateCSR(ctx api.Context, csr *certificates.CertificateSigningRequest) error + GetCSR(ctx api.Context, csrID string) (*certificates.CertificateSigningRequest, error) + DeleteCSR(ctx api.Context, csrID string) error + WatchCSRs(ctx api.Context, options *api.ListOptions) (watch.Interface, error) +} + +// storage puts strong typing around storage calls +type storage struct { + rest.StandardStorage +} + +// NewRegistry returns a new Registry interface for the given Storage. Any mismatched +// types will panic. +func NewRegistry(s rest.StandardStorage) Registry { + return &storage{s} +} + +func (s *storage) ListCSRs(ctx api.Context, options *api.ListOptions) (*certificates.CertificateSigningRequestList, error) { + obj, err := s.List(ctx, options) + if err != nil { + return nil, err + } + + return obj.(*certificates.CertificateSigningRequestList), nil +} + +func (s *storage) CreateCSR(ctx api.Context, csr *certificates.CertificateSigningRequest) error { + // Inject user.Info from request context if available and no + // information was supplied. Don't smash existing user information + // since it should be possible for a broadly-scoped user to request a + // certificate on behalf of a more limited user. + if user, ok := api.UserFrom(ctx); ok { + if csr.Spec.Username == "" { + csr.Spec.Username = user.GetName() + csr.Spec.UID = user.GetUID() + csr.Spec.Groups = user.GetGroups() + } + } + _, err := s.Create(ctx, csr) + return err +} + +func (s *storage) UpdateCSR(ctx api.Context, csr *certificates.CertificateSigningRequest) error { + _, _, err := s.Update(ctx, csr.Name, rest.DefaultUpdatedObjectInfo(csr, api.Scheme)) + return err +} + +func (s *storage) WatchCSRs(ctx api.Context, options *api.ListOptions) (watch.Interface, error) { + return s.Watch(ctx, options) +} + +func (s *storage) GetCSR(ctx api.Context, name string) (*certificates.CertificateSigningRequest, error) { + obj, err := s.Get(ctx, name) + if err != nil { + return nil, err + } + return obj.(*certificates.CertificateSigningRequest), nil +} + +func (s *storage) DeleteCSR(ctx api.Context, name string) error { + _, err := s.Delete(ctx, name, nil) + return err +} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/certificates/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/certificates/strategy.go new file mode 100644 index 000000000000..4ea468645e20 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/certificates/strategy.go @@ -0,0 +1,177 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/certificates" + "k8s.io/kubernetes/pkg/apis/certificates/validation" + "k8s.io/kubernetes/pkg/fields" + "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/registry/generic" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/validation/field" +) + +// csrStrategy implements behavior for CSRs +type csrStrategy struct { + runtime.ObjectTyper + api.NameGenerator +} + +// csrStrategy is the default logic that applies when creating and updating +// CSR objects. +var Strategy = csrStrategy{api.Scheme, api.SimpleNameGenerator} + +// NamespaceScoped is true for CSRs. +func (csrStrategy) NamespaceScoped() bool { + return false +} + +// AllowCreateOnUpdate is false for CSRs. +func (csrStrategy) AllowCreateOnUpdate() bool { + return false +} + +// PrepareForCreate clears fields that are not allowed to be set by end users +// on creation. Users cannot create any derived information, but we expect +// information about the requesting user to be injected by the registry +// interface. Clear everything else. +// TODO: check these ordering assumptions. better way to inject user info? +func (csrStrategy) PrepareForCreate(obj runtime.Object) { + csr := obj.(*certificates.CertificateSigningRequest) + + // Be explicit that users cannot create pre-approved certificate requests. + csr.Status = certificates.CertificateSigningRequestStatus{} + csr.Status.Conditions = []certificates.CertificateSigningRequestCondition{} +} + +// PrepareForUpdate clears fields that are not allowed to be set by end users +// on update. Certificate requests are immutable after creation except via subresources. +func (csrStrategy) PrepareForUpdate(obj, old runtime.Object) { + newCSR := obj.(*certificates.CertificateSigningRequest) + oldCSR := old.(*certificates.CertificateSigningRequest) + + newCSR.Spec = oldCSR.Spec + newCSR.Status = oldCSR.Status +} + +// Validate validates a new CSR. Validation must check for a correct signature. +func (csrStrategy) Validate(ctx api.Context, obj runtime.Object) field.ErrorList { + csr := obj.(*certificates.CertificateSigningRequest) + return validation.ValidateCertificateSigningRequest(csr) +} + +// Canonicalize normalizes the object after validation (which includes a signature check). +func (csrStrategy) Canonicalize(obj runtime.Object) {} + +// ValidateUpdate is the default update validation for an end user. +func (csrStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList { + oldCSR := old.(*certificates.CertificateSigningRequest) + newCSR := obj.(*certificates.CertificateSigningRequest) + return validation.ValidateCertificateSigningRequestUpdate(newCSR, oldCSR) +} + +// If AllowUnconditionalUpdate() is true and the object specified by +// the user does not have a resource version, then generic Update() +// populates it with the latest version. Else, it checks that the +// version specified by the user matches the version of latest etcd +// object. +func (csrStrategy) AllowUnconditionalUpdate() bool { + return true +} + +func (s csrStrategy) Export(obj runtime.Object, exact bool) error { + csr, ok := obj.(*certificates.CertificateSigningRequest) + if !ok { + // unexpected programmer error + return fmt.Errorf("unexpected object: %v", obj) + } + s.PrepareForCreate(obj) + if exact { + return nil + } + // CSRs allow direct subresource edits, we clear them without exact so the CSR value can be reused. + csr.Status = certificates.CertificateSigningRequestStatus{} + return nil +} + +// Storage strategy for the Status subresource +type csrStatusStrategy struct { + csrStrategy +} + +var StatusStrategy = csrStatusStrategy{Strategy} + +func (csrStatusStrategy) PrepareForUpdate(obj, old runtime.Object) { + newCSR := obj.(*certificates.CertificateSigningRequest) + oldCSR := old.(*certificates.CertificateSigningRequest) + + // Updating the Status should only update the Status and not the spec + // or approval conditions. The intent is to separate the concerns of + // approval and certificate issuance. + newCSR.Spec = oldCSR.Spec + newCSR.Status.Conditions = oldCSR.Status.Conditions +} + +func (csrStatusStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList { + return validation.ValidateCertificateSigningRequestUpdate(obj.(*certificates.CertificateSigningRequest), old.(*certificates.CertificateSigningRequest)) +} + +// Canonicalize normalizes the object after validation. +func (csrStatusStrategy) Canonicalize(obj runtime.Object) { +} + +// Storage strategy for the Approval subresource +type csrApprovalStrategy struct { + csrStrategy +} + +var ApprovalStrategy = csrApprovalStrategy{Strategy} + +func (csrApprovalStrategy) PrepareForUpdate(obj, old runtime.Object) { + newCSR := obj.(*certificates.CertificateSigningRequest) + oldCSR := old.(*certificates.CertificateSigningRequest) + + // Updating the approval should only update the conditions. + newCSR.Spec = oldCSR.Spec + oldCSR.Status.Conditions = newCSR.Status.Conditions + newCSR.Status = oldCSR.Status +} + +func (csrApprovalStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList { + return validation.ValidateCertificateSigningRequestUpdate(obj.(*certificates.CertificateSigningRequest), old.(*certificates.CertificateSigningRequest)) +} + +// Matcher returns a generic matcher for a given label and field selector. +func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { + return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { + sa, ok := obj.(*certificates.CertificateSigningRequest) + if !ok { + return false, fmt.Errorf("not a CertificateSigningRequest") + } + fields := SelectableFields(sa) + return label.Matches(labels.Set(sa.Labels)) && field.Matches(fields), nil + }) +} + +// SelectableFields returns a label set that can be used for filter selection +func SelectableFields(obj *certificates.CertificateSigningRequest) labels.Set { + return labels.Set{} +} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/doc.go index 89c0edef4d3a..11dea907de9f 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/etcd/etcd.go index e33ffaa6bb63..86b39dcfb9a9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/clusterrole" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for ClusterRole against etcd @@ -35,7 +34,7 @@ type REST struct { // NewREST returns a RESTStorage object that will work against ClusterRole objects. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/clusterroles" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &rbac.ClusterRoleList{} } storageInterface := opts.Decorator( @@ -45,6 +44,7 @@ func NewREST(opts generic.RESTOptions) *REST { prefix, clusterrole.Strategy, newListFunc, + storage.NoTriggerPublisher, ) store := ®istry.Store{ @@ -59,9 +59,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*rbac.ClusterRole).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return clusterrole.Matcher(label, field) - }, + PredicateFunc: clusterrole.Matcher, QualifiedResource: rbac.Resource("clusterroles"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/policybased/storage.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/policybased/storage.go index 8e9f5cc9728f..3c6a4a63e008 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/policybased/storage.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/policybased/storage.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/registry.go index 701fc55a0b98..4312307c6712 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/strategy.go index dc7e1e056549..cf24c248eef0 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrole/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/doc.go index 8eb13084ad40..8df6c7cc2018 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/etcd/etcd.go index c49b9b2dc867..50c621800b3c 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/clusterrolebinding" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for ClusterRoleBinding against etcd @@ -35,7 +34,7 @@ type REST struct { // NewREST returns a RESTStorage object that will work against ClusterRoleBinding objects. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/clusterrolebindings" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &rbac.ClusterRoleBindingList{} } storageInterface := opts.Decorator( @@ -45,6 +44,7 @@ func NewREST(opts generic.RESTOptions) *REST { prefix, clusterrolebinding.Strategy, newListFunc, + storage.NoTriggerPublisher, ) store := ®istry.Store{ @@ -59,9 +59,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*rbac.ClusterRoleBinding).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return clusterrolebinding.Matcher(label, field) - }, + PredicateFunc: clusterrolebinding.Matcher, QualifiedResource: rbac.Resource("clusterrolebindings"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/policybased/storage.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/policybased/storage.go index 358a36bd8cf0..bc6da0569df4 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/policybased/storage.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/policybased/storage.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/registry.go index 7f96eaa4a142..c7738640aea9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/strategy.go index 3dd1bf7e5976..c8eac7ca5b85 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/clusterrolebinding/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/doc.go index 85248b33af51..af0672af8381 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/rest.go b/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/rest.go index 968b90bbbc0e..3de63e0e9fdc 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/rest.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/componentstatus/rest.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/configmap/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/configmap/doc.go index ec8cc087d834..dd414e3ce470 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/configmap/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/configmap/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/configmap/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/configmap/etcd/etcd.go index 801e94d2ec30..66fd775d2080 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/configmap/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/configmap/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/registry/configmap" "k8s.io/kubernetes/pkg/registry/generic" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/registry/generic/registry" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for ConfigMap against etcd @@ -32,11 +32,11 @@ type REST struct { // NewREST returns a RESTStorage object that will work with ConfigMap objects. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/configmaps" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.ConfigMapList{} } storageInterface := opts.Decorator( - opts.Storage, 100, &api.ConfigMap{}, prefix, configmap.Strategy, newListFunc) + opts.Storage, 100, &api.ConfigMap{}, prefix, configmap.Strategy, newListFunc, storage.NoTriggerPublisher) store := ®istry.Store{ NewFunc: func() runtime.Object { diff --git a/vendor/k8s.io/kubernetes/pkg/registry/configmap/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/configmap/registry.go index ff052e377d3d..b3fcc2450780 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/configmap/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/configmap/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/configmap/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/configmap/strategy.go index a07a7b917183..f6ddeb4132e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/configmap/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/configmap/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/controller/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/controller/doc.go index 4c0d14fabbfb..3d5e22410432 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/controller/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/controller/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/controller/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/controller/etcd/etcd.go index a6607d66c15b..fed90eaf0ab2 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/controller/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/controller/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,13 +26,13 @@ import ( "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/autoscaling" "k8s.io/kubernetes/pkg/apis/autoscaling/validation" - "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/controller" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // ControllerStorage includes dummy storage for Replication Controllers and for Scale subresource. @@ -59,11 +59,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against replication controllers. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/controllers" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.ReplicationControllerList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Controllers), &api.ReplicationController{}, prefix, controller.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Controllers), + &api.ReplicationController{}, + prefix, + controller.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.ReplicationController{} }, @@ -85,9 +92,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*api.ReplicationController).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return controller.MatchController(label, field) - }, + PredicateFunc: controller.MatchController, QualifiedResource: api.Resource("replicationcontrollers"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/controller/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/controller/registry.go index a8eea1dde3b9..2455eca8212e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/controller/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/controller/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/controller/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/controller/strategy.go index 9fa5bebdac67..e4e879487094 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/controller/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/controller/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/doc.go index 435b0fe615b4..2c1697402b5d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/etcd/etcd.go index c5df8cb0c282..408e56c2c39d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/daemonset" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // rest implements a RESTStorage for DaemonSets against etcd @@ -36,11 +35,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against DaemonSets. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/daemonsets" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &extensions.DaemonSetList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Daemonsets), &extensions.DaemonSet{}, prefix, daemonset.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Daemonsets), + &extensions.DaemonSet{}, + prefix, + daemonset.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensions.DaemonSet{} }, @@ -62,9 +68,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*extensions.DaemonSet).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return daemonset.MatchDaemonSet(label, field) - }, + PredicateFunc: daemonset.MatchDaemonSet, QualifiedResource: extensions.Resource("daemonsets"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/strategy.go index 044d779b43e4..88d3f1c8644e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/daemonset/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/daemonset/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/deployment/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/deployment/doc.go index 184fa30d3a48..6bc30adfacba 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/deployment/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/deployment/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/deployment/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/deployment/etcd/etcd.go index e09f88120478..298bcceedecd 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/deployment/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/deployment/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,8 +25,6 @@ import ( "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" extvalidation "k8s.io/kubernetes/pkg/apis/extensions/validation" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/deployment" "k8s.io/kubernetes/pkg/registry/generic" @@ -61,11 +59,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against deployments. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *RollbackREST) { - prefix := "/deployments" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &extensions.DeploymentList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Deployments), &extensions.Deployment{}, prefix, deployment.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Deployments), + &extensions.Deployment{}, + prefix, + deployment.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensions.Deployment{} }, @@ -86,9 +91,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *RollbackREST) { return obj.(*extensions.Deployment).Name, nil }, // Used to match objects based on labels/fields for list. - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return deployment.MatchDeployment(label, field) - }, + PredicateFunc: deployment.MatchDeployment, QualifiedResource: extensions.Resource("deployments"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/deployment/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/deployment/registry.go index f9ddf358c65f..73a02288cf8e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/deployment/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/deployment/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/deployment/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/deployment/strategy.go index 574cc0583a63..09fdbfb260a2 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/deployment/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/deployment/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/doc.go index 05141506cd7b..8d8bffd52f3e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/etcd/etcd.go index 71658b4c6af7..cd4d45cfc190 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,13 +18,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/endpoint" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -33,11 +32,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against endpoints. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/services/endpoints" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.EndpointsList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Endpoints), &api.Endpoints{}, prefix, endpoint.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Endpoints), + &api.Endpoints{}, + prefix, + endpoint.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Endpoints{} }, @@ -51,9 +57,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Endpoints).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return endpoint.MatchEndpoints(label, field) - }, + PredicateFunc: endpoint.MatchEndpoints, QualifiedResource: api.Resource("endpoints"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/registry.go index 84907189224e..fa415921e236 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/strategy.go index f6f6634a3223..24cc6824e4f9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/endpoint/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/endpoint/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/event/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/event/doc.go index 67633f235fbb..5c5446d61a69 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/event/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/event/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/event/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/event/etcd/etcd.go index c90da35fb140..fb5d3de69741 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/event/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/event/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/event" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" @@ -32,7 +30,7 @@ type REST struct { // NewREST returns a RESTStorage object that will work against events. func NewREST(opts generic.RESTOptions, ttl uint64) *REST { - prefix := "/events" + prefix := "/" + opts.ResourcePrefix // We explicitly do NOT do any decoration here - switching on Cacher // for events will lead to too high memory consumption. @@ -50,9 +48,7 @@ func NewREST(opts generic.RESTOptions, ttl uint64) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Event).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return event.MatchEvent(label, field) - }, + PredicateFunc: event.MatchEvent, TTLFunc: func(runtime.Object, uint64, bool) (uint64, error) { return ttl, nil }, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/event/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/event/strategy.go index d9f628e76837..292c87f7f3dc 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/event/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/event/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/experimental/controller/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/experimental/controller/etcd/etcd.go index 58ce0af0e0dc..ee8a15bcf7aa 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/experimental/controller/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/experimental/controller/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/doc.go index 2486e9b74266..47bb95304046 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/matcher.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/matcher.go index 08e2df7b4563..3c1b7ecaaeb3 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/matcher.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/matcher.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import ( "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // AttrFunc returns label and field sets for List or Watch to compare against, or an error. @@ -50,9 +51,10 @@ func MergeFieldsSets(source fields.Set, fragment fields.Set) fields.Set { // SelectionPredicate implements a generic predicate that can be passed to // GenericRegistry's List or Watch methods. Implements the Matcher interface. type SelectionPredicate struct { - Label labels.Selector - Field fields.Selector - GetAttrs AttrFunc + Label labels.Selector + Field fields.Selector + GetAttrs AttrFunc + IndexFields []string } // Matches returns true if the given object's labels and fields (as @@ -79,6 +81,20 @@ func (s *SelectionPredicate) MatchesSingle() (string, bool) { return "", false } +// For any index defined by IndexFields, if a matcher can match only (a subset) +// of objects that return for a given index, a pair (, ) +// wil be returned. +// TODO: Consider supporting also labels. +func (s *SelectionPredicate) MatcherIndex() []storage.MatchValue { + var result []storage.MatchValue + for _, field := range s.IndexFields { + if value, ok := s.Field.RequiresExactMatch(field); ok { + result = append(result, storage.MatchValue{IndexName: field, Value: value}) + } + } + return result +} + // Matcher can return true if an object matches the Matcher's selection // criteria. If it is known that the matcher will match only a single object // then MatchesSingle should return the key of that object and true. This is an @@ -93,9 +109,10 @@ type Matcher interface { // include the object's namespace. MatchesSingle() (key string, matchesSingleObject bool) - // TODO: when we start indexing objects, add something like the below: - // MatchesIndices() (indexName []string, indexValue []string) - // where indexName/indexValue are the same length. + // For any known index, if a matcher can match only (a subset) of objects + // that return for a given index, a pair (, ) + // will be returned. + MatcherIndex() []storage.MatchValue } // MatcherFunc makes a matcher from the provided function. For easy definition @@ -117,6 +134,11 @@ func (m matcherFunc) MatchesSingle() (string, bool) { return "", false } +// MatcherIndex always returns empty list. +func (m matcherFunc) MatcherIndex() []storage.MatchValue { + return nil +} + // MatchOnKey returns a matcher that will send only the object matching key // through the matching function f. For testing! // Note: use SelectionPredicate above for real code! diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/options.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/options.go index eea52c995b13..39965731bc3b 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/options.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/options.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,4 +25,6 @@ type RESTOptions struct { Storage pkgstorage.Interface Decorator StorageDecorator DeleteCollectionWorkers int + + ResourcePrefix string } diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/doc.go index ee972408dce2..643a6fb7b659 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/storage_factory.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/storage_factory.go index f1c265113bf9..3b96e77c135e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/storage_factory.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/storage_factory.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,8 +30,27 @@ func StorageWithCacher( objectType runtime.Object, resourcePrefix string, scopeStrategy rest.NamespaceScopedStrategy, - newListFunc func() runtime.Object) storage.Interface { - return storage.NewCacher( - storageInterface, capacity, etcdstorage.APIObjectVersioner{}, - objectType, resourcePrefix, scopeStrategy, newListFunc) + newListFunc func() runtime.Object, + triggerFunc storage.TriggerPublisherFunc) storage.Interface { + + config := storage.CacherConfig{ + CacheCapacity: capacity, + Storage: storageInterface, + Versioner: etcdstorage.APIObjectVersioner{}, + Type: objectType, + ResourcePrefix: resourcePrefix, + NewListFunc: newListFunc, + TriggerPublisherFunc: triggerFunc, + } + if scopeStrategy.NamespaceScoped() { + config.KeyFunc = func(obj runtime.Object) (string, error) { + return storage.NamespaceKeyFunc(resourcePrefix, obj) + } + } else { + config.KeyFunc = func(obj runtime.Object) (string, error) { + return storage.NoNamespaceKeyFunc(resourcePrefix, obj) + } + } + + return storage.NewCacherFromConfig(config) } diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/store.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/store.go index e5f120124d83..9234e006ea32 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/store.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/registry/store.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -190,10 +190,10 @@ func (e *Store) List(ctx api.Context, options *api.ListOptions) (runtime.Object, // ListPredicate returns a list of all the items matching m. func (e *Store) ListPredicate(ctx api.Context, m generic.Matcher, options *api.ListOptions) (runtime.Object, error) { list := e.NewListFunc() - filterFunc := e.filterAndDecorateFunction(m) + filter := e.createFilter(m) if name, ok := m.MatchesSingle(); ok { if key, err := e.KeyFunc(ctx, name); err == nil { - err := e.Storage.GetToList(ctx, key, filterFunc, list) + err := e.Storage.GetToList(ctx, key, filter, list) return list, storeerr.InterpretListError(err, e.QualifiedResource) } // if we cannot extract a key based on the current context, the optimization is skipped @@ -202,7 +202,7 @@ func (e *Store) ListPredicate(ctx api.Context, m generic.Matcher, options *api.L if options == nil { options = &api.ListOptions{ResourceVersion: "0"} } - err := e.Storage.List(ctx, e.KeyRootFunc(ctx), options.ResourceVersion, filterFunc, list) + err := e.Storage.List(ctx, e.KeyRootFunc(ctx), options.ResourceVersion, filter, list) return list, storeerr.InterpretListError(err, e.QualifiedResource) } @@ -479,6 +479,10 @@ func markAsDeleting(obj runtime.Object) (err error) { return kerr } now := unversioned.NewTime(time.Now()) + // This handles Generation bump for resources that don't support graceful deletion. For resources that support graceful deletion is handle in pkg/api/rest/delete.go + if objectMeta.DeletionTimestamp == nil && objectMeta.Generation > 0 { + objectMeta.Generation++ + } objectMeta.DeletionTimestamp = &now var zero int64 = 0 objectMeta.DeletionGracePeriodSeconds = &zero @@ -794,23 +798,23 @@ func (e *Store) Watch(ctx api.Context, options *api.ListOptions) (watch.Interfac // WatchPredicate starts a watch for the items that m matches. func (e *Store) WatchPredicate(ctx api.Context, m generic.Matcher, resourceVersion string) (watch.Interface, error) { - filterFunc := e.filterAndDecorateFunction(m) + filter := e.createFilter(m) if name, ok := m.MatchesSingle(); ok { if key, err := e.KeyFunc(ctx, name); err == nil { if err != nil { return nil, err } - return e.Storage.Watch(ctx, key, resourceVersion, filterFunc) + return e.Storage.Watch(ctx, key, resourceVersion, filter) } // if we cannot extract a key based on the current context, the optimization is skipped } - return e.Storage.WatchList(ctx, e.KeyRootFunc(ctx), resourceVersion, filterFunc) + return e.Storage.WatchList(ctx, e.KeyRootFunc(ctx), resourceVersion, filter) } -func (e *Store) filterAndDecorateFunction(m generic.Matcher) func(runtime.Object) bool { - return func(obj runtime.Object) bool { +func (e *Store) createFilter(m generic.Matcher) storage.Filter { + filterFunc := func(obj runtime.Object) bool { matches, err := m.Matches(obj) if err != nil { glog.Errorf("unable to match watch: %v", err) @@ -824,6 +828,7 @@ func (e *Store) filterAndDecorateFunction(m generic.Matcher) func(runtime.Object } return matches } + return storage.NewSimpleFilter(filterFunc, m.MatcherIndex) } // calculateTTL is a helper for retrieving the updated TTL for an object or returning an error diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/doc.go index fef461387795..9696087fb234 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/proxy.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/proxy.go index ca28831c8c0f..81a297bc3071 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/proxy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/proxy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/response_checker.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/response_checker.go index b0c61075c135..c0be9d27f0ff 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/response_checker.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/response_checker.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/streamer.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/streamer.go index afa9eb5b5dc0..2f13f25d3a38 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/streamer.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/rest/streamer.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/generic/storage_decorator.go b/vendor/k8s.io/kubernetes/pkg/registry/generic/storage_decorator.go index 70109efe3364..965a272e2772 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/generic/storage_decorator.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/generic/storage_decorator.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,7 +30,8 @@ type StorageDecorator func( objectType runtime.Object, resourcePrefix string, scopeStrategy rest.NamespaceScopedStrategy, - newListFunc func() runtime.Object) storage.Interface + newListFunc func() runtime.Object, + trigger storage.TriggerPublisherFunc) storage.Interface // Returns given 'storageInterface' without any decoration. func UndecoratedStorage( @@ -39,6 +40,7 @@ func UndecoratedStorage( objectType runtime.Object, resourcePrefix string, scopeStrategy rest.NamespaceScopedStrategy, - newListFunc func() runtime.Object) storage.Interface { + newListFunc func() runtime.Object, + trigger storage.TriggerPublisherFunc) storage.Interface { return storageInterface } diff --git a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/doc.go index a628ee1b9496..349ff005443d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd/etcd.go index 614455924c2c..3b304d104327 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/autoscaling" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -35,11 +34,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against horizontal pod autoscalers. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/horizontalpodautoscalers" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &autoscaling.HorizontalPodAutoscalerList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.HorizontalPodAutoscalers), &autoscaling.HorizontalPodAutoscaler{}, prefix, horizontalpodautoscaler.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.HorizontalPodAutoscalers), + &autoscaling.HorizontalPodAutoscaler{}, + prefix, + horizontalpodautoscaler.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &autoscaling.HorizontalPodAutoscaler{} }, @@ -60,9 +66,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*autoscaling.HorizontalPodAutoscaler).Name, nil }, // Used to match objects based on labels/fields for list - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return horizontalpodautoscaler.MatchAutoscaler(label, field) - }, + PredicateFunc: horizontalpodautoscaler.MatchAutoscaler, QualifiedResource: autoscaling.Resource("horizontalpodautoscalers"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/strategy.go index 419beb6b1b55..6a0133217a23 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/horizontalpodautoscaler/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -84,7 +84,7 @@ func (autoscalerStrategy) AllowUnconditionalUpdate() bool { return true } -func AutoscalerToSelectableFields(limitRange *autoscaling.HorizontalPodAutoscaler) fields.Set { +func AutoscalerToSelectableFields(hpa *autoscaling.HorizontalPodAutoscaler) fields.Set { return fields.Set{} } diff --git a/vendor/k8s.io/kubernetes/pkg/registry/ingress/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/ingress/doc.go index 5a6272cc546b..42fb63fc57ad 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/ingress/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/ingress/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/ingress/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/ingress/etcd/etcd.go index 185d4331c296..9c1b7f9bd4c6 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/ingress/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/ingress/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" ingress "k8s.io/kubernetes/pkg/registry/ingress" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // rest implements a RESTStorage for replication controllers against etcd @@ -36,11 +35,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against replication controllers. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/ingress" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &extensions.IngressList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Ingress), &extensions.Ingress{}, prefix, ingress.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Ingress), + &extensions.Ingress{}, + prefix, + ingress.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensions.Ingress{} }, @@ -62,9 +68,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*extensions.Ingress).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return ingress.MatchIngress(label, field) - }, + PredicateFunc: ingress.MatchIngress, QualifiedResource: extensions.Resource("ingresses"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/ingress/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/ingress/strategy.go index 92a596a5e574..0c4d434c3949 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/ingress/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/ingress/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/job/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/job/doc.go index d6351371c5a5..f34b36abc045 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/job/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/job/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/job/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/job/etcd/etcd.go index 726fb63ab1bf..dbef9a38c285 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/job/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/job/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/batch" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/job" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for jobs against etcd @@ -36,11 +35,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against Jobs. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/jobs" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &batch.JobList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Jobs), &batch.Job{}, prefix, job.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Jobs), + &batch.Job{}, + prefix, + job.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &batch.Job{} }, @@ -62,9 +68,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*batch.Job).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return job.MatchJob(label, field) - }, + PredicateFunc: job.MatchJob, QualifiedResource: batch.Resource("jobs"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/job/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/job/strategy.go index 3c362326e73a..f2755f52ab1f 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/job/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/job/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/doc.go index 6c4214a040bc..4a6ab76c5c45 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/etcd/etcd.go index 620cc829ff86..4aac57ca1db2 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,13 +18,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/limitrange" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -33,11 +32,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against horizontal pod autoscalers. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/limitranges" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.LimitRangeList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.LimitRanges), &api.LimitRange{}, prefix, limitrange.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.LimitRanges), + &api.LimitRange{}, + prefix, + limitrange.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.LimitRange{} }, @@ -51,9 +57,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.LimitRange).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return limitrange.MatchLimitRange(label, field) - }, + PredicateFunc: limitrange.MatchLimitRange, QualifiedResource: api.Resource("limitranges"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/strategy.go index ff36fe68d2ae..aa424eb6f439 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/limitrange/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/limitrange/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/namespace/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/namespace/doc.go index 206290037ed5..f618932fe2cf 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/namespace/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/namespace/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/namespace/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/namespace/etcd/etcd.go index cfecfd43747c..eaf1293cee81 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/namespace/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/namespace/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,8 +24,6 @@ import ( storageerr "k8s.io/kubernetes/pkg/api/errors/storage" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" @@ -52,11 +50,18 @@ type FinalizeREST struct { // NewREST returns a RESTStorage object that will work against namespaces. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *FinalizeREST) { - prefix := "/namespaces" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.NamespaceList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Namespaces), &api.Namespace{}, prefix, namespace.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Namespaces), + &api.Namespace{}, + prefix, + namespace.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Namespace{} }, @@ -70,9 +75,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *FinalizeREST) { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Namespace).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return namespace.MatchNamespace(label, field) - }, + PredicateFunc: namespace.MatchNamespace, QualifiedResource: api.Resource("namespaces"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/namespace/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/namespace/registry.go index b78d3afd7feb..f30857fd47e9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/namespace/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/namespace/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/namespace/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/namespace/strategy.go index 3b069847c362..b27826450f5e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/namespace/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/namespace/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/doc.go index 2cc5a21e9b54..3535feb2422c 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/etcd/etcd.go index e3dea0f18c06..fc33c9283c2d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" extensionsapi "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/networkpolicy" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // rest implements a RESTStorage for network policies against etcd @@ -35,11 +34,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against network policies. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/networkpolicies" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &extensionsapi.NetworkPolicyList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.NetworkPolicys), &extensionsapi.NetworkPolicy{}, prefix, networkpolicy.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.NetworkPolicys), + &extensionsapi.NetworkPolicy{}, + prefix, + networkpolicy.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensionsapi.NetworkPolicy{} }, @@ -61,9 +67,7 @@ func NewREST(opts generic.RESTOptions) *REST { return obj.(*extensionsapi.NetworkPolicy).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return networkpolicy.MatchNetworkPolicy(label, field) - }, + PredicateFunc: networkpolicy.MatchNetworkPolicy, QualifiedResource: extensionsapi.Resource("networkpolicies"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/strategy.go index b8217ac50c2e..e12165e26add 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/networkpolicy/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/node/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/node/doc.go index cd604b4ab410..79a95fd3d38d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/node/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/node/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/node/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/node/etcd/etcd.go index c37af18eab72..e360e8a741f0 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/node/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/node/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -64,13 +64,19 @@ func (r *StatusREST) Update(ctx api.Context, name string, objInfo rest.UpdatedOb return r.store.Update(ctx, name, objInfo) } -// NewREST returns a RESTStorage object that will work against nodes. +// NewStorage returns a NodeStorage object that will work against nodes. func NewStorage(opts generic.RESTOptions, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper) NodeStorage { - prefix := "/minions" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.NodeList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Nodes), &api.Node{}, prefix, node.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Nodes), + &api.Node{}, + prefix, + node.Strategy, + newListFunc, + node.NodeNameTriggerFunc) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Node{} }, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/node/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/node/registry.go index aae18bfc2182..71e194dcc186 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/node/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/node/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/node/rest/proxy.go b/vendor/k8s.io/kubernetes/pkg/registry/node/rest/proxy.go index 1e80327cfe2e..afe0bd9a8665 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/node/rest/proxy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/node/rest/proxy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/node/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/node/strategy.go index 9085090b8c19..83aef5e16711 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/node/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/node/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ import ( "k8s.io/kubernetes/pkg/master/ports" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" + pkgstorage "k8s.io/kubernetes/pkg/storage" utilnet "k8s.io/kubernetes/pkg/util/net" nodeutil "k8s.io/kubernetes/pkg/util/node" "k8s.io/kubernetes/pkg/util/validation/field" @@ -157,9 +158,16 @@ func MatchNode(label labels.Selector, field fields.Selector) generic.Matcher { } return labels.Set(nodeObj.ObjectMeta.Labels), NodeToSelectableFields(nodeObj), nil }, + IndexFields: []string{"metadata.name"}, } } +func NodeNameTriggerFunc(obj runtime.Object) []pkgstorage.MatchValue { + node := obj.(*api.Node) + result := pkgstorage.MatchValue{IndexName: "metadata.name", Value: node.ObjectMeta.Name} + return []pkgstorage.MatchValue{result} +} + // ResourceLocation returns an URL and transport which one can use to send traffic for the specified node. func ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx api.Context, id string) (*url.URL, http.RoundTripper, error) { schemeReq, name, portReq, valid := utilnet.SplitSchemeNamePort(id) diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/doc.go index 0f0cd6c912ec..06fda296fa90 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/etcd/etcd.go index 53d92d827b10..217563c60946 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/persistentvolume" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -34,11 +33,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against persistent volumes. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/persistentvolumes" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.PersistentVolumeList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.PersistentVolumes), &api.PersistentVolume{}, prefix, persistentvolume.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.PersistentVolumes), + &api.PersistentVolume{}, + prefix, + persistentvolume.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.PersistentVolume{} }, @@ -52,9 +58,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.PersistentVolume).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return persistentvolume.MatchPersistentVolumes(label, field) - }, + PredicateFunc: persistentvolume.MatchPersistentVolumes, QualifiedResource: api.Resource("persistentvolumes"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/strategy.go index b8920c4708f3..1c1039434eea 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolume/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/doc.go index f58b1682ce39..c6950ee8c0f2 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/etcd/etcd.go index f724bf887503..b7cf36c3cbf5 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/persistentvolumeclaim" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -34,11 +33,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against persistent volume claims. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/persistentvolumeclaims" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.PersistentVolumeClaimList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.PersistentVolumeClaims), &api.PersistentVolumeClaim{}, prefix, persistentvolumeclaim.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.PersistentVolumeClaims), + &api.PersistentVolumeClaim{}, + prefix, + persistentvolumeclaim.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.PersistentVolumeClaim{} }, @@ -52,9 +58,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.PersistentVolumeClaim).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return persistentvolumeclaim.MatchPersistentVolumeClaim(label, field) - }, + PredicateFunc: persistentvolumeclaim.MatchPersistentVolumeClaim, QualifiedResource: api.Resource("persistentvolumeclaims"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/strategy.go index 100ad6a4cbdd..2cf2b6483383 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/persistentvolumeclaim/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/petset/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/petset/doc.go index 960710dd4f8b..fe54856993ff 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/petset/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/petset/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/petset/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/petset/etcd/etcd.go index 1d9a92a83f18..f3ca06d72ad1 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/petset/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/petset/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" appsapi "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/petset" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // rest implements a RESTStorage for replication controllers against etcd @@ -36,11 +35,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against replication controllers. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/petsets" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &appsapi.PetSetList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.PetSet), &appsapi.PetSet{}, prefix, petset.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.PetSet), + &appsapi.PetSet{}, + prefix, + petset.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &appsapi.PetSet{} }, @@ -62,9 +68,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*appsapi.PetSet).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return petset.MatchPetSet(label, field) - }, + PredicateFunc: petset.MatchPetSet, QualifiedResource: appsapi.Resource("petsets"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/petset/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/petset/strategy.go index 80bff2a5ddee..c315cbd6a303 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/petset/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/petset/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/pod/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/pod/doc.go index 3c6d2f3c17c7..d2294852b513 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/pod/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/pod/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/pod/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/pod/etcd/etcd.go index 8e9939a3df16..fbc201b74d85 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/pod/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/pod/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,9 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/validation" - "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/kubelet/client" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" @@ -59,11 +57,18 @@ type REST struct { // NewStorage returns a RESTStorage object that will work against pods. func NewStorage(opts generic.RESTOptions, k client.ConnectionInfoGetter, proxyTransport http.RoundTripper) PodStorage { - prefix := "/pods" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.PodList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Pods), &api.Pod{}, prefix, pod.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Pods), + &api.Pod{}, + prefix, + pod.Strategy, + newListFunc, + pod.NodeNameTriggerFunc, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Pod{} }, @@ -77,9 +82,7 @@ func NewStorage(opts generic.RESTOptions, k client.ConnectionInfoGetter, proxyTr ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Pod).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return pod.MatchPod(label, field) - }, + PredicateFunc: pod.MatchPod, QualifiedResource: api.Resource("pods"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/log.go b/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/log.go index bae6c6a0d8e5..24e3c422e6af 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/log.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/log.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/subresources.go b/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/subresources.go index fd65a441dcac..049aeeb78d29 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/subresources.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/pod/rest/subresources.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/pod/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/pod/strategy.go index 98d551322bb3..38ebda14571c 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/pod/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/pod/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import ( "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" utilnet "k8s.io/kubernetes/pkg/util/net" "k8s.io/kubernetes/pkg/util/validation/field" ) @@ -177,9 +178,16 @@ func MatchPod(label labels.Selector, field fields.Selector) generic.Matcher { } return podLabels, podFields, nil }, + IndexFields: []string{"spec.nodeName"}, } } +func NodeNameTriggerFunc(obj runtime.Object) []storage.MatchValue { + pod := obj.(*api.Pod) + result := storage.MatchValue{IndexName: "spec.nodeName", Value: pod.Spec.NodeName} + return []storage.MatchValue{result} +} + // PodToSelectableFields returns a field set that represents the object // TODO: fields are not labels, and the validation rules for them do not apply. func PodToSelectableFields(pod *api.Pod) fields.Set { @@ -246,9 +254,9 @@ func ResourceLocation(getter ResourceGetter, rt http.RoundTripper, ctx api.Conte } // getContainerNames returns a formatted string containing the container names -func getContainerNames(pod *api.Pod) string { +func getContainerNames(containers []api.Container) string { names := []string{} - for _, c := range pod.Spec.Containers { + for _, c := range containers { names = append(names, c.Name) } return strings.Join(names, " ") @@ -278,8 +286,13 @@ func LogLocation( case 0: return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s", name)) default: - containerNames := getContainerNames(pod) - return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s, choose one of: [%s]", name, containerNames)) + containerNames := getContainerNames(pod.Spec.Containers) + initContainerNames := getContainerNames(pod.Spec.InitContainers) + err := fmt.Sprintf("a container name must be specified for pod %s, choose one of: [%s]", name, containerNames) + if len(initContainerNames) > 0 { + err += fmt.Sprintf(" or one of the init containers: [%s]", initContainerNames) + } + return nil, nil, errors.NewBadRequest(err) } } else { if !podHasContainerWithName(pod, container) { @@ -424,8 +437,13 @@ func streamLocation( case 0: return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s", name)) default: - containerNames := getContainerNames(pod) - return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s, choose one of: [%s]", name, containerNames)) + containerNames := getContainerNames(pod.Spec.Containers) + initContainerNames := getContainerNames(pod.Spec.InitContainers) + err := fmt.Sprintf("a container name must be specified for pod %s, choose one of: [%s]", name, containerNames) + if len(initContainerNames) > 0 { + err += fmt.Sprintf(" or one of the init containers: [%s]", initContainerNames) + } + return nil, nil, errors.NewBadRequest(err) } } else { if !podHasContainerWithName(pod, container) { diff --git a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/doc.go index 717f26d21d8d..a3ee49ca4588 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/etcd/etcd.go index 8fa3524fb6a8..3151f7229d34 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" policyapi "k8s.io/kubernetes/pkg/apis/policy" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/poddisruptionbudget" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // rest implements a RESTStorage for pod disruption budgets against etcd @@ -36,11 +35,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against pod disruption budgets. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/poddisruptionbudgets" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &policyapi.PodDisruptionBudgetList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.PodDisruptionBudget), &policyapi.PodDisruptionBudget{}, prefix, poddisruptionbudget.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.PodDisruptionBudget), + &policyapi.PodDisruptionBudget{}, + prefix, + poddisruptionbudget.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &policyapi.PodDisruptionBudget{} }, @@ -62,9 +68,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*policyapi.PodDisruptionBudget).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return poddisruptionbudget.MatchPodDisruptionBudget(label, field) - }, + PredicateFunc: poddisruptionbudget.MatchPodDisruptionBudget, QualifiedResource: policyapi.Resource("poddisruptionbudgets"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/strategy.go index 4b32b9532630..1f97c7b8d3c0 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/poddisruptionbudget/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/doc.go index fa50db8e4ee7..c52667c5b7f8 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd/etcd.go index 58cc8b83076e..33ed738cec73 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,12 +19,11 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/podsecuritypolicy" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for PodSecurityPolicies against etcd. @@ -32,29 +31,34 @@ type REST struct { *registry.Store } -const Prefix = "/podsecuritypolicies" - // NewREST returns a RESTStorage object that will work against PodSecurityPolicy objects. func NewREST(opts generic.RESTOptions) *REST { + prefix := "/" + opts.ResourcePrefix + newListFunc := func() runtime.Object { return &extensions.PodSecurityPolicyList{} } storageInterface := opts.Decorator( - opts.Storage, 100, &extensions.PodSecurityPolicy{}, Prefix, podsecuritypolicy.Strategy, newListFunc) + opts.Storage, + 100, + &extensions.PodSecurityPolicy{}, + prefix, + podsecuritypolicy.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensions.PodSecurityPolicy{} }, NewListFunc: newListFunc, KeyRootFunc: func(ctx api.Context) string { - return Prefix + return prefix }, KeyFunc: func(ctx api.Context, name string) (string, error) { - return registry.NoNamespaceKeyFunc(ctx, Prefix, name) + return registry.NoNamespaceKeyFunc(ctx, prefix, name) }, ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*extensions.PodSecurityPolicy).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return podsecuritypolicy.MatchPodSecurityPolicy(label, field) - }, + PredicateFunc: podsecuritypolicy.MatchPodSecurityPolicy, QualifiedResource: extensions.Resource("podsecuritypolicies"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/strategy.go index 905be4dc6db5..9d04bdd9335b 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podsecuritypolicy/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/doc.go index a622a2ecfa11..b3e43f22ffdf 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/etcd/etcd.go index 760853a6ffa1..b863df24f979 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,13 +18,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/podtemplate" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -33,11 +32,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against pod templates. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/podtemplates" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.PodTemplateList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.PodTemplates), &api.PodTemplate{}, prefix, podtemplate.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.PodTemplates), + &api.PodTemplate{}, + prefix, + podtemplate.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.PodTemplate{} }, @@ -51,9 +57,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.PodTemplate).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return podtemplate.MatchPodTemplate(label, field) - }, + PredicateFunc: podtemplate.MatchPodTemplate, QualifiedResource: api.Resource("podtemplates"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/strategy.go index 03ce85186510..5667db8ad07c 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/podtemplate/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/doc.go index ee349fae7407..3e8d4bfefecc 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/etcd/etcd.go index 463dd689e7d2..ab5e74495194 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,13 +26,12 @@ import ( "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apis/extensions" extvalidation "k8s.io/kubernetes/pkg/apis/extensions/validation" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/replicaset" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // ReplicaSetStorage includes dummy storage for ReplicaSets and for Scale subresource. @@ -59,11 +58,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against ReplicaSet. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/replicasets" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &extensions.ReplicaSetList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Replicasets), &extensions.ReplicaSet{}, prefix, replicaset.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Replicasets), + &extensions.ReplicaSet{}, + prefix, + replicaset.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &extensions.ReplicaSet{} }, @@ -85,9 +91,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { return obj.(*extensions.ReplicaSet).Name, nil }, // Used to match objects based on labels/fields for list and watch - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return replicaset.MatchReplicaSet(label, field) - }, + PredicateFunc: replicaset.MatchReplicaSet, QualifiedResource: api.Resource("replicasets"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/registry.go index 284ed47f3293..16202919bc71 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/strategy.go index 7d7b38a0d049..773eb6f52dc4 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/replicaset/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/replicaset/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/doc.go index 91ec69fccefb..aa335fe24c52 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/etcd/etcd.go index ea343ae29cda..d78ab27ba80f 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/resourcequota" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -34,11 +33,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against resource quotas. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/resourcequotas" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.ResourceQuotaList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.ResourceQuotas), &api.ResourceQuota{}, prefix, resourcequota.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.ResourceQuotas), + &api.ResourceQuota{}, + prefix, + resourcequota.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.ResourceQuota{} }, @@ -52,9 +58,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.ResourceQuota).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return resourcequota.MatchResourceQuota(label, field) - }, + PredicateFunc: resourcequota.MatchResourceQuota, QualifiedResource: api.Resource("resourcequotas"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/strategy.go index 656d5cecbac9..a426079f77c0 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/resourcequota/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/role/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/role/doc.go index 2e867eb39e98..38e231021382 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/role/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/role/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/role/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/role/etcd/etcd.go index 0097292ea89e..e5e13a3e6954 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/role/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/role/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/role" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for Role against etcd @@ -35,7 +34,7 @@ type REST struct { // NewREST returns a RESTStorage object that will work against Role objects. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/roles" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &rbac.RoleList{} } storageInterface := opts.Decorator( @@ -45,6 +44,7 @@ func NewREST(opts generic.RESTOptions) *REST { prefix, role.Strategy, newListFunc, + storage.NoTriggerPublisher, ) store := ®istry.Store{ @@ -59,9 +59,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*rbac.Role).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return role.Matcher(label, field) - }, + PredicateFunc: role.Matcher, QualifiedResource: rbac.Resource("roles"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/role/policybased/storage.go b/vendor/k8s.io/kubernetes/pkg/registry/role/policybased/storage.go index 07ddc26a1629..f9e07435e130 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/role/policybased/storage.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/role/policybased/storage.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/role/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/role/registry.go index 40f2975da84e..706988dfe1da 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/role/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/role/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/role/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/role/strategy.go index 23efccd77fe0..007bb61552a9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/role/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/role/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/doc.go index bac8e64fc079..581afbb9f2e7 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/etcd/etcd.go index 559a00402e0e..01d913a73761 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/rolebinding" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) // REST implements a RESTStorage for RoleBinding against etcd @@ -35,7 +34,7 @@ type REST struct { // NewREST returns a RESTStorage object that will work against RoleBinding objects. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/rolebindings" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &rbac.RoleBindingList{} } storageInterface := opts.Decorator( @@ -45,6 +44,7 @@ func NewREST(opts generic.RESTOptions) *REST { prefix, rolebinding.Strategy, newListFunc, + storage.NoTriggerPublisher, ) store := ®istry.Store{ @@ -59,9 +59,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*rbac.RoleBinding).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return rolebinding.Matcher(label, field) - }, + PredicateFunc: rolebinding.Matcher, QualifiedResource: rbac.Resource("rolebindings"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/policybased/storage.go b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/policybased/storage.go index df2049b5e172..c0d3ce1259a8 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/policybased/storage.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/policybased/storage.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/registry.go index 435a2d57f755..fa7a2694181e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/strategy.go index 7818025a7597..885d9b2bf5f8 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/rolebinding/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/secret/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/secret/doc.go index 0f3c2c720902..1dc79f578f51 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/secret/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/secret/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/secret/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/secret/etcd/etcd.go index 77b34273b3b9..c1a88760058f 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/secret/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/secret/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,13 +18,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/secret" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -33,11 +32,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against secrets. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/secrets" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.SecretList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Secrets), &api.Secret{}, prefix, secret.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Secrets), + &api.Secret{}, + prefix, + secret.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Secret{} }, @@ -51,9 +57,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Secret).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return secret.Matcher(label, field) - }, + PredicateFunc: secret.Matcher, QualifiedResource: api.Resource("secrets"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/secret/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/secret/registry.go index 157ac7191af6..03d948c3d81e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/secret/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/secret/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/secret/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/secret/strategy.go index d06c86b3309a..66ff11d1ecd9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/secret/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/secret/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/bitmap.go b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/bitmap.go index e90f396a6027..9394d59fc3cb 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/bitmap.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/bitmap.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/etcd/etcd.go index 2c1c74984b2c..4e52ae362bee 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -167,22 +167,6 @@ func (e *Etcd) tryUpdate(fn func() error) error { return storeerr.InterpretUpdateError(err, e.resource, "") } -// Refresh reloads the RangeAllocation from etcd. -func (e *Etcd) Refresh() (*api.RangeAllocation, error) { - e.lock.Lock() - defer e.lock.Unlock() - - existing := &api.RangeAllocation{} - if err := e.storage.Get(context.TODO(), e.baseKey, existing, false); err != nil { - if storage.IsNotFound(err) { - return nil, nil - } - return nil, storeerr.InterpretGetError(err, e.resource, "") - } - - return existing, nil -} - // Get returns an api.RangeAllocation that represents the current state in // etcd. If the key does not exist, the object will have an empty ResourceVersion. func (e *Etcd) Get() (*api.RangeAllocation, error) { diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/interfaces.go b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/interfaces.go index 9d44090989b6..88231dafc12e 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/utils.go b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/utils.go index fc7cff70e2b8..4691f57a157c 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/utils.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/allocator/utils.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/service/doc.go index 64d927e8072d..13616309c4a9 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/service/etcd/etcd.go index 1ebbc4292922..cb532eb769ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/service" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -34,11 +33,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against services. func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { - prefix := "/services/specs" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.ServiceList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Services), &api.Service{}, prefix, service.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.Services), + &api.Service{}, + prefix, + service.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.Service{} }, @@ -52,9 +58,7 @@ func NewREST(opts generic.RESTOptions) (*REST, *StatusREST) { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Service).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return service.MatchServices(label, field) - }, + PredicateFunc: service.MatchServices, QualifiedResource: api.Resource("services"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/allocator.go b/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/allocator.go index 3aa5e58f63c0..d5a3ced642b0 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/allocator.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/allocator.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/controller/repair.go b/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/controller/repair.go index b0a2b90a5ddb..dc37a5a4a6eb 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/controller/repair.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/ipallocator/controller/repair.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/allocator.go b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/allocator.go index 765ac8f3c011..a6d565b099c8 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/allocator.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/allocator.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/controller/repair.go b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/controller/repair.go index cff3f5f3edbd..d80c06d099e7 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/controller/repair.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/controller/repair.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/operation.go b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/operation.go index a43501043495..08d9d587815d 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/operation.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/portallocator/operation.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/proxy.go b/vendor/k8s.io/kubernetes/pkg/registry/service/proxy.go index 77ff95331ac5..47f3be6606fa 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/proxy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/proxy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/service/registry.go index fa7df32af58e..34b955bbb359 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/rest.go b/vendor/k8s.io/kubernetes/pkg/registry/service/rest.go index 875d15779cc1..77da71bbb004 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/rest.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/rest.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/service/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/service/strategy.go index bc87a8107114..fd794cfd42dc 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/service/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/service/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/doc.go index 40606205d308..ea714a980f44 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/etcd/etcd.go index 354a07558c49..4f595cc1bcc5 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,13 +18,12 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/cachesize" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/serviceaccount" "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" ) type REST struct { @@ -33,11 +32,18 @@ type REST struct { // NewREST returns a RESTStorage object that will work against service accounts. func NewREST(opts generic.RESTOptions) *REST { - prefix := "/serviceaccounts" + prefix := "/" + opts.ResourcePrefix newListFunc := func() runtime.Object { return &api.ServiceAccountList{} } storageInterface := opts.Decorator( - opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.ServiceAccounts), &api.ServiceAccount{}, prefix, serviceaccount.Strategy, newListFunc) + opts.Storage, + cachesize.GetWatchCacheSizeByResource(cachesize.ServiceAccounts), + &api.ServiceAccount{}, + prefix, + serviceaccount.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) store := ®istry.Store{ NewFunc: func() runtime.Object { return &api.ServiceAccount{} }, @@ -51,9 +57,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.ServiceAccount).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return serviceaccount.Matcher(label, field) - }, + PredicateFunc: serviceaccount.Matcher, QualifiedResource: api.Resource("serviceaccounts"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/registry.go index 2a7a1c7dd5f4..7e5635dad0e6 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/strategy.go index 1d1f208f8c73..27c0f1639152 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/serviceaccount/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/storageclass/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/doc.go new file mode 100644 index 000000000000..8cb043231773 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 storageClass provides Registry interface and its REST +// implementation for storing storageclass api objects. +package storageclass diff --git a/vendor/k8s.io/kubernetes/pkg/registry/storageclass/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/etcd/etcd.go new file mode 100644 index 000000000000..5241547471ab --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/etcd/etcd.go @@ -0,0 +1,73 @@ +/* +Copyright 2015 The Kubernetes 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 etcd + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/registry/generic" + "k8s.io/kubernetes/pkg/registry/generic/registry" + "k8s.io/kubernetes/pkg/registry/storageclass" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage" +) + +type REST struct { + *registry.Store +} + +// NewREST returns a RESTStorage object that will work against persistent volumes. +func NewREST(opts generic.RESTOptions) *REST { + prefix := "/storageclasses" + + newListFunc := func() runtime.Object { return &extensions.StorageClassList{} } + storageInterface := opts.Decorator( + opts.Storage, + 100, + &extensions.StorageClass{}, + prefix, + storageclass.Strategy, + newListFunc, + storage.NoTriggerPublisher, + ) + + store := ®istry.Store{ + NewFunc: func() runtime.Object { return &extensions.StorageClass{} }, + NewListFunc: newListFunc, + KeyRootFunc: func(ctx api.Context) string { + return prefix + }, + KeyFunc: func(ctx api.Context, name string) (string, error) { + return registry.NoNamespaceKeyFunc(ctx, prefix, name) + }, + ObjectNameFunc: func(obj runtime.Object) (string, error) { + return obj.(*extensions.StorageClass).Name, nil + }, + PredicateFunc: storageclass.MatchStorageClasses, + QualifiedResource: api.Resource("storageclasses"), + DeleteCollectionWorkers: opts.DeleteCollectionWorkers, + + CreateStrategy: storageclass.Strategy, + UpdateStrategy: storageclass.Strategy, + DeleteStrategy: storageclass.Strategy, + ReturnDeletedObject: true, + + Storage: storageInterface, + } + + return &REST{store} +} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/storageclass/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/strategy.go new file mode 100644 index 000000000000..a8ebac5d0a47 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/registry/storageclass/strategy.go @@ -0,0 +1,98 @@ +/* +Copyright 2016 The Kubernetes 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 storageclass + +import ( + "fmt" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/apis/extensions" + "k8s.io/kubernetes/pkg/apis/extensions/validation" + "k8s.io/kubernetes/pkg/fields" + "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/registry/generic" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/util/validation/field" +) + +// storageClassStrategy implements behavior for StorageClass objects +type storageClassStrategy struct { + runtime.ObjectTyper + api.NameGenerator +} + +// Strategy is the default logic that applies when creating and updating +// StorageClass objects via the REST API. +var Strategy = storageClassStrategy{api.Scheme, api.SimpleNameGenerator} + +func (storageClassStrategy) NamespaceScoped() bool { + return false +} + +// ResetBeforeCreate clears the Status field which is not allowed to be set by end users on creation. +func (storageClassStrategy) PrepareForCreate(obj runtime.Object) { + _ = obj.(*extensions.StorageClass) +} + +func (storageClassStrategy) Validate(ctx api.Context, obj runtime.Object) field.ErrorList { + storageClass := obj.(*extensions.StorageClass) + return validation.ValidateStorageClass(storageClass) +} + +// Canonicalize normalizes the object after validation. +func (storageClassStrategy) Canonicalize(obj runtime.Object) { +} + +func (storageClassStrategy) AllowCreateOnUpdate() bool { + return false +} + +// PrepareForUpdate sets the Status fields which is not allowed to be set by an end user updating a PV +func (storageClassStrategy) PrepareForUpdate(obj, old runtime.Object) { + _ = obj.(*extensions.StorageClass) + _ = old.(*extensions.StorageClass) +} + +func (storageClassStrategy) ValidateUpdate(ctx api.Context, obj, old runtime.Object) field.ErrorList { + errorList := validation.ValidateStorageClass(obj.(*extensions.StorageClass)) + return append(errorList, validation.ValidateStorageClassUpdate(obj.(*extensions.StorageClass), old.(*extensions.StorageClass))...) +} + +func (storageClassStrategy) AllowUnconditionalUpdate() bool { + return true +} + +// MatchStorageClass returns a generic matcher for a given label and field selector. +func MatchStorageClasses(label labels.Selector, field fields.Selector) generic.Matcher { + return &generic.SelectionPredicate{ + Label: label, + Field: field, + GetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) { + cls, ok := obj.(*extensions.StorageClass) + if !ok { + return nil, nil, fmt.Errorf("given object is not of type StorageClass") + } + + return labels.Set(cls.ObjectMeta.Labels), StorageClassToSelectableFields(cls), nil + }, + } +} + +// StorageClassToSelectableFields returns a label set that represents the object +func StorageClassToSelectableFields(storageClass *extensions.StorageClass) fields.Set { + return generic.ObjectMetaFieldsSet(storageClass.ObjectMeta, false) +} diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/doc.go index 7f52880dac51..331c94cb0a68 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd/etcd.go index d371addc7344..b59531b858e7 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,8 +19,6 @@ package etcd import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/thirdpartyresource" @@ -34,7 +32,7 @@ type REST struct { // NewREST returns a registry which will store ThirdPartyResource in the given helper func NewREST(opts generic.RESTOptions) *REST { - prefix := "/thirdpartyresources" + prefix := "/" + opts.ResourcePrefix // We explicitly do NOT do any decoration here yet. storageInterface := opts.Storage @@ -51,9 +49,7 @@ func NewREST(opts generic.RESTOptions) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*extensions.ThirdPartyResource).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return thirdpartyresource.Matcher(label, field) - }, + PredicateFunc: thirdpartyresource.Matcher, QualifiedResource: extensions.Resource("thirdpartyresources"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, CreateStrategy: thirdpartyresource.Strategy, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/strategy.go index 38a256d6d887..3f553aa9ef82 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresource/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/codec.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/codec.go index 758ffd46625d..ca190c1f37f5 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/codec.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/codec.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -152,6 +152,27 @@ func (t *thirdPartyResourceDataMapper) RESTMapping(gk unversioned.GroupKind, ver return mapping, nil } +func (t *thirdPartyResourceDataMapper) RESTMappings(gk unversioned.GroupKind) ([]*meta.RESTMapping, error) { + if gk.Group != t.group { + return nil, fmt.Errorf("unknown group %q expected %s", gk.Group, t.group) + } + if gk.Kind != "ThirdPartyResourceData" { + return nil, fmt.Errorf("unknown kind %s expected %s", gk.Kind, t.kind) + } + + // TODO figure out why we're doing this rewriting + extensionGK := unversioned.GroupKind{Group: extensions.GroupName, Kind: "ThirdPartyResourceData"} + + mappings, err := t.mapper.RESTMappings(extensionGK) + if err != nil { + return nil, err + } + for _, m := range mappings { + m.ObjectConvertor = &thirdPartyObjectConverter{m.ObjectConvertor} + } + return mappings, nil +} + func (t *thirdPartyResourceDataMapper) AliasesForResource(resource string) ([]string, bool) { return t.mapper.AliasesForResource(resource) } @@ -451,13 +472,6 @@ func (t *thirdPartyResourceDataDecoder) populateListResource(objIn *extensions.T return nil } -const template = `{ - "kind": "%s", - "apiVersion": "%s", - "metadata": {}, - "items": [ %s ] -}` - type thirdPartyResourceDataEncoder struct { delegate runtime.Encoder gvk unversioned.GroupVersionKind @@ -488,19 +502,37 @@ func (t *thirdPartyResourceDataEncoder) Encode(obj runtime.Object, stream io.Wri case *extensions.ThirdPartyResourceData: return encodeToJSON(obj, stream) case *extensions.ThirdPartyResourceDataList: - // TODO: There must be a better way to do this... - dataStrings := make([]string, len(obj.Items)) + // TODO: There are likely still better ways to do this... + listItems := make([]json.RawMessage, len(obj.Items)) + for ix := range obj.Items { buff := &bytes.Buffer{} err := encodeToJSON(&obj.Items[ix], buff) if err != nil { return err } - dataStrings[ix] = buff.String() + listItems[ix] = json.RawMessage(buff.Bytes()) } - gv := t.gvk.GroupVersion() - fmt.Fprintf(stream, template, t.gvk.Kind+"List", gv.String(), strings.Join(dataStrings, ",")) - return nil + + encMap := struct { + Kind string `json:"kind,omitempty"` + Items []json.RawMessage `json:"items"` + Metadata unversioned.ListMeta `json:"metadata,omitempty"` + APIVersion string `json:"apiVersion,omitempty"` + }{ + Kind: t.gvk.Kind + "List", + Items: listItems, + Metadata: obj.ListMeta, + APIVersion: t.gvk.GroupVersion().String(), + } + + encBytes, err := json.Marshal(encMap) + if err != nil { + return err + } + + _, err = stream.Write(encBytes) + return err case *versioned.InternalEvent: event := &versioned.Event{} err := versioned.Convert_versioned_InternalEvent_to_versioned_Event(obj, event, nil) diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/doc.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/doc.go index 62e2dc1e3eb7..d9988ccb0852 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd/etcd.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd/etcd.go index 55eaf09b17c6..cea7bb3c884b 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd/etcd.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/etcd/etcd.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,8 +21,6 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/fields" - "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/registry/generic" "k8s.io/kubernetes/pkg/registry/generic/registry" "k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata" @@ -54,9 +52,7 @@ func NewREST(opts generic.RESTOptions, group, kind string) *REST { ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*extensions.ThirdPartyResourceData).Name, nil }, - PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher { - return thirdpartyresourcedata.Matcher(label, field) - }, + PredicateFunc: thirdpartyresourcedata.Matcher, QualifiedResource: extensions.Resource("thirdpartyresourcedatas"), DeleteCollectionWorkers: opts.DeleteCollectionWorkers, CreateStrategy: thirdpartyresourcedata.Strategy, diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/registry.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/registry.go index 058276d1e2f5..87f1156ec1f5 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/registry.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/registry.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/strategy.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/strategy.go index 9f7673d7c06e..12108c39e4a1 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/strategy.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/strategy.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/util.go b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/util.go index 120981e85ec2..d8e91b15727f 100644 --- a/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/util.go +++ b/vendor/k8s.io/kubernetes/pkg/registry/thirdpartyresourcedata/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/codec.go b/vendor/k8s.io/kubernetes/pkg/runtime/codec.go index 9cd7e153682b..3f7681c0024e 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/codec.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/codec.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/codec_check.go b/vendor/k8s.io/kubernetes/pkg/runtime/codec_check.go index 09e7d51ad9f9..b0126963d36e 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/codec_check.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/codec_check.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/conversion.go b/vendor/k8s.io/kubernetes/pkg/runtime/conversion.go index 69cf00fea5d6..dd6e26af7de5 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/conversion.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/runtime/deep_copy_generated.go deleted file mode 100644 index fad426daa689..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/runtime/deep_copy_generated.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2016 The Kubernetes Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package runtime - -import ( - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func DeepCopy_runtime_RawExtension(in RawExtension, out *RawExtension, c *conversion.Cloner) error { - if in.Raw != nil { - in, out := in.Raw, &out.Raw - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Raw = nil - } - if in.Object == nil { - out.Object = nil - } else if newVal, err := c.DeepCopy(in.Object); err != nil { - return err - } else { - out.Object = newVal.(Object) - } - return nil -} - -func DeepCopy_runtime_TypeMeta(in TypeMeta, out *TypeMeta, c *conversion.Cloner) error { - out.APIVersion = in.APIVersion - out.Kind = in.Kind - return nil -} - -func DeepCopy_runtime_Unknown(in Unknown, out *Unknown, c *conversion.Cloner) error { - if err := DeepCopy_runtime_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil { - return err - } - if in.Raw != nil { - in, out := in.Raw, &out.Raw - *out = make([]byte, len(in)) - copy(*out, in) - } else { - out.Raw = nil - } - out.ContentEncoding = in.ContentEncoding - out.ContentType = in.ContentType - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/doc.go b/vendor/k8s.io/kubernetes/pkg/runtime/doc.go index 08e18891bf6c..a9d084d9fbee 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -41,4 +41,5 @@ limitations under the License. // // As a bonus, a few common types useful from all api objects and versions // are provided in types.go. + package runtime diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/embedded.go b/vendor/k8s.io/kubernetes/pkg/runtime/embedded.go index a62080e39aca..eb1f573db6ff 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/embedded.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/embedded.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/error.go b/vendor/k8s.io/kubernetes/pkg/runtime/error.go index ca60ee813322..2a1262c5682c 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/error.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/error.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -84,7 +84,7 @@ type missingVersionErr struct { } // IsMissingVersion returns true if the error indicates that the provided object -// is missing a 'Versioj' field. +// is missing a 'Version' field. func NewMissingVersionErr(data string) error { return &missingVersionErr{data} } diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/extension.go b/vendor/k8s.io/kubernetes/pkg/runtime/extension.go index eca82986eab9..4d23ee9ee385 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/extension.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/extension.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/runtime/generated.pb.go index 289268483632..95d71e97054a 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -35,6 +35,9 @@ import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -42,17 +45,14 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *RawExtension) Reset() { *m = RawExtension{} } -func (m *RawExtension) String() string { return proto.CompactTextString(m) } -func (*RawExtension) ProtoMessage() {} +func (m *RawExtension) Reset() { *m = RawExtension{} } +func (*RawExtension) ProtoMessage() {} -func (m *TypeMeta) Reset() { *m = TypeMeta{} } -func (m *TypeMeta) String() string { return proto.CompactTextString(m) } -func (*TypeMeta) ProtoMessage() {} +func (m *TypeMeta) Reset() { *m = TypeMeta{} } +func (*TypeMeta) ProtoMessage() {} -func (m *Unknown) Reset() { *m = Unknown{} } -func (m *Unknown) String() string { return proto.CompactTextString(m) } -func (*Unknown) ProtoMessage() {} +func (m *Unknown) Reset() { *m = Unknown{} } +func (*Unknown) ProtoMessage() {} func init() { proto.RegisterType((*RawExtension)(nil), "k8s.io.kubernetes.pkg.runtime.RawExtension") @@ -225,6 +225,48 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *RawExtension) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&RawExtension{`, + `Raw:` + valueToStringGenerated(this.Raw) + `,`, + `}`, + }, "") + return s +} +func (this *TypeMeta) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&TypeMeta{`, + `APIVersion:` + fmt.Sprintf("%v", this.APIVersion) + `,`, + `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`, + `}`, + }, "") + return s +} +func (this *Unknown) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Unknown{`, + `TypeMeta:` + strings.Replace(strings.Replace(this.TypeMeta.String(), "TypeMeta", "TypeMeta", 1), `&`, ``, 1) + `,`, + `Raw:` + valueToStringGenerated(this.Raw) + `,`, + `ContentEncoding:` + fmt.Sprintf("%v", this.ContentEncoding) + `,`, + `ContentType:` + fmt.Sprintf("%v", this.ContentType) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *RawExtension) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/generated.proto b/vendor/k8s.io/kubernetes/pkg/runtime/generated.proto index 852721228fc3..0e602abe1b33 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/runtime/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ option go_package = "runtime"; // in the Object. (TODO: In the case where the object is of an unknown type, a // runtime.Unknown object will be created and stored.) // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true message RawExtension { // Raw is the underlying serialization of this object. @@ -89,7 +89,7 @@ message RawExtension { // TypeMeta is provided here for convenience. You may use it directly from this package or define // your own with the same fields. // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true message TypeMeta { optional string apiVersion = 1; @@ -103,7 +103,7 @@ message TypeMeta { // TODO: Make this object have easy access to field based accessors and settors for // metadata and field mutatation. // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true message Unknown { optional TypeMeta typeMeta = 1; diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/helper.go b/vendor/k8s.io/kubernetes/pkg/runtime/helper.go index b131fdcd90f4..827cff1b846f 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/helper.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/helper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/interfaces.go b/vendor/k8s.io/kubernetes/pkg/runtime/interfaces.go index 7239ac44ce7b..e46324608e55 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/register.go b/vendor/k8s.io/kubernetes/pkg/runtime/register.go index 5201a15ffd5f..39a1eb14b8e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/register.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/scheme.go b/vendor/k8s.io/kubernetes/pkg/runtime/scheme.go index c49c43e93ffd..71b01073c4c8 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/scheme.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/scheme.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -357,9 +357,9 @@ func (s *Scheme) AddDeepCopyFuncs(deepCopyFuncs ...interface{}) error { // Similar to AddDeepCopyFuncs, but registers deep-copy functions that were // automatically generated. -func (s *Scheme) AddGeneratedDeepCopyFuncs(deepCopyFuncs ...interface{}) error { - for _, f := range deepCopyFuncs { - if err := s.cloner.RegisterGeneratedDeepCopyFunc(f); err != nil { +func (s *Scheme) AddGeneratedDeepCopyFuncs(deepCopyFuncs ...conversion.GeneratedDeepCopyFunc) error { + for _, fn := range deepCopyFuncs { + if err := s.cloner.RegisterGeneratedDeepCopyFunc(fn); err != nil { return err } } diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/codec_factory.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/codec_factory.go index 4432e489603f..66a9ae5dbe22 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/codec_factory.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/codec_factory.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -215,7 +215,7 @@ func (f CodecFactory) UniversalDecoder(versions ...unversioned.GroupVersion) run return f.CodecForVersions(nil, f.universal, nil, versions) } -// CodecFor creates a codec with the provided serializer. If an object is decoded and its group is not in the list, +// CodecForVersions creates a codec with the provided serializer. If an object is decoded and its group is not in the list, // it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not // converted. If encode or decode are nil, no conversion is performed. func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode []unversioned.GroupVersion, decode []unversioned.GroupVersion) runtime.Codec { diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/json.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/json.go index c226448f379a..c26fa50d8198 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/json.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/json.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/meta.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/meta.go index 91df105ed6cd..b9bea21eb9e1 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/meta.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/json/meta.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/negotiated_codec.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/negotiated_codec.go index 6f6a56dd3fa5..59b078ce8b03 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/negotiated_codec.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/negotiated_codec.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/doc.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/doc.go index 91b86af6cdb7..381748d69fd5 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/protobuf.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/protobuf.go index a202a18d6655..a21df48a05d7 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/protobuf.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf/protobuf.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -124,7 +124,7 @@ func (s *Serializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKi if intoUnknown, ok := into.(*runtime.Unknown); ok && intoUnknown != nil { *intoUnknown = unk - if len(intoUnknown.ContentType) == 0 { + if ok, _ := s.RecognizesData(bytes.NewBuffer(unk.Raw)); ok { intoUnknown.ContentType = s.contentType } return intoUnknown, &actual, nil @@ -167,17 +167,30 @@ func (s *Serializer) Decode(originalData []byte, gvk *unversioned.GroupVersionKi // Encode serializes the provided object to the given writer. func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error { + prefixSize := uint64(len(s.prefix)) + var unk runtime.Unknown - kind := obj.GetObjectKind().GroupVersionKind() - unk = runtime.Unknown{ - TypeMeta: runtime.TypeMeta{ - Kind: kind.Kind, - APIVersion: kind.GroupVersion().String(), - }, + switch t := obj.(type) { + case *runtime.Unknown: + estimatedSize := prefixSize + uint64(t.Size()) + data := make([]byte, estimatedSize) + i, err := t.MarshalTo(data[prefixSize:]) + if err != nil { + return err + } + copy(data, s.prefix) + _, err = w.Write(data[:prefixSize+uint64(i)]) + return err + default: + kind := obj.GetObjectKind().GroupVersionKind() + unk = runtime.Unknown{ + TypeMeta: runtime.TypeMeta{ + Kind: kind.Kind, + APIVersion: kind.GroupVersion().String(), + }, + } } - prefixSize := uint64(len(s.prefix)) - switch t := obj.(type) { case bufferedMarshaller: // this path performs a single allocation during write but requires the caller to implement diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf_extension.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf_extension.go index a93708c45d05..5846d94d5327 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf_extension.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/protobuf_extension.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer.go index 4b8b1e204e39..310002a2428d 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/recognizer/recognizer.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/streaming/streaming.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/streaming/streaming.go index c34f9a570db8..ac17138e43ab 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/streaming/streaming.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/streaming/streaming.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning.go b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning.go index f69d126c8c2d..6e67964b1633 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/serializer/versioning/versioning.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator.go b/vendor/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator.go index 19b8378a4912..29722d52e714 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/swagger_doc_generator.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/types.go b/vendor/k8s.io/kubernetes/pkg/runtime/types.go index e646d2afaf95..5033c0dc2c97 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/types.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ import ( // TypeMeta is provided here for convenience. You may use it directly from this package or define // your own with the same fields. // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true type TypeMeta struct { APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty" protobuf:"bytes,1,opt,name=apiVersion"` @@ -93,7 +93,7 @@ const ( // in the Object. (TODO: In the case where the object is of an unknown type, a // runtime.Unknown object will be created and stored.) // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true type RawExtension struct { // Raw is the underlying serialization of this object. @@ -111,7 +111,7 @@ type RawExtension struct { // TODO: Make this object have easy access to field based accessors and settors for // metadata and field mutatation. // -// +gencopy=true +// +k8s:deepcopy-gen=true // +protobuf=true type Unknown struct { TypeMeta `json:",inline" protobuf:"bytes,1,opt,name=typeMeta"` diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/types_proto.go b/vendor/k8s.io/kubernetes/pkg/runtime/types_proto.go index 142dd05daaac..ead96ee05543 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/types_proto.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/types_proto.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/unstructured.go b/vendor/k8s.io/kubernetes/pkg/runtime/unstructured.go index 4a15142c1247..048e6dc148cc 100644 --- a/vendor/k8s.io/kubernetes/pkg/runtime/unstructured.go +++ b/vendor/k8s.io/kubernetes/pkg/runtime/unstructured.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/runtime/zz_generated.deepcopy.go b/vendor/k8s.io/kubernetes/pkg/runtime/zz_generated.deepcopy.go new file mode 100644 index 000000000000..627c22b63abe --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/runtime/zz_generated.deepcopy.go @@ -0,0 +1,75 @@ +// +build !ignore_autogenerated + +/* +Copyright 2016 The Kubernetes 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package runtime + +import ( + conversion "k8s.io/kubernetes/pkg/conversion" +) + +func DeepCopy_runtime_RawExtension(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*RawExtension) + out := out.(*RawExtension) + if in.Raw != nil { + in, out := &in.Raw, &out.Raw + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Raw = nil + } + if in.Object == nil { + out.Object = nil + } else if newVal, err := c.DeepCopy(&in.Object); err != nil { + return err + } else { + out.Object = *newVal.(*Object) + } + return nil + } +} + +func DeepCopy_runtime_TypeMeta(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*TypeMeta) + out := out.(*TypeMeta) + out.APIVersion = in.APIVersion + out.Kind = in.Kind + return nil + } +} + +func DeepCopy_runtime_Unknown(in interface{}, out interface{}, c *conversion.Cloner) error { + { + in := in.(*Unknown) + out := out.(*Unknown) + out.TypeMeta = in.TypeMeta + if in.Raw != nil { + in, out := &in.Raw, &out.Raw + *out = make([]byte, len(*in)) + copy(*out, *in) + } else { + out.Raw = nil + } + out.ContentEncoding = in.ContentEncoding + out.ContentType = in.ContentType + return nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/doc.go new file mode 100644 index 000000000000..ff0383a270d8 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 capabilities contains code for validating and defaulting a pod's +// kernel capabilities according to a security policy. +package capabilities diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/mustrunas.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/mustrunas.go index 1ffc55fdba7f..8c71833d95f2 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/mustrunas.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/mustrunas.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/types.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/types.go index 428f24558426..0d1e6e2c1f93 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/types.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/capabilities/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/doc.go new file mode 100644 index 000000000000..3a8052c53637 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/doc.go @@ -0,0 +1,20 @@ +/* +Copyright 2016 The Kubernetes 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 podsecuritypolicy contains code for validating and defaulting the +// security context of a pod and its containers according to a security +// policy. +package podsecuritypolicy diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/factory.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/factory.go index 477845f14768..b2e99d810f4e 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/factory.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/factory.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/doc.go new file mode 100644 index 000000000000..9bb177b442a5 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 group contains code for validating and defaulting the FSGroup and +// supplemental groups of a pod according to a security policy. +package group diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/mustrunas.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/mustrunas.go index bcb2edade9f3..a6c64e7627af 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/mustrunas.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/mustrunas.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/runasany.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/runasany.go index 2398a2ab5387..edf6d0b12463 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/runasany.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/runasany.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/types.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/types.go index be19fe9b9dc8..7d4c2e31d31a 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/types.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/group/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/provider.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/provider.go index bf606a3384bc..b8f0bc5353d5 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/provider.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/provider.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -250,6 +250,12 @@ func (s *simpleProvider) ValidateContainerSecurityContext(pod *api.Pod, containe allErrs = append(allErrs, s.hasInvalidHostPort(&c, idxPath)...) } + containersPath = fldPath.Child("initContainers") + for idx, c := range pod.Spec.InitContainers { + idxPath := containersPath.Index(idx) + allErrs = append(allErrs, s.hasInvalidHostPort(&c, idxPath)...) + } + if !s.psp.Spec.HostPID && pod.Spec.SecurityContext.HostPID { allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPID"), pod.Spec.SecurityContext.HostPID, "Host PID is not allowed to be used")) } diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/doc.go new file mode 100644 index 000000000000..506981a9f404 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 selinux contains code for validating and defaulting the SELinux +// context of a pod according to a security policy. +package selinux diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/mustrunas.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/mustrunas.go index 4b59211bb4d2..4b1f30ee5e9a 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/mustrunas.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/mustrunas.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/runasany.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/runasany.go index 1418fc331c28..5203b9a303fc 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/runasany.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/runasany.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/types.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/types.go index 25613d62a139..b93acba27b49 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/types.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/selinux/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/types.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/types.go index 64535ee4af74..1e318662aecd 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/types.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/doc.go new file mode 100644 index 000000000000..1ddc08aee6d8 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 user contains code for validating and defaulting the UID of a pod +// or container according to a security policy. +package user diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/mustrunas.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/mustrunas.go index f48c803c99ed..26da58cab702 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/mustrunas.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/mustrunas.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/nonroot.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/nonroot.go index fc7c356a0b3f..8a7afe24618a 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/nonroot.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/nonroot.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/runasany.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/runasany.go index 6fbf1e032153..052b00ed64b5 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/runasany.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/runasany.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/types.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/types.go index ee691c7becfe..21cd18ab1e8a 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/types.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/user/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/doc.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/doc.go new file mode 100644 index 000000000000..af407b58c66a --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/doc.go @@ -0,0 +1,19 @@ +/* +Copyright 2016 The Kubernetes 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 util contains utility code shared amongst different parts of the +// pod security policy apparatus. +package util diff --git a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/util.go b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/util.go index 097b1a6c21d9..0af4ad060b35 100644 --- a/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/util.go +++ b/vendor/k8s.io/kubernetes/pkg/security/podsecuritypolicy/util/util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/securitycontext/doc.go b/vendor/k8s.io/kubernetes/pkg/securitycontext/doc.go index 9e9a84ba1004..529451e50cd3 100644 --- a/vendor/k8s.io/kubernetes/pkg/securitycontext/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/securitycontext/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/securitycontext/fake.go b/vendor/k8s.io/kubernetes/pkg/securitycontext/fake.go index a4bf2fa7073c..ef86de3c8684 100644 --- a/vendor/k8s.io/kubernetes/pkg/securitycontext/fake.go +++ b/vendor/k8s.io/kubernetes/pkg/securitycontext/fake.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/securitycontext/provider.go b/vendor/k8s.io/kubernetes/pkg/securitycontext/provider.go index 4a187676bb09..524aa7723536 100644 --- a/vendor/k8s.io/kubernetes/pkg/securitycontext/provider.go +++ b/vendor/k8s.io/kubernetes/pkg/securitycontext/provider.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/securitycontext/types.go b/vendor/k8s.io/kubernetes/pkg/securitycontext/types.go index 87b5063fcc72..2ab2d0390b5e 100644 --- a/vendor/k8s.io/kubernetes/pkg/securitycontext/types.go +++ b/vendor/k8s.io/kubernetes/pkg/securitycontext/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/securitycontext/util.go b/vendor/k8s.io/kubernetes/pkg/securitycontext/util.go index 32b97af2388d..13d48a258f61 100644 --- a/vendor/k8s.io/kubernetes/pkg/securitycontext/util.go +++ b/vendor/k8s.io/kubernetes/pkg/securitycontext/util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt.go b/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt.go index d26349d861e6..84792a88a5e7 100644 --- a/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt.go +++ b/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -92,17 +92,19 @@ type jwtTokenGenerator struct { func (j *jwtTokenGenerator) GenerateToken(serviceAccount api.ServiceAccount, secret api.Secret) (string, error) { token := jwt.New(jwt.SigningMethodRS256) + claims, _ := token.Claims.(jwt.MapClaims) + // Identify the issuer - token.Claims[IssuerClaim] = Issuer + claims[IssuerClaim] = Issuer // Username - token.Claims[SubjectClaim] = MakeUsername(serviceAccount.Namespace, serviceAccount.Name) + claims[SubjectClaim] = MakeUsername(serviceAccount.Namespace, serviceAccount.Name) // Persist enough structured info for the authenticator to be able to look up the service account and secret - token.Claims[NamespaceClaim] = serviceAccount.Namespace - token.Claims[ServiceAccountNameClaim] = serviceAccount.Name - token.Claims[ServiceAccountUIDClaim] = serviceAccount.UID - token.Claims[SecretNameClaim] = secret.Name + claims[NamespaceClaim] = serviceAccount.Namespace + claims[ServiceAccountNameClaim] = serviceAccount.Name + claims[ServiceAccountUIDClaim] = serviceAccount.UID + claims[SecretNameClaim] = secret.Name // Sign and get the complete encoded token as a string return token.SignedString(j.key) @@ -156,30 +158,32 @@ func (j *jwtTokenAuthenticator) AuthenticateToken(token string) (user.Info, bool // If we get here, we have a token with a recognized signature + claims, _ := parsedToken.Claims.(jwt.MapClaims) + // Make sure we issued the token - iss, _ := parsedToken.Claims[IssuerClaim].(string) + iss, _ := claims[IssuerClaim].(string) if iss != Issuer { return nil, false, nil } // Make sure the claims we need exist - sub, _ := parsedToken.Claims[SubjectClaim].(string) + sub, _ := claims[SubjectClaim].(string) if len(sub) == 0 { return nil, false, errors.New("sub claim is missing") } - namespace, _ := parsedToken.Claims[NamespaceClaim].(string) + namespace, _ := claims[NamespaceClaim].(string) if len(namespace) == 0 { return nil, false, errors.New("namespace claim is missing") } - secretName, _ := parsedToken.Claims[SecretNameClaim].(string) + secretName, _ := claims[SecretNameClaim].(string) if len(namespace) == 0 { return nil, false, errors.New("secretName claim is missing") } - serviceAccountName, _ := parsedToken.Claims[ServiceAccountNameClaim].(string) + serviceAccountName, _ := claims[ServiceAccountNameClaim].(string) if len(serviceAccountName) == 0 { return nil, false, errors.New("serviceAccountName claim is missing") } - serviceAccountUID, _ := parsedToken.Claims[ServiceAccountUIDClaim].(string) + serviceAccountUID, _ := claims[ServiceAccountUIDClaim].(string) if len(serviceAccountUID) == 0 { return nil, false, errors.New("serviceAccountUID claim is missing") } diff --git a/vendor/k8s.io/kubernetes/pkg/serviceaccount/util.go b/vendor/k8s.io/kubernetes/pkg/serviceaccount/util.go index 487b0f156923..712b086ad48d 100644 --- a/vendor/k8s.io/kubernetes/pkg/serviceaccount/util.go +++ b/vendor/k8s.io/kubernetes/pkg/serviceaccount/util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/ssh/ssh.go b/vendor/k8s.io/kubernetes/pkg/ssh/ssh.go index ea6c7955e3ff..69dbec685bf3 100644 --- a/vendor/k8s.io/kubernetes/pkg/ssh/ssh.go +++ b/vendor/k8s.io/kubernetes/pkg/ssh/ssh.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/cacher.go b/vendor/k8s.io/kubernetes/pkg/storage/cacher.go index 7bbb5717a553..311622289a19 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/cacher.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/cacher.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/conversion" @@ -59,11 +58,67 @@ type CacherConfig struct { // KeyFunc is used to get a key in the underyling storage for a given object. KeyFunc func(runtime.Object) (string, error) + // TriggerPublisherFunc is used for optimizing amount of watchers that + // needs to process an incoming event. + TriggerPublisherFunc TriggerPublisherFunc + // NewList is a function that creates new empty object storing a list of // objects of type Type. NewListFunc func() runtime.Object } +type watchersMap map[int]*cacheWatcher + +func (wm watchersMap) addWatcher(w *cacheWatcher, number int) { + wm[number] = w +} + +func (wm watchersMap) deleteWatcher(number int) { + delete(wm, number) +} + +func (wm watchersMap) terminateAll() { + for key, watcher := range wm { + delete(wm, key) + watcher.stop() + } +} + +type indexedWatchers struct { + allWatchers watchersMap + valueWatchers map[string]watchersMap +} + +func (i *indexedWatchers) addWatcher(w *cacheWatcher, number int, value string, supported bool) { + if supported { + if _, ok := i.valueWatchers[value]; !ok { + i.valueWatchers[value] = watchersMap{} + } + i.valueWatchers[value].addWatcher(w, number) + } else { + i.allWatchers.addWatcher(w, number) + } +} + +func (i *indexedWatchers) deleteWatcher(number int, value string, supported bool) { + if supported { + i.valueWatchers[value].deleteWatcher(number) + if len(i.valueWatchers[value]) == 0 { + delete(i.valueWatchers, value) + } + } else { + i.allWatchers.deleteWatcher(number) + } +} + +func (i *indexedWatchers) terminateAll() { + i.allWatchers.terminateAll() + for index, watchers := range i.valueWatchers { + watchers.terminateAll() + delete(i.valueWatchers, index) + } +} + // Cacher is responsible for serving WATCH and LIST requests for a given // resource from its internal cache and updating its cache in the background // based on the underlying storage contents. @@ -72,19 +127,13 @@ type CacherConfig struct { type Cacher struct { sync.RWMutex - // Each user-facing method that is not simply redirected to the underlying - // storage has to read-lock on this mutex before starting any processing. + // Before accessing the cacher's cache, wait for the ready to be ok. // This is necessary to prevent users from accessing structures that are // uninitialized or are being repopulated right now. - // NOTE: We cannot easily reuse the main mutex for it due to multi-threaded - // interactions of Cacher with the underlying WatchCache. Since Cacher is - // caling WatchCache directly and WatchCache is calling Cacher methods - // via its OnEvent and OnReplace hooks, we explicitly assume that if mutexes - // of both structures are held, the one from WatchCache is acquired first - // to avoid deadlocks. Unfortunately, forcing this rule in startCaching - // would be very difficult and introducing one more mutex seems to be much - // easier. - usable sync.RWMutex + // ready needs to be set to false when the cacher is paused or stopped. + // ready needs to be set to true when the cacher is ready to use after + // initialization. + ready *ready // Underlying storage.Interface. storage Interface @@ -93,16 +142,20 @@ type Cacher struct { watchCache *watchCache reflector *cache.Reflector - // Registered watchers. - watcherIdx int - watchers map[int]*cacheWatcher - // Versioner is used to handle resource versions. versioner Versioner // keyFunc is used to get a key in the underyling storage for a given object. keyFunc func(runtime.Object) (string, error) + // triggerFunc is used for optimizing amount of watchers that needs to process + // an incoming event. + triggerFunc TriggerPublisherFunc + // watchers is mapping from the value of trigger function that a + // watcher is interested into the watchers + watcherIdx int + watchers indexedWatchers + // Handling graceful termination. stopLock sync.RWMutex stopped bool @@ -110,37 +163,6 @@ type Cacher struct { stopWg sync.WaitGroup } -// Create a new Cacher responsible from service WATCH and LIST requests from its -// internal cache and updating its cache in the background based on the given -// configuration. -func NewCacher( - storage Interface, - capacity int, - versioner Versioner, - objectType runtime.Object, - resourcePrefix string, - scopeStrategy rest.NamespaceScopedStrategy, - newListFunc func() runtime.Object) Interface { - config := CacherConfig{ - CacheCapacity: capacity, - Storage: storage, - Versioner: versioner, - Type: objectType, - ResourcePrefix: resourcePrefix, - NewListFunc: newListFunc, - } - if scopeStrategy.NamespaceScoped() { - config.KeyFunc = func(obj runtime.Object) (string, error) { - return NamespaceKeyFunc(resourcePrefix, obj) - } - } else { - config.KeyFunc = func(obj runtime.Object) (string, error) { - return NoNamespaceKeyFunc(resourcePrefix, obj) - } - } - return NewCacherFromConfig(config) -} - // Create a new Cacher responsible from service WATCH and LIST requests from its // internal cache and updating its cache in the background based on the given // configuration. @@ -157,25 +179,25 @@ func NewCacherFromConfig(config CacherConfig) *Cacher { } cacher := &Cacher{ - usable: sync.RWMutex{}, - storage: config.Storage, - watchCache: watchCache, - reflector: cache.NewReflector(listerWatcher, config.Type, watchCache, 0), - watcherIdx: 0, - watchers: make(map[int]*cacheWatcher), - versioner: config.Versioner, - keyFunc: config.KeyFunc, - stopped: false, + ready: newReady(), + storage: config.Storage, + watchCache: watchCache, + reflector: cache.NewReflector(listerWatcher, config.Type, watchCache, 0), + versioner: config.Versioner, + keyFunc: config.KeyFunc, + triggerFunc: config.TriggerPublisherFunc, + watcherIdx: 0, + watchers: indexedWatchers{ + allWatchers: make(map[int]*cacheWatcher), + valueWatchers: make(map[string]watchersMap), + }, // We need to (potentially) stop both: // - wait.Until go-routine // - reflector.ListAndWatch // and there are no guarantees on the order that they will stop. // So we will be simply closing the channel, and synchronizing on the WaitGroup. stopCh: make(chan struct{}), - stopWg: sync.WaitGroup{}, } - // See startCaching method for explanation and where this is unlocked. - cacher.usable.Lock() watchCache.SetOnEvent(cacher.processEvent) stopCh := cacher.stopCh @@ -203,11 +225,11 @@ func (c *Cacher) startCaching(stopChannel <-chan struct{}) { successfulList := false c.watchCache.SetOnReplace(func() { successfulList = true - c.usable.Unlock() + c.ready.set(true) }) defer func() { if successfulList { - c.usable.Lock() + c.ready.set(false) } }() @@ -242,15 +264,13 @@ func (c *Cacher) Delete(ctx context.Context, key string, out runtime.Object, pre } // Implements storage.Interface. -func (c *Cacher) Watch(ctx context.Context, key string, resourceVersion string, filter FilterFunc) (watch.Interface, error) { +func (c *Cacher) Watch(ctx context.Context, key string, resourceVersion string, filter Filter) (watch.Interface, error) { watchRV, err := ParseWatchResourceVersion(resourceVersion) if err != nil { return nil, err } - // Do NOT allow Watch to start when the underlying structures are not propagated. - c.usable.RLock() - defer c.usable.RUnlock() + c.ready.wait() // We explicitly use thread unsafe version and do locking ourself to ensure that // no new events will be processed in the meantime. The watchCache will be unlocked @@ -267,16 +287,26 @@ func (c *Cacher) Watch(ctx context.Context, key string, resourceVersion string, return newErrWatcher(err), nil } + triggerValue, triggerSupported := "", false + // TODO: Currently we assume that in a given Cacher object, any that is + // passed here is aware of exactly the same trigger (at most one). + // Thus, either 0 or 1 values will be returned. + if matchValues := filter.Trigger(); len(matchValues) > 0 { + triggerValue, triggerSupported = matchValues[0].Value, true + } + c.Lock() defer c.Unlock() - watcher := newCacheWatcher(watchRV, initEvents, filterFunction(key, c.keyFunc, filter), forgetWatcher(c, c.watcherIdx)) - c.watchers[c.watcherIdx] = watcher + forget := forgetWatcher(c, c.watcherIdx, triggerValue, triggerSupported) + watcher := newCacheWatcher(watchRV, initEvents, filterFunction(key, c.keyFunc, filter), forget) + + c.watchers.addWatcher(watcher, c.watcherIdx, triggerValue, triggerSupported) c.watcherIdx++ return watcher, nil } // Implements storage.Interface. -func (c *Cacher) WatchList(ctx context.Context, key string, resourceVersion string, filter FilterFunc) (watch.Interface, error) { +func (c *Cacher) WatchList(ctx context.Context, key string, resourceVersion string, filter Filter) (watch.Interface, error) { return c.Watch(ctx, key, resourceVersion, filter) } @@ -286,12 +316,12 @@ func (c *Cacher) Get(ctx context.Context, key string, objPtr runtime.Object, ign } // Implements storage.Interface. -func (c *Cacher) GetToList(ctx context.Context, key string, filter FilterFunc, listObj runtime.Object) error { +func (c *Cacher) GetToList(ctx context.Context, key string, filter Filter, listObj runtime.Object) error { return c.storage.GetToList(ctx, key, filter, listObj) } // Implements storage.Interface. -func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, filter FilterFunc, listObj runtime.Object) error { +func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, filter Filter, listObj runtime.Object) error { if resourceVersion == "" { // If resourceVersion is not specified, serve it from underlying // storage (for backward compatibility). @@ -307,13 +337,7 @@ func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, f return err } - // To avoid situation when List is processed before the underlying - // watchCache is propagated for the first time, we acquire and immediately - // release the 'usable' lock. - // We don't need to hold it all the time, because watchCache is thread-safe - // and it would complicate already very difficult locking pattern. - c.usable.RLock() - c.usable.RUnlock() + c.ready.wait() // List elements from cache, with at least 'listRV'. listPtr, err := meta.GetItemsPtr(listObj) @@ -335,7 +359,7 @@ func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, f if !ok { return fmt.Errorf("non runtime.Object returned from storage: %v", obj) } - if filterFunc(object) { + if filterFunc.Filter(object) { listVal.Set(reflect.Append(listVal, reflect.ValueOf(object).Elem())) } } @@ -357,21 +381,68 @@ func (c *Cacher) Codec() runtime.Codec { return c.storage.Codec() } +func (c *Cacher) triggerValues(event *watchCacheEvent) ([]string, bool) { + // TODO: Currently we assume that in a given Cacher object, its + // is aware of exactly the same trigger (at most one). Thus calling: + // c.triggerFunc() + // can return only 0 or 1 values. + // That means, that triggerValues itself may return up to 2 different values. + if c.triggerFunc == nil { + return nil, false + } + result := make([]string, 0, 2) + matchValues := c.triggerFunc(event.Object) + if len(matchValues) > 0 { + result = append(result, matchValues[0].Value) + } + if event.PrevObject == nil { + return result, len(result) > 0 + } + prevMatchValues := c.triggerFunc(event.PrevObject) + if len(prevMatchValues) > 0 { + if len(result) == 0 || result[0] != prevMatchValues[0].Value { + result = append(result, prevMatchValues[0].Value) + } + } + return result, len(result) > 0 +} + func (c *Cacher) processEvent(event watchCacheEvent) { + triggerValues, supported := c.triggerValues(&event) + c.Lock() defer c.Unlock() - for _, watcher := range c.watchers { + // Iterate over "allWatchers" no matter what the trigger function is. + for _, watcher := range c.watchers.allWatchers { watcher.add(event) } + if supported { + // Iterate over watchers interested in the given values of the trigger. + for _, triggerValue := range triggerValues { + for _, watcher := range c.watchers.valueWatchers[triggerValue] { + watcher.add(event) + } + } + } else { + // supported equal to false generally means that trigger function + // is not defined (or not aware of any indexes). In this case, + // watchers filters should generally also don't generate any + // trigger values, but can cause problems in case of some + // misconfiguration. Thus we paranoidly leave this branch. + + // Iterate over watchers interested in exact values for all values. + for _, watchers := range c.watchers.valueWatchers { + for _, watcher := range watchers { + watcher.add(event) + } + } + } } func (c *Cacher) terminateAllWatchers() { c.Lock() defer c.Unlock() - for key, watcher := range c.watchers { - delete(c.watchers, key) - watcher.stop() - } + c.watchers.terminateAll() } func (c *Cacher) isStopped() bool { @@ -388,20 +459,20 @@ func (c *Cacher) Stop() { c.stopWg.Wait() } -func forgetWatcher(c *Cacher, index int) func(bool) { +func forgetWatcher(c *Cacher, index int, triggerValue string, triggerSupported bool) func(bool) { return func(lock bool) { if lock { c.Lock() defer c.Unlock() } - // It's possible that the watcher is already not in the map (e.g. in case of + // It's possible that the watcher is already not in the structure (e.g. in case of // simulaneous Stop() and terminateAllWatchers(), but it doesn't break anything. - delete(c.watchers, index) + c.watchers.deleteWatcher(index, triggerValue, triggerSupported) } } -func filterFunction(key string, keyFunc func(runtime.Object) (string, error), filter FilterFunc) FilterFunc { - return func(obj runtime.Object) bool { +func filterFunction(key string, keyFunc func(runtime.Object) (string, error), filter Filter) Filter { + filterFunc := func(obj runtime.Object) bool { objKey, err := keyFunc(obj) if err != nil { glog.Errorf("invalid object for filter: %v", obj) @@ -410,24 +481,20 @@ func filterFunction(key string, keyFunc func(runtime.Object) (string, error), fi if !hasPathPrefix(objKey, key) { return false } - return filter(obj) + return filter.Filter(obj) } + return NewSimpleFilter(filterFunc, filter.Trigger) } // Returns resource version to which the underlying cache is synced. func (c *Cacher) LastSyncResourceVersion() (uint64, error) { - // To avoid situation when LastSyncResourceVersion is processed before the - // underlying watchCache is propagated, we acquire 'usable' lock. - c.usable.RLock() - defer c.usable.RUnlock() - - c.RLock() - defer c.RUnlock() + c.ready.wait() resourceVersion := c.reflector.LastSyncResourceVersion() if resourceVersion == "" { return 0, nil } + return strconv.ParseUint(resourceVersion, 10, 64) } @@ -505,12 +572,12 @@ type cacheWatcher struct { sync.Mutex input chan watchCacheEvent result chan watch.Event - filter FilterFunc + filter Filter stopped bool forget func(bool) } -func newCacheWatcher(resourceVersion uint64, initEvents []watchCacheEvent, filter FilterFunc, forget func(bool)) *cacheWatcher { +func newCacheWatcher(resourceVersion uint64, initEvents []watchCacheEvent, filter Filter, forget func(bool)) *cacheWatcher { watcher := &cacheWatcher{ input: make(chan watchCacheEvent, 10), result: make(chan watch.Event, 10), @@ -582,10 +649,10 @@ func (c *cacheWatcher) add(event watchCacheEvent) { } func (c *cacheWatcher) sendWatchCacheEvent(event watchCacheEvent) { - curObjPasses := event.Type != watch.Deleted && c.filter(event.Object) + curObjPasses := event.Type != watch.Deleted && c.filter.Filter(event.Object) oldObjPasses := false if event.PrevObject != nil { - oldObjPasses = c.filter(event.PrevObject) + oldObjPasses = c.filter.Filter(event.PrevObject) } if !curObjPasses && !oldObjPasses { // Watcher is not interested in that object. @@ -626,3 +693,27 @@ func (c *cacheWatcher) process(initEvents []watchCacheEvent, resourceVersion uin } } } + +type ready struct { + ok bool + c *sync.Cond +} + +func newReady() *ready { + return &ready{c: sync.NewCond(&sync.Mutex{})} +} + +func (r *ready) wait() { + r.c.L.Lock() + for !r.ok { + r.c.Wait() + } + r.c.L.Unlock() +} + +func (r *ready) set(ok bool) { + r.c.L.Lock() + defer r.c.L.Unlock() + r.ok = ok + r.c.Broadcast() +} diff --git a/vendor/k8s.io/kubernetes/pkg/storage/doc.go b/vendor/k8s.io/kubernetes/pkg/storage/doc.go index dca0d5b70965..d2c5dbfc4562 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/errors.go b/vendor/k8s.io/kubernetes/pkg/storage/errors.go index 61b3cba52c75..3ae0a8893c81 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -107,7 +107,7 @@ func IsUnreachable(err error) bool { // IsTestFailed returns true if and only if err is a write conflict. func IsTestFailed(err error) bool { - return isErrCode(err, ErrCodeResourceVersionConflicts, ErrCodeInvalidObj) + return isErrCode(err, ErrCodeResourceVersionConflicts) } // IsInvalidUID returns true if and only if err is invalid UID error @@ -115,16 +115,12 @@ func IsInvalidObj(err error) bool { return isErrCode(err, ErrCodeInvalidObj) } -func isErrCode(err error, codes ...int) bool { +func isErrCode(err error, code int) bool { if err == nil { return false } if e, ok := err.(*StorageError); ok { - for _, code := range codes { - if e.Code == code { - return true - } - } + return e.Code == code } return false } diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/api_object_versioner.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/api_object_versioner.go index 639f24a8afde..59839b9367b0 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/api_object_versioner.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/api_object_versioner.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/doc.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/doc.go index 44a2b9d44505..73e2f50c4163 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_helper.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_helper.go index 3de60374396d..3912c4e86f24 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_helper.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_helper.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -150,7 +150,7 @@ func (h *etcdHelper) Create(ctx context.Context, key string, obj, out runtime.Ob return err } -func checkPreconditions(preconditions *storage.Preconditions, out runtime.Object) error { +func checkPreconditions(key string, preconditions *storage.Preconditions, out runtime.Object) error { if preconditions == nil { return nil } @@ -159,7 +159,8 @@ func checkPreconditions(preconditions *storage.Preconditions, out runtime.Object return storage.NewInternalErrorf("can't enforce preconditions %v on un-introspectable object %v, got error: %v", *preconditions, out, err) } if preconditions.UID != nil && *preconditions.UID != objMeta.UID { - return etcd.Error{Code: etcd.ErrorCodeTestFailed, Message: fmt.Sprintf("the UID in the precondition (%s) does not match the UID in record (%s). The object might have been deleted and then recreated", *preconditions.UID, objMeta.UID)} + errMsg := fmt.Sprintf("Precondition failed: UID in precondition: %v, UID in object meta: %v", preconditions.UID, objMeta.UID) + return storage.NewInvalidObjError(key, errMsg) } return nil } @@ -195,7 +196,7 @@ func (h *etcdHelper) Delete(ctx context.Context, key string, out runtime.Object, if err != nil { return toStorageErr(err, key, 0) } - if err := checkPreconditions(preconditions, obj); err != nil { + if err := checkPreconditions(key, preconditions, obj); err != nil { return toStorageErr(err, key, 0) } index := uint64(0) @@ -223,7 +224,7 @@ func (h *etcdHelper) Delete(ctx context.Context, key string, out runtime.Object, } // Implements storage.Interface. -func (h *etcdHelper) Watch(ctx context.Context, key string, resourceVersion string, filter storage.FilterFunc) (watch.Interface, error) { +func (h *etcdHelper) Watch(ctx context.Context, key string, resourceVersion string, filter storage.Filter) (watch.Interface, error) { if ctx == nil { glog.Errorf("Context is nil") } @@ -238,7 +239,7 @@ func (h *etcdHelper) Watch(ctx context.Context, key string, resourceVersion stri } // Implements storage.Interface. -func (h *etcdHelper) WatchList(ctx context.Context, key string, resourceVersion string, filter storage.FilterFunc) (watch.Interface, error) { +func (h *etcdHelper) WatchList(ctx context.Context, key string, resourceVersion string, filter storage.Filter) (watch.Interface, error) { if ctx == nil { glog.Errorf("Context is nil") } @@ -318,7 +319,7 @@ func (h *etcdHelper) extractObj(response *etcd.Response, inErr error, objPtr run } // Implements storage.Interface. -func (h *etcdHelper) GetToList(ctx context.Context, key string, filter storage.FilterFunc, listObj runtime.Object) error { +func (h *etcdHelper) GetToList(ctx context.Context, key string, filter storage.Filter, listObj runtime.Object) error { if ctx == nil { glog.Errorf("Context is nil") } @@ -358,7 +359,7 @@ func (h *etcdHelper) GetToList(ctx context.Context, key string, filter storage.F } // decodeNodeList walks the tree of each node in the list and decodes into the specified object -func (h *etcdHelper) decodeNodeList(nodes []*etcd.Node, filter storage.FilterFunc, slicePtr interface{}) error { +func (h *etcdHelper) decodeNodeList(nodes []*etcd.Node, filter storage.Filter, slicePtr interface{}) error { trace := util.NewTrace("decodeNodeList " + getTypeName(slicePtr)) defer trace.LogIfLong(400 * time.Millisecond) v, err := conversion.EnforcePtr(slicePtr) @@ -387,7 +388,7 @@ func (h *etcdHelper) decodeNodeList(nodes []*etcd.Node, filter storage.FilterFun } // being unable to set the version does not prevent the object from being extracted _ = h.versioner.UpdateObject(obj, node.ModifiedIndex) - if filter(obj) { + if filter.Filter(obj) { v.Set(reflect.Append(v, reflect.ValueOf(obj).Elem())) } if node.ModifiedIndex != 0 { @@ -400,7 +401,7 @@ func (h *etcdHelper) decodeNodeList(nodes []*etcd.Node, filter storage.FilterFun } // Implements storage.Interface. -func (h *etcdHelper) List(ctx context.Context, key string, resourceVersion string, filter storage.FilterFunc, listObj runtime.Object) error { +func (h *etcdHelper) List(ctx context.Context, key string, resourceVersion string, filter storage.Filter, listObj runtime.Object) error { if ctx == nil { glog.Errorf("Context is nil") } @@ -471,7 +472,7 @@ func (h *etcdHelper) GuaranteedUpdate(ctx context.Context, key string, ptrToType if err != nil { return toStorageErr(err, key, 0) } - if err := checkPreconditions(preconditions, obj); err != nil { + if err := checkPreconditions(key, preconditions, obj); err != nil { return toStorageErr(err, key, 0) } meta := storage.ResponseMeta{} @@ -569,7 +570,7 @@ func (h *etcdHelper) prefixEtcdKey(key string) string { // their Node.ModifiedIndex, which is unique across all types. // All implementations must be thread-safe. type etcdCache interface { - getFromCache(index uint64, filter storage.FilterFunc) (runtime.Object, bool) + getFromCache(index uint64, filter storage.Filter) (runtime.Object, bool) addToCache(index uint64, obj runtime.Object) } @@ -577,14 +578,14 @@ func getTypeName(obj interface{}) string { return reflect.TypeOf(obj).String() } -func (h *etcdHelper) getFromCache(index uint64, filter storage.FilterFunc) (runtime.Object, bool) { +func (h *etcdHelper) getFromCache(index uint64, filter storage.Filter) (runtime.Object, bool) { startTime := time.Now() defer func() { metrics.ObserveGetCache(startTime) }() obj, found := h.cache.Get(index) if found { - if !filter(obj.(runtime.Object)) { + if !filter.Filter(obj.(runtime.Object)) { return nil, true } // We should not return the object itself to avoid polluting the cache if someone diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_watcher.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_watcher.go index c856b59ccf89..e6cbd3969676 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_watcher.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/etcd_watcher.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ type etcdWatcher struct { list bool // If we're doing a recursive watch, should be true. quorum bool // If we enable quorum, shoule be true include includeFunc - filter storage.FilterFunc + filter storage.Filter etcdIncoming chan *etcd.Response etcdError chan error @@ -116,7 +116,7 @@ const watchWaitDuration = 100 * time.Millisecond // newEtcdWatcher returns a new etcdWatcher; if list is true, watch sub-nodes. // The versioner must be able to handle the objects that transform creates. func newEtcdWatcher( - list bool, quorum bool, include includeFunc, filter storage.FilterFunc, + list bool, quorum bool, include includeFunc, filter storage.Filter, encoding runtime.Codec, versioner storage.Versioner, transform TransformFunc, cache etcdCache) *etcdWatcher { w := &etcdWatcher{ @@ -364,7 +364,7 @@ func (w *etcdWatcher) sendAdd(res *etcd.Response) { // the resourceVersion to resume will never be able to get past a bad value. return } - if !w.filter(obj) { + if !w.filter.Filter(obj) { return } action := watch.Added @@ -393,7 +393,7 @@ func (w *etcdWatcher) sendModify(res *etcd.Response) { // the resourceVersion to resume will never be able to get past a bad value. return } - curObjPasses := w.filter(curObj) + curObjPasses := w.filter.Filter(curObj) oldObjPasses := false var oldObj runtime.Object if res.PrevNode != nil && res.PrevNode.Value != "" { @@ -402,7 +402,7 @@ func (w *etcdWatcher) sendModify(res *etcd.Response) { if err := w.versioner.UpdateObject(oldObj, res.Node.ModifiedIndex); err != nil { utilruntime.HandleError(fmt.Errorf("failure to version api object (%d) %#v: %v", res.Node.ModifiedIndex, oldObj, err)) } - oldObjPasses = w.filter(oldObj) + oldObjPasses = w.filter.Filter(oldObj) } } // Some changes to an object may cause it to start or stop matching a filter. @@ -451,7 +451,7 @@ func (w *etcdWatcher) sendDelete(res *etcd.Response) { // the resourceVersion to resume will never be able to get past a bad value. return } - if !w.filter(obj) { + if !w.filter.Filter(obj) { return } w.emit(watch.Event{ diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/metrics/metrics.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/metrics/metrics.go index 7e88e43c2e6f..119e2e8fc6ec 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/metrics/metrics.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/metrics/metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/doc.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/doc.go index aa1039fafa8c..48a70cb737dc 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/etcd_util.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/etcd_util.go index b15ec5bd0199..7c71fe24fc53 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/etcd_util.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd/util/etcd_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/compact.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/compact.go index ddd8e312c3ec..ad1ac1ac2a26 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/compact.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/compact.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ limitations under the License. package etcd3 import ( + "strconv" "sync" "time" @@ -25,7 +26,10 @@ import ( "golang.org/x/net/context" ) -const compactInterval = 10 * time.Minute +const ( + compactInterval = 10 * time.Minute + compactRevKey = "compact_rev_key" +) var ( endpointsMapMu sync.Mutex @@ -36,19 +40,16 @@ func init() { endpointsMap = make(map[string]struct{}) } -// StartCompactor starts a compactor in the background in order to compact keys -// older than fixed time. -// We need to compact keys because we can't let on disk data grow forever. -// We save the most recent 10 minutes data. It should be enough for slow watchers and to tolerate burst. -// TODO: We might keep a longer history (12h) in the future once storage API can take -// advantage of multi-version key. +// StartCompactor starts a compactor in the background to compact old version of keys that's not needed. +// By default, we save the most recent 10 minutes data and compact versions > 10minutes ago. +// It should be enough for slow watchers and to tolerate burst. +// TODO: We might keep a longer history (12h) in the future once storage API can take advantage of past version of keys. func StartCompactor(ctx context.Context, client *clientv3.Client) { endpointsMapMu.Lock() defer endpointsMapMu.Unlock() - // We can't have multiple compaction jobs for the same cluster. + // In one process, we can have only one compactor for one cluster. // Currently we rely on endpoints to differentiate clusters. - var emptyStruct struct{} for _, ep := range client.Endpoints() { if _, ok := endpointsMap[ep]; ok { glog.V(4).Infof("compactor already exists for endpoints %v", client.Endpoints()) @@ -56,18 +57,59 @@ func StartCompactor(ctx context.Context, client *clientv3.Client) { } } for _, ep := range client.Endpoints() { - endpointsMap[ep] = emptyStruct + endpointsMap[ep] = struct{}{} } go compactor(ctx, client, compactInterval) } // compactor periodically compacts historical versions of keys in etcd. -// After compaction, old versions of keys set before given interval will be gone. -// Any API call for the old versions of keys will return error. -// interval: the interval between each compaction. The first compaction happens after "interval". +// It will compact keys with versions older than given interval. +// In other words, after compaction, it will only contain keys set during last interval. +// Any API call for the older versions of keys will return error. +// Interval is the time interval between each compaction. The first compaction happens after "interval". func compactor(ctx context.Context, client *clientv3.Client, interval time.Duration) { - var curRev int64 + // Technical definitions: + // We have a special key in etcd defined as *compactRevKey*. + // compactRevKey's value will be set to the string of last compacted revision. + // compactRevKey's version will be used as logical time for comparison. THe version is referred as compact time. + // Initially, because the key doesn't exist, the compact time (version) is 0. + // + // Algorithm: + // - Compare to see if (local compact_time) = (remote compact_time). + // - If yes, increment both local and remote compact_time, and do a compaction. + // - If not, set local to remote compact_time. + // + // Technical details/insights: + // + // The protocol here is lease based. If one compactor CAS successfully, the others would know it when they fail in + // CAS later and would try again in 10 minutes. If an APIServer crashed, another one would "take over" the lease. + // + // For example, in the following diagram, we have a compactor C1 doing compaction in t1, t2. Another compactor C2 + // at t1' (t1 < t1' < t2) would CAS fail, set its known oldRev to rev at t1, and try again in t2' (t2' > t2). + // If C1 crashed and wouldn't compact at t2, C2 would CAS successfully at t2'. + // + // oldRev(t2) curRev(t2) + // + + // oldRev curRev | + // + + | + // | | | + // | | t1' | t2' + // +---v-------------v----^---------v------^----> + // t0 t1 t2 + // + // We have the guarantees: + // - in normal cases, the interval is 10 minutes. + // - in failover, the interval is >10m and <20m + // + // FAQ: + // - What if time is not accurate? We don't care as long as someone did the compaction. Atomicity is ensured using + // etcd API. + // - What happened under heavy load scenarios? Initially, each apiserver will do only one compaction + // every 10 minutes. This is very unlikely affecting or affected w.r.t. server load. + + var compactTime int64 + var rev int64 var err error for { select { @@ -76,29 +118,44 @@ func compactor(ctx context.Context, client *clientv3.Client, interval time.Durat return } - curRev, err = compact(ctx, client, curRev) + compactTime, rev, err = compact(ctx, client, compactTime, rev) if err != nil { - glog.Error(err) + glog.Errorf("etcd: endpoint (%v) compact failed: %v", client.Endpoints(), err) continue } } } // compact compacts etcd store and returns current rev. -// If it couldn't get current revision, the old rev will be returned. -func compact(ctx context.Context, client *clientv3.Client, oldRev int64) (int64, error) { - resp, err := client.Get(ctx, "/") +// It will return the current compact time and global revision if no error occurred. +// Note that CAS fail will not incur any error. +func compact(ctx context.Context, client *clientv3.Client, t, rev int64) (int64, int64, error) { + resp, err := client.KV.Txn(ctx).If( + clientv3.Compare(clientv3.Version(compactRevKey), "=", t), + ).Then( + clientv3.OpPut(compactRevKey, strconv.FormatInt(rev, 10)), // Expect side effect: increment Version + ).Else( + clientv3.OpGet(compactRevKey), + ).Commit() if err != nil { - return oldRev, err + return t, rev, err } + curRev := resp.Header.Revision - if oldRev == 0 { - return curRev, nil + + if !resp.Succeeded { + curTime := resp.Responses[0].GetResponseRange().Kvs[0].Version + return curTime, curRev, nil } - err = client.Compact(ctx, oldRev) - if err != nil { - return curRev, err + curTime := t + 1 + + if rev == 0 { + // We don't compact on bootstrap. + return curTime, curRev, nil + } + if err = client.Compact(ctx, rev); err != nil { + return curTime, curRev, err } - glog.Infof("etcd: Compacted rev %d, endpoints %v", oldRev, client.Endpoints()) - return curRev, nil + glog.Infof("etcd: compacted rev (%d), endpoints (%v)", rev, client.Endpoints()) + return curTime, curRev, nil } diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/event.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/event.go index 58072bd7b4f2..93f994346be7 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/event.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/event.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/store.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/store.go index 4ac455df5d64..88984756a6f1 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/store.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/store.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -274,7 +274,7 @@ func (s *store) GuaranteedUpdate(ctx context.Context, key string, out runtime.Ob } // GetToList implements storage.Interface.GetToList. -func (s *store) GetToList(ctx context.Context, key string, filter storage.FilterFunc, listObj runtime.Object) error { +func (s *store) GetToList(ctx context.Context, key string, filter storage.Filter, listObj runtime.Object) error { listPtr, err := meta.GetItemsPtr(listObj) if err != nil { return err @@ -300,7 +300,7 @@ func (s *store) GetToList(ctx context.Context, key string, filter storage.Filter } // List implements storage.Interface.List. -func (s *store) List(ctx context.Context, key, resourceVersion string, filter storage.FilterFunc, listObj runtime.Object) error { +func (s *store) List(ctx context.Context, key, resourceVersion string, filter storage.Filter, listObj runtime.Object) error { listPtr, err := meta.GetItemsPtr(listObj) if err != nil { return err @@ -332,16 +332,16 @@ func (s *store) List(ctx context.Context, key, resourceVersion string, filter st } // Watch implements storage.Interface.Watch. -func (s *store) Watch(ctx context.Context, key string, resourceVersion string, filter storage.FilterFunc) (watch.Interface, error) { +func (s *store) Watch(ctx context.Context, key string, resourceVersion string, filter storage.Filter) (watch.Interface, error) { return s.watch(ctx, key, resourceVersion, filter, false) } // WatchList implements storage.Interface.WatchList. -func (s *store) WatchList(ctx context.Context, key string, resourceVersion string, filter storage.FilterFunc) (watch.Interface, error) { +func (s *store) WatchList(ctx context.Context, key string, resourceVersion string, filter storage.Filter) (watch.Interface, error) { return s.watch(ctx, key, resourceVersion, filter, true) } -func (s *store) watch(ctx context.Context, key string, rv string, filter storage.FilterFunc, recursive bool) (watch.Interface, error) { +func (s *store) watch(ctx context.Context, key string, rv string, filter storage.Filter, recursive bool) (watch.Interface, error) { rev, err := storage.ParseWatchResourceVersion(rv) if err != nil { return nil, err @@ -435,7 +435,7 @@ func decode(codec runtime.Codec, versioner storage.Versioner, value []byte, objP // decodeList decodes a list of values into a list of objects, with resource version set to corresponding rev. // On success, ListPtr would be set to the list of objects. -func decodeList(elems []*elemForDecode, filter storage.FilterFunc, ListPtr interface{}, codec runtime.Codec, versioner storage.Versioner) error { +func decodeList(elems []*elemForDecode, filter storage.Filter, ListPtr interface{}, codec runtime.Codec, versioner storage.Versioner) error { v, err := conversion.EnforcePtr(ListPtr) if err != nil || v.Kind() != reflect.Slice { panic("need ptr to slice") @@ -447,7 +447,7 @@ func decodeList(elems []*elemForDecode, filter storage.FilterFunc, ListPtr inter } // being unable to set the version does not prevent the object from being extracted versioner.UpdateObject(obj, elem.rev) - if filter(obj) { + if filter.Filter(obj) { v.Set(reflect.Append(v, reflect.ValueOf(obj).Elem())) } } diff --git a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/watcher.go b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/watcher.go index 1e13d59b5847..02bc31437d80 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/etcd3/watcher.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/etcd3/watcher.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ type watchChan struct { key string initialRev int64 recursive bool - filter storage.FilterFunc + filter storage.Filter ctx context.Context cancel context.CancelFunc incomingEventChan chan *event @@ -76,7 +76,7 @@ func newWatcher(client *clientv3.Client, codec runtime.Codec, versioner storage. // If recursive is false, it watches on given key. // If recursive is true, it watches any children and directories under the key, excluding the root key itself. // filter must be non-nil. Only if filter returns true will the changes be returned. -func (w *watcher) Watch(ctx context.Context, key string, rev int64, recursive bool, filter storage.FilterFunc) (watch.Interface, error) { +func (w *watcher) Watch(ctx context.Context, key string, rev int64, recursive bool, filter storage.Filter) (watch.Interface, error) { if recursive && !strings.HasSuffix(key, "/") { key += "/" } @@ -85,7 +85,7 @@ func (w *watcher) Watch(ctx context.Context, key string, rev int64, recursive bo return wc, nil } -func (w *watcher) createWatchChan(ctx context.Context, key string, rev int64, recursive bool, filter storage.FilterFunc) *watchChan { +func (w *watcher) createWatchChan(ctx context.Context, key string, rev int64, recursive bool, filter storage.Filter) *watchChan { wc := &watchChan{ watcher: w, key: key, @@ -221,7 +221,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { switch { case e.isDeleted: - if !wc.filter(oldObj) { + if !wc.filter.Filter(oldObj) { return nil } res = &watch.Event{ @@ -229,7 +229,7 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { Object: oldObj, } case e.isCreated: - if !wc.filter(curObj) { + if !wc.filter.Filter(curObj) { return nil } res = &watch.Event{ @@ -237,8 +237,8 @@ func (wc *watchChan) transform(e *event) (res *watch.Event) { Object: curObj, } default: - curObjPasses := wc.filter(curObj) - oldObjPasses := wc.filter(oldObj) + curObjPasses := wc.filter.Filter(curObj) + oldObjPasses := wc.filter.Filter(oldObj) switch { case curObjPasses && oldObjPasses: res = &watch.Event{ diff --git a/vendor/k8s.io/kubernetes/pkg/storage/interfaces.go b/vendor/k8s.io/kubernetes/pkg/storage/interfaces.go index 89290e29abe5..b4b0aace58c2 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -51,15 +51,47 @@ type ResponseMeta struct { ResourceVersion uint64 } -// FilterFunc is a predicate which takes an API object and returns true -// if and only if the object should remain in the set. -type FilterFunc func(obj runtime.Object) bool +// MatchValue defines a pair (, ). +type MatchValue struct { + IndexName string + Value string +} + +// TriggerPublisherFunc is a function that takes an object, and returns a list of pairs +// (, ) for all indexes known +// to that function. +type TriggerPublisherFunc func(obj runtime.Object) []MatchValue + +// Filter is interface that is used to pass filtering mechanism. +type Filter interface { + // Filter is a predicate which takes an API object and returns true + // if and only if the object should remain in the set. + Filter(obj runtime.Object) bool + // For any triggers known to the Filter, if Filter() can return only + // (a subset of) objects for which indexing function returns , + // (, pair would be returned. + // + // This is optimization to avoid computing Filter() function (which are + // usually relatively expensive) in case we are sure they will return + // false anyway. + Trigger() []MatchValue +} + +// Everything is a Filter which accepts all objects. +var Everything Filter = everything{} -// Everything is a FilterFunc which accepts all objects. -func Everything(runtime.Object) bool { +// everything is implementation of Everything. +type everything struct { +} + +func (e everything) Filter(runtime.Object) bool { return true } +func (e everything) Trigger() []MatchValue { + return nil +} + // Pass an UpdateFunc to Interface.GuaranteedUpdate to make an update // that is guaranteed to succeed. // See the comment for GuaranteedUpdate for more details. @@ -77,7 +109,7 @@ func NewUIDPreconditions(uid string) *Preconditions { return &Preconditions{UID: &u} } -// Interface offers a common interface for object marshaling/unmarshling operations and +// Interface offers a common interface for object marshaling/unmarshaling operations and // hides all the storage-related operations behind it. type Interface interface { // Returns list of servers addresses of the underyling database. @@ -102,14 +134,14 @@ type Interface interface { // resourceVersion may be used to specify what version to begin watching, // which should be the current resourceVersion, and no longer rv+1 // (e.g. reconnecting without missing any updates). - Watch(ctx context.Context, key string, resourceVersion string, filter FilterFunc) (watch.Interface, error) + Watch(ctx context.Context, key string, resourceVersion string, filter Filter) (watch.Interface, error) // WatchList begins watching the specified key's items. Items are decoded into API // objects and any item passing 'filter' are sent down to returned watch.Interface. // resourceVersion may be used to specify what version to begin watching, // which should be the current resourceVersion, and no longer rv+1 // (e.g. reconnecting without missing any updates). - WatchList(ctx context.Context, key string, resourceVersion string, filter FilterFunc) (watch.Interface, error) + WatchList(ctx context.Context, key string, resourceVersion string, filter Filter) (watch.Interface, error) // Get unmarshals json found at key into objPtr. On a not found error, will either // return a zero object of the requested type, or an error, depending on ignoreNotFound. @@ -118,13 +150,13 @@ type Interface interface { // GetToList unmarshals json found at key and opaque it into *List api object // (an object that satisfies the runtime.IsList definition). - GetToList(ctx context.Context, key string, filter FilterFunc, listObj runtime.Object) error + GetToList(ctx context.Context, key string, filter Filter, listObj runtime.Object) error // List unmarshalls jsons found at directory defined by key and opaque them // into *List api object (an object that satisfies runtime.IsList definition). // The returned contents may be delayed, but it is guaranteed that they will // be have at least 'resourceVersion'. - List(ctx context.Context, key string, resourceVersion string, filter FilterFunc, listObj runtime.Object) error + List(ctx context.Context, key string, resourceVersion string, filter Filter, listObj runtime.Object) error // GuaranteedUpdate keeps calling 'tryUpdate()' to update key 'key' (of type 'ptrToType') // retrying the update until success if there is index conflict. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/config.go b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/config.go index d1e17c87caea..9b3c469a40a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/config.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/config.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd2.go b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd2.go index 4ac526d99968..b5a5ee29388a 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd2.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd2.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd3.go b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd3.go index add091a06904..73f9913d72ba 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd3.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/etcd3.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/factory.go b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/factory.go index cc7ae052e910..f6bb263da954 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/factory.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/storagebackend/factory/factory.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/storage/util.go b/vendor/k8s.io/kubernetes/pkg/storage/util.go index 6f208f833596..571e104d9363 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/util.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -37,6 +37,41 @@ func SimpleUpdate(fn SimpleUpdateFunc) UpdateFunc { } } +// SimpleFilter implements Filter interface. +type SimpleFilter struct { + filterFunc func(runtime.Object) bool + triggerFunc func() []MatchValue +} + +func (s *SimpleFilter) Filter(obj runtime.Object) bool { + return s.filterFunc(obj) +} + +func (s *SimpleFilter) Trigger() []MatchValue { + return s.triggerFunc() +} + +func NewSimpleFilter( + filterFunc func(runtime.Object) bool, + triggerFunc func() []MatchValue) Filter { + return &SimpleFilter{ + filterFunc: filterFunc, + triggerFunc: triggerFunc, + } +} + +func EverythingFunc(runtime.Object) bool { + return true +} + +func NoTriggerFunc() []MatchValue { + return nil +} + +func NoTriggerPublisher(runtime.Object) []MatchValue { + return nil +} + // ParseWatchResourceVersion takes a resource version argument and converts it to // the etcd version we should pass to helper.Watch(). Because resourceVersion is // an opaque value, the default watch behavior for non-zero watch is to watch diff --git a/vendor/k8s.io/kubernetes/pkg/storage/watch_cache.go b/vendor/k8s.io/kubernetes/pkg/storage/watch_cache.go index 3e5ce5d73003..b3f5e0371caf 100644 --- a/vendor/k8s.io/kubernetes/pkg/storage/watch_cache.go +++ b/vendor/k8s.io/kubernetes/pkg/storage/watch_cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import ( "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/watch" ) @@ -96,7 +96,7 @@ type watchCache struct { onEvent func(watchCacheEvent) // for testing timeouts. - clock util.Clock + clock clock.Clock } func newWatchCache(capacity int) *watchCache { @@ -107,7 +107,7 @@ func newWatchCache(capacity int) *watchCache { endIndex: 0, store: cache.NewStore(cache.MetaNamespaceKeyFunc), resourceVersion: 0, - clock: util.RealClock{}, + clock: clock.RealClock{}, } wc.cond = sync.NewCond(wc.RLocker()) return wc diff --git a/vendor/k8s.io/kubernetes/pkg/types/doc.go b/vendor/k8s.io/kubernetes/pkg/types/doc.go index 239a9a5f51f3..783cbcdc8db3 100644 --- a/vendor/k8s.io/kubernetes/pkg/types/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/types/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/types/namespacedname.go b/vendor/k8s.io/kubernetes/pkg/types/namespacedname.go index 895d7c5beb89..70a9ac3e24ec 100644 --- a/vendor/k8s.io/kubernetes/pkg/types/namespacedname.go +++ b/vendor/k8s.io/kubernetes/pkg/types/namespacedname.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/types/uid.go b/vendor/k8s.io/kubernetes/pkg/types/uid.go index de6cd18fbebf..869339222e96 100644 --- a/vendor/k8s.io/kubernetes/pkg/types/uid.go +++ b/vendor/k8s.io/kubernetes/pkg/types/uid.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/types/unix_user_id.go b/vendor/k8s.io/kubernetes/pkg/types/unix_user_id.go index b59792abff51..dc770c11e2b5 100644 --- a/vendor/k8s.io/kubernetes/pkg/types/unix_user_id.go +++ b/vendor/k8s.io/kubernetes/pkg/types/unix_user_id.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/ui/data/swagger/datafile.go b/vendor/k8s.io/kubernetes/pkg/ui/data/swagger/datafile.go index 1a49fe6779c3..0ccd806f738b 100644 --- a/vendor/k8s.io/kubernetes/pkg/ui/data/swagger/datafile.go +++ b/vendor/k8s.io/kubernetes/pkg/ui/data/swagger/datafile.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/ui/doc.go b/vendor/k8s.io/kubernetes/pkg/ui/doc.go index 7e566d32466b..4a1abc71c7fe 100644 --- a/vendor/k8s.io/kubernetes/pkg/ui/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/ui/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/ui/installsupport.go b/vendor/k8s.io/kubernetes/pkg/ui/installsupport.go index 15d1bb30a6f8..49a12671679a 100644 --- a/vendor/k8s.io/kubernetes/pkg/ui/installsupport.go +++ b/vendor/k8s.io/kubernetes/pkg/ui/installsupport.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/doc.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/doc.go index 5ae73e8be6d8..289b17fe291e 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go index 12798bde18e2..ad8712d5b8c3 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/fake_shaper.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go index 62b20d87d0c6..a6792afe2193 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/linux.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/linux.go index edb480c6977d..13d6a7e58e0e 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -255,7 +255,7 @@ func (t *tcShaper) ReconcileInterface() error { return t.initializeInterface() } fields := strings.Split(output, " ") - if len(fields) != 12 || fields[1] != "htb" || fields[2] != "1:" { + if len(fields) < 12 || fields[1] != "htb" || fields[2] != "1:" { if err := t.deleteInterface(fields[2]); err != nil { return err } diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go index 7f980a26558e..21ed2ad28380 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/utils.go b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/utils.go index b501e9b5c803..77447b4840a1 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/bandwidth/utils.go +++ b/vendor/k8s.io/kubernetes/pkg/util/bandwidth/utils.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/cache/cache.go b/vendor/k8s.io/kubernetes/pkg/util/cache/cache.go index 1f96c9b9aacc..9a09fe54d6eb 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/cache/cache.go +++ b/vendor/k8s.io/kubernetes/pkg/util/cache/cache.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/cache/lruexpirecache.go b/vendor/k8s.io/kubernetes/pkg/util/cache/lruexpirecache.go index 22f7f27679c2..7e1bb65a87b1 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/cache/lruexpirecache.go +++ b/vendor/k8s.io/kubernetes/pkg/util/cache/lruexpirecache.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/certificates/csr.go b/vendor/k8s.io/kubernetes/pkg/util/certificates/csr.go new file mode 100644 index 000000000000..86b037df42c7 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/certificates/csr.go @@ -0,0 +1,40 @@ +/* +Copyright 2016 The Kubernetes 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 certificates + +import ( + "crypto/x509" + "encoding/pem" + "errors" + + "k8s.io/kubernetes/pkg/apis/certificates" +) + +// ParseCertificateRequestObject extracts the CSR from the API object and decodes it. +func ParseCertificateRequestObject(obj *certificates.CertificateSigningRequest) (*x509.CertificateRequest, error) { + // extract PEM from request object + pemBytes := obj.Spec.Request + block, _ := pem.Decode(pemBytes) + if block == nil || block.Type != "CERTIFICATE REQUEST" { + return nil, errors.New("PEM block type must be CERTIFICATE REQUEST") + } + csr, err := x509.ParseCertificateRequest(block.Bytes) + if err != nil { + return nil, err + } + return csr, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/chmod/chmod.go b/vendor/k8s.io/kubernetes/pkg/util/chmod/chmod.go index 5b646c95bc49..d051137d0b12 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/chmod/chmod.go +++ b/vendor/k8s.io/kubernetes/pkg/util/chmod/chmod.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/chmod/doc.go b/vendor/k8s.io/kubernetes/pkg/util/chmod/doc.go index a230e98fdc97..4e3912541974 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/chmod/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/chmod/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/chown/chown.go b/vendor/k8s.io/kubernetes/pkg/util/chown/chown.go index 0d90629de825..8a99084c3d8d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/chown/chown.go +++ b/vendor/k8s.io/kubernetes/pkg/util/chown/chown.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/chown/doc.go b/vendor/k8s.io/kubernetes/pkg/util/chown/doc.go index 3c41f5ed3b40..cf71fd1568ea 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/chown/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/chown/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/clock.go b/vendor/k8s.io/kubernetes/pkg/util/clock/clock.go similarity index 98% rename from vendor/k8s.io/kubernetes/pkg/util/clock.go rename to vendor/k8s.io/kubernetes/pkg/util/clock/clock.go index 474cbb68d11f..2ea1b53c1a3d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/clock.go +++ b/vendor/k8s.io/kubernetes/pkg/util/clock/clock.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package util +package clock import ( "sync" diff --git a/vendor/k8s.io/kubernetes/pkg/util/config/config.go b/vendor/k8s.io/kubernetes/pkg/util/config/config.go index 37f6f6ab1865..30defee87da7 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/config/config.go +++ b/vendor/k8s.io/kubernetes/pkg/util/config/config.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/config/configuration_map.go b/vendor/k8s.io/kubernetes/pkg/util/config/configuration_map.go index e7ad4fadb3d7..0acbde56f8fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/config/configuration_map.go +++ b/vendor/k8s.io/kubernetes/pkg/util/config/configuration_map.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/config/doc.go b/vendor/k8s.io/kubernetes/pkg/util/config/doc.go index 697f3ab566c2..5dbb37d44874 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/config/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/config/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/configz/configz.go b/vendor/k8s.io/kubernetes/pkg/util/configz/configz.go index e8954a4a8fc0..bed7c96148af 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/configz/configz.go +++ b/vendor/k8s.io/kubernetes/pkg/util/configz/configz.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/crypto/crypto.go b/vendor/k8s.io/kubernetes/pkg/util/crypto/crypto.go index f43664369f61..b573c8a5945c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/crypto/crypto.go +++ b/vendor/k8s.io/kubernetes/pkg/util/crypto/crypto.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/dbus/dbus.go b/vendor/k8s.io/kubernetes/pkg/util/dbus/dbus.go index 13da1469e567..702d16e5dce2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/dbus/dbus.go +++ b/vendor/k8s.io/kubernetes/pkg/util/dbus/dbus.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/dbus/doc.go b/vendor/k8s.io/kubernetes/pkg/util/dbus/doc.go index 59bec0e56064..e09ad3e5c862 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/dbus/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/dbus/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go b/vendor/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go index eb97febae49e..44131272e7a9 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go +++ b/vendor/k8s.io/kubernetes/pkg/util/dbus/fake_dbus.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/diff/diff.go b/vendor/k8s.io/kubernetes/pkg/util/diff/diff.go index c1fd723752bb..aa83a6742e45 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/diff/diff.go +++ b/vendor/k8s.io/kubernetes/pkg/util/diff/diff.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -145,7 +145,7 @@ func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff { } } return changes - case reflect.Ptr: + case reflect.Ptr, reflect.Interface: if a.IsNil() || b.IsNil() { switch { case a.IsNil() && b.IsNil(): @@ -177,10 +177,10 @@ func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff { } } var diffs []diff - for i := l; l < lA; i++ { + for i := l; i < lA; i++ { diffs = append(diffs, diff{path: path.Index(i), a: a.Index(i), b: nil}) } - for i := l; l < lB; i++ { + for i := l; i < lB; i++ { diffs = append(diffs, diff{path: path.Index(i), a: nil, b: b.Index(i)}) } return diffs @@ -199,7 +199,7 @@ func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff { if reflect.DeepEqual(a.MapIndex(key).Interface(), b.MapIndex(key).Interface()) { continue } - missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: a.MapIndex(key).Interface(), b: b.MapIndex(key).Interface()}) + missing = append(missing, objectReflectDiff(path.Key(fmt.Sprintf("%s", key.Interface())), a.MapIndex(key), b.MapIndex(key))...) continue } missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: nil, b: b.MapIndex(key).Interface()}) diff --git a/vendor/k8s.io/kubernetes/pkg/util/doc.go b/vendor/k8s.io/kubernetes/pkg/util/doc.go index cd3f0823e7af..1747db550671 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/env/env.go b/vendor/k8s.io/kubernetes/pkg/util/env/env.go index ad4310c25cea..dee544f7c668 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/env/env.go +++ b/vendor/k8s.io/kubernetes/pkg/util/env/env.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/errors/doc.go b/vendor/k8s.io/kubernetes/pkg/util/errors/doc.go index b0af0f0558f8..b3b39bc388f3 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/errors/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/errors/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/errors/errors.go b/vendor/k8s.io/kubernetes/pkg/util/errors/errors.go index df3adaf3e8b4..0445c142bea4 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/errors/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/util/errors/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/exec/doc.go b/vendor/k8s.io/kubernetes/pkg/util/exec/doc.go index 64c1541bf7a7..8b824d24456e 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/exec/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/exec/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/exec/exec.go b/vendor/k8s.io/kubernetes/pkg/util/exec/exec.go index 80444a9d86f4..f40e7fd37779 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/exec/exec.go +++ b/vendor/k8s.io/kubernetes/pkg/util/exec/exec.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/exec/fake_exec.go b/vendor/k8s.io/kubernetes/pkg/util/exec/fake_exec.go index 40df52921bed..79bfce6ee6e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/exec/fake_exec.go +++ b/vendor/k8s.io/kubernetes/pkg/util/exec/fake_exec.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/flock/flock_other.go b/vendor/k8s.io/kubernetes/pkg/util/flock/flock_other.go index b80981882d84..069a5b3a2cb1 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flock/flock_other.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flock/flock_other.go @@ -1,7 +1,7 @@ // +build !linux,!darwin,!freebsd,!openbsd,!netbsd,!dragonfly /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/flock/flock_unix.go b/vendor/k8s.io/kubernetes/pkg/util/flock/flock_unix.go index 88ca8d700fcb..366090ccfd1d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flock/flock_unix.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flock/flock_unix.go @@ -1,7 +1,7 @@ // +build linux darwin freebsd openbsd netbsd dragonfly /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/backoff.go b/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/backoff.go index 1898c55c99d7..2d91cc5e021c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/backoff.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/backoff.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import ( "sync" "time" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" "k8s.io/kubernetes/pkg/util/integer" ) @@ -31,13 +31,13 @@ type backoffEntry struct { type Backoff struct { sync.Mutex - Clock util.Clock + Clock clock.Clock defaultDuration time.Duration maxDuration time.Duration perItemBackoff map[string]*backoffEntry } -func NewFakeBackOff(initial, max time.Duration, tc *util.FakeClock) *Backoff { +func NewFakeBackOff(initial, max time.Duration, tc *clock.FakeClock) *Backoff { return &Backoff{ perItemBackoff: map[string]*backoffEntry{}, Clock: tc, @@ -49,7 +49,7 @@ func NewFakeBackOff(initial, max time.Duration, tc *util.FakeClock) *Backoff { func NewBackOff(initial, max time.Duration) *Backoff { return &Backoff{ perItemBackoff: map[string]*backoffEntry{}, - Clock: util.RealClock{}, + Clock: clock.RealClock{}, defaultDuration: initial, maxDuration: max, } diff --git a/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/throttle.go b/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/throttle.go index a63817ca8c10..232ef6e58c6a 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/throttle.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flowcontrol/throttle.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -35,10 +35,13 @@ type RateLimiter interface { // Usually we use token bucket rate limiter. In that case, // 1.0 means no tokens are available; 0.0 means we have a full bucket of tokens to use. Saturation() float64 + // QPS returns QPS of this rate limiter + QPS() float32 } type tokenBucketRateLimiter struct { limiter *ratelimit.Bucket + qps float32 } // NewTokenBucketRateLimiter creates a rate limiter which implements a token bucket approach. @@ -48,7 +51,10 @@ type tokenBucketRateLimiter struct { // The maximum number of tokens in the bucket is capped at 'burst'. func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter { limiter := ratelimit.NewBucketWithRate(float64(qps), int64(burst)) - return &tokenBucketRateLimiter{limiter} + return &tokenBucketRateLimiter{ + limiter: limiter, + qps: qps, + } } func (t *tokenBucketRateLimiter) TryAccept() bool { @@ -69,6 +75,10 @@ func (t *tokenBucketRateLimiter) Accept() { func (t *tokenBucketRateLimiter) Stop() { } +func (t *tokenBucketRateLimiter) QPS() float32 { + return t.qps +} + type fakeAlwaysRateLimiter struct{} func NewFakeAlwaysRateLimiter() RateLimiter { @@ -87,6 +97,10 @@ func (t *fakeAlwaysRateLimiter) Stop() {} func (t *fakeAlwaysRateLimiter) Accept() {} +func (t *fakeAlwaysRateLimiter) QPS() float32 { + return 1 +} + type fakeNeverRateLimiter struct { wg sync.WaitGroup } @@ -114,3 +128,7 @@ func (t *fakeNeverRateLimiter) Stop() { func (t *fakeNeverRateLimiter) Accept() { t.wg.Wait() } + +func (t *fakeNeverRateLimiter) QPS() float32 { + return 1 +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/flushwriter/doc.go b/vendor/k8s.io/kubernetes/pkg/util/flushwriter/doc.go index 485b9992651d..1e7e324a1540 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flushwriter/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flushwriter/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/flushwriter/writer.go b/vendor/k8s.io/kubernetes/pkg/util/flushwriter/writer.go index 0a9d88a7899e..748bd010856b 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/flushwriter/writer.go +++ b/vendor/k8s.io/kubernetes/pkg/util/flushwriter/writer.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/framer/framer.go b/vendor/k8s.io/kubernetes/pkg/util/framer/framer.go index 7ca806fa0547..066680f443e5 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/framer/framer.go +++ b/vendor/k8s.io/kubernetes/pkg/util/framer/framer.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go b/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go index fb8c125c5ba9..c00fe46823b5 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go +++ b/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/goroutinemap.go b/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/goroutinemap.go index 3ca5f6870198..c5f6884a0c9d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/goroutinemap.go +++ b/vendor/k8s.io/kubernetes/pkg/util/goroutinemap/goroutinemap.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,11 +36,11 @@ const ( // that GoRoutineMap will refuse to allow another operation to start with // the same operation name (if exponentialBackOffOnError is enabled). Each // successive error results in a wait 2x times the previous. - initialDurationBeforeRetry time.Duration = 500 * time.Millisecond + initialDurationBeforeRetry = 500 * time.Millisecond // maxDurationBeforeRetry is the maximum amount of time that // durationBeforeRetry will grow to due to exponential backoff. - maxDurationBeforeRetry time.Duration = 2 * time.Minute + maxDurationBeforeRetry = 2 * time.Minute ) // GoRoutineMap defines the supported set of operations. @@ -65,10 +65,9 @@ func NewGoRoutineMap(exponentialBackOffOnError bool) GoRoutineMap { g := &goRoutineMap{ operations: make(map[string]operation), exponentialBackOffOnError: exponentialBackOffOnError, - lock: &sync.Mutex{}, } - g.cond = sync.NewCond(g.lock) + g.cond = sync.NewCond(&g.lock) return g } @@ -76,7 +75,7 @@ type goRoutineMap struct { operations map[string]operation exponentialBackOffOnError bool cond *sync.Cond - lock *sync.Mutex + lock sync.Mutex } type operation struct { diff --git a/vendor/k8s.io/kubernetes/pkg/util/hash/hash.go b/vendor/k8s.io/kubernetes/pkg/util/hash/hash.go index 95fd32abe7dd..803f066a440b 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/hash/hash.go +++ b/vendor/k8s.io/kubernetes/pkg/util/hash/hash.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/homedir/homedir.go b/vendor/k8s.io/kubernetes/pkg/util/homedir/homedir.go index 57171e109bbd..403475491afe 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/homedir/homedir.go +++ b/vendor/k8s.io/kubernetes/pkg/util/homedir/homedir.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/httpstream/doc.go b/vendor/k8s.io/kubernetes/pkg/util/httpstream/doc.go index b474fc572ea2..1da83f14b18c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/httpstream/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/httpstream/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go b/vendor/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go index 3ce3b02a0198..7c9b791d4ff0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go +++ b/vendor/k8s.io/kubernetes/pkg/util/httpstream/httpstream.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go index 0330e2038172..da63a0298208 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go +++ b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/connection.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go index 6091c4e4b103..f8c6e36a586f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go +++ b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/roundtripper.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import ( apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/util/httpstream" - "k8s.io/kubernetes/third_party/golang/netutil" + "k8s.io/kubernetes/third_party/forked/golang/netutil" ) // SpdyRoundTripper knows how to upgrade an HTTP request to one that supports diff --git a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go index b7d126a5d82f..0ae4a15191ce 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go +++ b/vendor/k8s.io/kubernetes/pkg/util/httpstream/spdy/upgrade.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/integer/integer.go b/vendor/k8s.io/kubernetes/pkg/util/integer/integer.go index c51cd952d1d6..c6ea106f9b1e 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/integer/integer.go +++ b/vendor/k8s.io/kubernetes/pkg/util/integer/integer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,6 +30,20 @@ func IntMin(a, b int) int { return a } +func Int32Max(a, b int32) int32 { + if b > a { + return b + } + return a +} + +func Int32Min(a, b int32) int32 { + if b < a { + return b + } + return a +} + func Int64Max(a, b int64) int64 { if b > a { return b @@ -43,3 +57,11 @@ func Int64Min(a, b int64) int64 { } return a } + +// RoundToInt32 rounds floats into integer numbers. +func RoundToInt32(a float64) int32 { + if a < 0 { + return int32(a - 0.5) + } + return int32(a + 0.5) +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/interrupt/interrupt.go b/vendor/k8s.io/kubernetes/pkg/util/interrupt/interrupt.go new file mode 100644 index 000000000000..0265b9fb1712 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/interrupt/interrupt.go @@ -0,0 +1,104 @@ +/* +Copyright 2016 The Kubernetes 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 interrupt + +import ( + "os" + "os/signal" + "sync" + "syscall" +) + +// terminationSignals are signals that cause the program to exit in the +// supported platforms (linux, darwin, windows). +var terminationSignals = []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT} + +// Handler guarantees execution of notifications after a critical section (the function passed +// to a Run method), even in the presence of process termination. It guarantees exactly once +// invocation of the provided notify functions. +type Handler struct { + notify []func() + final func(os.Signal) + once sync.Once +} + +// Chain creates a new handler that invokes all notify functions when the critical section exits +// and then invokes the optional handler's notifications. This allows critical sections to be +// nested without losing exactly once invocations. Notify functions can invoke any cleanup needed +// but should not exit (which is the responsibility of the parent handler). +func Chain(handler *Handler, notify ...func()) *Handler { + if handler == nil { + return New(nil, notify...) + } + return New(handler.Signal, append(notify, handler.Close)...) +} + +// New creates a new handler that guarantees all notify functions are run after the critical +// section exits (or is interrupted by the OS), then invokes the final handler. If no final +// handler is specified, the default final is `os.Exit(1)`. A handler can only be used for +// one critical section. +func New(final func(os.Signal), notify ...func()) *Handler { + return &Handler{ + final: final, + notify: notify, + } +} + +// Close executes all the notification handlers if they have not yet been executed. +func (h *Handler) Close() { + h.once.Do(func() { + for _, fn := range h.notify { + fn() + } + }) +} + +// Signal is called when an os.Signal is received, and guarantees that all notifications +// are executed, then the final handler is executed. This function should only be called once +// per Handler instance. +func (h *Handler) Signal(s os.Signal) { + h.once.Do(func() { + for _, fn := range h.notify { + fn() + } + if h.final == nil { + os.Exit(1) + } + h.final(s) + }) +} + +// Run ensures that any notifications are invoked after the provided fn exits (even if the +// process is interrupted by an OS termination signal). Notifications are only invoked once +// per Handler instance, so calling Run more than once will not behave as the user expects. +func (h *Handler) Run(fn func() error) error { + ch := make(chan os.Signal, 1) + signal.Notify(ch, terminationSignals...) + defer func() { + signal.Stop(ch) + close(ch) + }() + go func() { + sig, ok := <-ch + if !ok { + return + } + h.Signal(sig) + }() + defer h.Close() + return fn() +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.pb.go index ef39cd58655b..3c2bf4fb1cf2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.proto b/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.proto index 32ad1b6b1bef..dd508e1c8fa2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/util/intstr/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ option go_package = "intstr"; // accept a name or number. // TODO: Rename to Int32OrString // -// +gencopy=true // +protobuf=true // +protobuf.options.(gogoproto.goproto_stringer)=false message IntOrString { diff --git a/vendor/k8s.io/kubernetes/pkg/util/intstr/intstr.go b/vendor/k8s.io/kubernetes/pkg/util/intstr/intstr.go index 53bc0fc7e627..59e7a0663364 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/intstr/intstr.go +++ b/vendor/k8s.io/kubernetes/pkg/util/intstr/intstr.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ import ( // accept a name or number. // TODO: Rename to Int32OrString // -// +gencopy=true // +protobuf=true // +protobuf.options.(gogoproto.goproto_stringer)=false type IntOrString struct { @@ -144,5 +143,5 @@ func getIntOrPercentValue(intOrStr *IntOrString) (int, bool, error) { } return int(v), true, nil } - return 0, false, fmt.Errorf("invalid value: neither int nor percentage") + return 0, false, fmt.Errorf("invalid type: neither int nor percentage") } diff --git a/vendor/k8s.io/kubernetes/pkg/util/io/io.go b/vendor/k8s.io/kubernetes/pkg/util/io/io.go index d600c08c191b..d7eb6d57f99b 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/io/io.go +++ b/vendor/k8s.io/kubernetes/pkg/util/io/io.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/io/writer.go b/vendor/k8s.io/kubernetes/pkg/util/io/writer.go index 3046c4d9b26e..086508c90d87 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/io/writer.go +++ b/vendor/k8s.io/kubernetes/pkg/util/io/writer.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/iptables/doc.go b/vendor/k8s.io/kubernetes/pkg/util/iptables/doc.go index 5824f3b4e32f..90d1b45b16a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/iptables/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/iptables/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/iptables/iptables.go b/vendor/k8s.io/kubernetes/pkg/util/iptables/iptables.go index 801cc8bf726b..3b9a00336cb7 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/iptables/iptables.go +++ b/vendor/k8s.io/kubernetes/pkg/util/iptables/iptables.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/iptables/save_restore.go b/vendor/k8s.io/kubernetes/pkg/util/iptables/save_restore.go index d86eb755ce71..435a54bebd4d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/iptables/save_restore.go +++ b/vendor/k8s.io/kubernetes/pkg/util/iptables/save_restore.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/json/json.go b/vendor/k8s.io/kubernetes/pkg/util/json/json.go index 1ff8cc0d4413..e8054a12ed76 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/json/json.go +++ b/vendor/k8s.io/kubernetes/pkg/util/json/json.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go b/vendor/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go index 2bcc95175923..fcffa99bfcce 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go +++ b/vendor/k8s.io/kubernetes/pkg/util/keymutex/keymutex.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/labels/doc.go b/vendor/k8s.io/kubernetes/pkg/util/labels/doc.go index 0746d878db50..c87305fb0914 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/labels/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/labels/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/labels/labels.go b/vendor/k8s.io/kubernetes/pkg/util/labels/labels.go index 624d5ad6886a..262f66e6e9d1 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/labels/labels.go +++ b/vendor/k8s.io/kubernetes/pkg/util/labels/labels.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/limitwriter/doc.go b/vendor/k8s.io/kubernetes/pkg/util/limitwriter/doc.go index 7daff9c079a6..84e693e16095 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/limitwriter/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/limitwriter/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go b/vendor/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go index 88890a9fa249..e4b374c4f32d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go +++ b/vendor/k8s.io/kubernetes/pkg/util/limitwriter/limitwriter.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/line_delimiter.go b/vendor/k8s.io/kubernetes/pkg/util/line_delimiter.go index b48478df8a70..9f64260c8625 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/line_delimiter.go +++ b/vendor/k8s.io/kubernetes/pkg/util/line_delimiter.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/logs.go b/vendor/k8s.io/kubernetes/pkg/util/logs.go index c79c4903d1b4..ea27f484f02d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/logs.go +++ b/vendor/k8s.io/kubernetes/pkg/util/logs.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/metrics/util.go b/vendor/k8s.io/kubernetes/pkg/util/metrics/util.go index ab74e35c463b..0fbc3ae08cb2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/metrics/util.go +++ b/vendor/k8s.io/kubernetes/pkg/util/metrics/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/doc.go b/vendor/k8s.io/kubernetes/pkg/util/mount/doc.go index 839c0a69a58f..0e225e0a1b57 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go b/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go index 115293813b50..3a9706cf3ced 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ func (f *FakeMounter) Mount(source string, target string, fstype string, options } f.MountPoints = append(f.MountPoints, MountPoint{Device: source, Path: target, Type: fstype}) - glog.V(5).Infof("Fake mounter: mouted %s to %s", source, target) + glog.V(5).Infof("Fake mounter: mounted %s to %s", source, target) f.Log = append(f.Log, FakeAction{Action: FakeActionMount, Target: target, Source: source, FSType: fstype}) return nil } @@ -93,7 +93,7 @@ func (f *FakeMounter) Unmount(target string) error { newMountpoints := []MountPoint{} for _, mp := range f.MountPoints { if mp.Path == target { - glog.V(5).Infof("Fake mounter: unmouted %s from %s", mp.Device, target) + glog.V(5).Infof("Fake mounter: unmounted %s from %s", mp.Device, target) // Don't copy it to newMountpoints continue } @@ -117,10 +117,26 @@ func (f *FakeMounter) IsLikelyNotMountPoint(file string) (bool, error) { for _, mp := range f.MountPoints { if mp.Path == file { - glog.V(5).Infof("isLikelyMountPoint for %s: monted %s, false", file, mp.Path) + glog.V(5).Infof("isLikelyMountPoint for %s: mounted %s, false", file, mp.Path) return false, nil } } glog.V(5).Infof("isLikelyMountPoint for %s: true", file) return true, nil } + +func (f *FakeMounter) DeviceOpened(pathname string) (bool, error) { + f.mutex.Lock() + defer f.mutex.Unlock() + + for _, mp := range f.MountPoints { + if mp.Device == pathname { + return true, nil + } + } + return false, nil +} + +func (f *FakeMounter) PathIsDevice(pathname string) (bool, error) { + return true, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go index 9c1d8d4f2658..69f39cf6943f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ limitations under the License. package mount import ( + "path/filepath" + "github.com/golang/glog" "k8s.io/kubernetes/pkg/util/exec" - "path/filepath" ) type Interface interface { @@ -37,6 +38,11 @@ type Interface interface { // IsLikelyNotMountPoint determines if a directory is a mountpoint. // It should return ErrNotExist when the directory does not exist. IsLikelyNotMountPoint(file string) (bool, error) + // DeviceOpened determines if the device is in use elsewhere + // on the system, i.e. still mounted. + DeviceOpened(pathname string) (bool, error) + // PathIsDevice determines if a path is a device. + PathIsDevice(pathname string) (bool, error) } // This represents a single line in /proc/mounts or /etc/fstab. diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go index 59e5f3341a2d..03a5ccae7559 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -172,6 +172,56 @@ func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { return true, nil } +// DeviceOpened checks if block device in use by calling Open with O_EXCL flag. +// Returns true if open returns errno EBUSY, and false if errno is nil. +// Returns an error if errno is any error other than EBUSY. +// Returns with error if pathname is not a device. +func (mounter *Mounter) DeviceOpened(pathname string) (bool, error) { + return exclusiveOpenFailsOnDevice(pathname) +} + +// PathIsDevice uses FileInfo returned from os.Stat to check if path refers +// to a device. +func (mounter *Mounter) PathIsDevice(pathname string) (bool, error) { + return pathIsDevice(pathname) +} + +func exclusiveOpenFailsOnDevice(pathname string) (bool, error) { + if isDevice, err := pathIsDevice(pathname); !isDevice { + return false, fmt.Errorf( + "PathIsDevice failed for path %q: %v", + pathname, + err) + } + fd, errno := syscall.Open(pathname, syscall.O_RDONLY|syscall.O_EXCL, 0) + // If the device is in use, open will return an invalid fd. + // When this happens, it is expected that Close will fail and throw an error. + defer syscall.Close(fd) + if errno == nil { + // device not in use + return false, nil + } else if errno == syscall.EBUSY { + // device is in use + return true, nil + } + // error during call to Open + return false, errno +} + +func pathIsDevice(pathname string) (bool, error) { + finfo, err := os.Stat(pathname) + // err in call to os.Stat + if err != nil { + return false, err + } + // path refers to a device + if finfo.Mode()&os.ModeDevice != 0 { + return true, nil + } + // path does not refer to device + return false, nil +} + func listProcMounts(mountFilePath string) ([]MountPoint, error) { hash1, err := readProcMounts(mountFilePath, nil) if err != nil { diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go index 8942c003635b..3e57ea8bad5c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,6 +36,14 @@ func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { return true, nil } +func (mounter *Mounter) DeviceOpened(pathname string) (bool, error) { + return false, nil +} + +func (mounter *Mounter) PathIsDevice(pathname string) (bool, error) { + return true, nil +} + func (mounter *SafeFormatAndMount) formatAndMount(source string, target string, fstype string, options []string) error { return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go index 9a64ae440bc2..ea2b945a7f25 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -203,6 +203,20 @@ func (n *NsenterMounter) IsLikelyNotMountPoint(file string) (bool, error) { return true, nil } +// DeviceOpened checks if block device in use by calling Open with O_EXCL flag. +// Returns true if open returns errno EBUSY, and false if errno is nil. +// Returns an error if errno is any error other than EBUSY. +// Returns with error if pathname is not a device. +func (n *NsenterMounter) DeviceOpened(pathname string) (bool, error) { + return exclusiveOpenFailsOnDevice(pathname) +} + +// PathIsDevice uses FileInfo returned from os.Stat to check if path refers +// to a device. +func (n *NsenterMounter) PathIsDevice(pathname string) (bool, error) { + return pathIsDevice(pathname) +} + func (n *NsenterMounter) absHostPath(command string) string { path, ok := n.paths[command] if !ok { diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go index 210fab851ab3..f40f73ab2d21 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -41,3 +41,11 @@ func (*NsenterMounter) List() ([]MountPoint, error) { func (*NsenterMounter) IsLikelyNotMountPoint(file string) (bool, error) { return true, nil } + +func (*NsenterMounter) DeviceOpened(pathname string) (bool, error) { + return false, nil +} + +func (*NsenterMounter) PathIsDevice(pathname string) (bool, error) { + return true, nil +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/http.go b/vendor/k8s.io/kubernetes/pkg/util/net/http.go index 68073776afb1..53f28dfca253 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/http.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/http.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/interface.go b/vendor/k8s.io/kubernetes/pkg/util/net/interface.go index cdf5ddb54a42..a1e53d2e436f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/interface.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/interface.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/port_range.go b/vendor/k8s.io/kubernetes/pkg/util/net/port_range.go index 527552571e04..6a50e6186da5 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/port_range.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/port_range.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -71,12 +71,17 @@ func (pr *PortRange) Set(value string) error { high, err = strconv.Atoi(value[hyphenIndex+1:]) } if err != nil { - return fmt.Errorf("unable to parse port range: %s", value) + return fmt.Errorf("unable to parse port range: %s: %v", value, err) + } + + if low > 65535 || high > 65535 { + return fmt.Errorf("the port range cannot be greater than 65535: %s", value) } if high < low { return fmt.Errorf("end port cannot be less than start port: %s", value) } + pr.Base = low pr.Size = 1 + high - low return nil diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/port_split.go b/vendor/k8s.io/kubernetes/pkg/util/net/port_split.go index be40eb75f4f6..29c985edc3ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/port_split.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/port_split.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go b/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go index db117f63ec5e..5b6fe933f1c0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/util.go b/vendor/k8s.io/kubernetes/pkg/util/net/util.go index 92d5d0b98d1c..1348f4deeb95 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/net/util.go +++ b/vendor/k8s.io/kubernetes/pkg/util/net/util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/node/node.go b/vendor/k8s.io/kubernetes/pkg/util/node/node.go index cbc062fc9708..5d25d7fea796 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/node/node.go +++ b/vendor/k8s.io/kubernetes/pkg/util/node/node.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,13 +17,17 @@ limitations under the License. package node import ( + "encoding/json" "fmt" "net" "os/exec" "strings" + "time" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" ) func GetHostname(hostnameOverride string) string { @@ -59,3 +63,42 @@ func GetNodeHostIP(node *api.Node) (net.IP, error) { } return nil, fmt.Errorf("host IP unknown; known addresses: %v", addresses) } + +// Helper function that builds a string identifier that is unique per failure-zone +// Returns empty-string for no zone +func GetZoneKey(node *api.Node) string { + labels := node.Labels + if labels == nil { + return "" + } + + region, _ := labels[unversioned.LabelZoneRegion] + failureDomain, _ := labels[unversioned.LabelZoneFailureDomain] + + if region == "" && failureDomain == "" { + return "" + } + + // We include the null character just in case region or failureDomain has a colon + // (We do assume there's no null characters in a region or failureDomain) + // As a nice side-benefit, the null character is not printed by fmt.Print or glog + return region + ":\x00:" + failureDomain +} + +// SetNodeCondition updates specific node condition with patch operation. +func SetNodeCondition(c clientset.Interface, node string, condition api.NodeCondition) error { + generatePatch := func(condition api.NodeCondition) ([]byte, error) { + raw, err := json.Marshal(&[]api.NodeCondition{condition}) + if err != nil { + return nil, err + } + return []byte(fmt.Sprintf(`{"status":{"conditions":%s}}`, raw)), nil + } + condition.LastHeartbeatTime = unversioned.NewTime(time.Now()) + patch, err := generatePatch(condition) + if err != nil { + return nil + } + _, err = c.Core().Nodes().PatchStatus(node, patch) + return err +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/oom/doc.go b/vendor/k8s.io/kubernetes/pkg/util/oom/doc.go index 539d6c43b291..9825a53f2a5a 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/oom/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/oom/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/oom/oom.go b/vendor/k8s.io/kubernetes/pkg/util/oom/oom.go index c6d563ab2323..a5b1ea0ffc61 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/oom/oom.go +++ b/vendor/k8s.io/kubernetes/pkg/util/oom/oom.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_fake.go b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_fake.go index bd0bf6f4558a..2712c5d0b8e2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_fake.go +++ b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_fake.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_linux.go b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_linux.go index c054682bdd7e..0bb8703874ea 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_linux.go @@ -1,7 +1,7 @@ // +build cgo,linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -76,6 +76,12 @@ func applyOOMScoreAdj(pid int, oomScoreAdj int) error { continue } if _, err := f.Write([]byte(value)); err != nil { + // we can ignore the return value of f.Close() here. + f.Close() + err = fmt.Errorf("failed to apply oom-score-adj to pid %d (%v)", pid, err) + continue + } + if err = f.Close(); err != nil { err = fmt.Errorf("failed to apply oom-score-adj to pid %d (%v)", pid, err) continue } diff --git a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go index 9c4473f7e093..063839d6b26d 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/oom/oom_unsupported.go @@ -1,7 +1,7 @@ // +build !cgo !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers.go b/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers.go index a02f18d3eb19..4e70cc682759 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers.go +++ b/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/pod/doc.go b/vendor/k8s.io/kubernetes/pkg/util/pod/doc.go index 3bad7d0b711d..d7a8ff226e8f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/pod/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/pod/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/pod/pod.go b/vendor/k8s.io/kubernetes/pkg/util/pod/pod.go index 9c57aaebbcab..e2286c7a0204 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/pod/pod.go +++ b/vendor/k8s.io/kubernetes/pkg/util/pod/pod.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/procfs/doc.go b/vendor/k8s.io/kubernetes/pkg/util/procfs/doc.go index d94e6687c1fe..2e99311d0289 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/procfs/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/procfs/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs.go b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs.go index d0c38bf21e75..11550b6674a7 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs.go +++ b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go index 8d16aa53cc93..ab480ed0e466 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go +++ b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_fake.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go index d3bf14f0c7b9..f75a839983e8 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go +++ b/vendor/k8s.io/kubernetes/pkg/util/procfs/procfs_interface.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/proxy/dial.go b/vendor/k8s.io/kubernetes/pkg/util/proxy/dial.go index 33cecb7ea1cf..bbc9ae61be93 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/proxy/dial.go +++ b/vendor/k8s.io/kubernetes/pkg/util/proxy/dial.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import ( "github.com/golang/glog" utilnet "k8s.io/kubernetes/pkg/util/net" - "k8s.io/kubernetes/third_party/golang/netutil" + "k8s.io/kubernetes/third_party/forked/golang/netutil" ) func DialURL(url *url.URL, transport http.RoundTripper) (net.Conn, error) { diff --git a/vendor/k8s.io/kubernetes/pkg/util/proxy/doc.go b/vendor/k8s.io/kubernetes/pkg/util/proxy/doc.go index 0d7519a0c5d5..06bb03f04e8f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/proxy/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/proxy/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/proxy/transport.go b/vendor/k8s.io/kubernetes/pkg/util/proxy/transport.go index 079670c0aa77..af12e3d5894c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/proxy/transport.go +++ b/vendor/k8s.io/kubernetes/pkg/util/proxy/transport.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/rand/rand.go b/vendor/k8s.io/kubernetes/pkg/util/rand/rand.go index f2647af337a9..134c15260503 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/rand/rand.go +++ b/vendor/k8s.io/kubernetes/pkg/util/rand/rand.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/replicaset/replicaset.go b/vendor/k8s.io/kubernetes/pkg/util/replicaset/replicaset.go index e5dd26517b85..0ac51203a5b1 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/replicaset/replicaset.go +++ b/vendor/k8s.io/kubernetes/pkg/util/replicaset/replicaset.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -108,3 +108,25 @@ func MatchingPodsFunc(rs *extensions.ReplicaSet) (func(api.Pod) bool, error) { return selector.Matches(podLabelsSelector) }, nil } + +// ReplicaSetIsInactive returns a condition that will be true when a replica set is inactive ie. +// it has zero running replicas. +func ReplicaSetIsInactive(c unversionedextensions.ExtensionsInterface, replicaSet *extensions.ReplicaSet) wait.ConditionFunc { + + // If we're given a ReplicaSet where the status lags the spec, it either means that the + // ReplicaSet is stale, or that the ReplicaSet manager hasn't noticed the update yet. + // Polling status.Replicas is not safe in the latter case. + desiredGeneration := replicaSet.Generation + + return func() (bool, error) { + rs, err := c.ReplicaSets(replicaSet.Namespace).Get(replicaSet.Name) + if err != nil { + return false, err + } + + return rs.Status.ObservedGeneration >= desiredGeneration && + rs.Spec.Replicas == 0 && + rs.Status.Replicas == 0 && + rs.Status.FullyLabeledReplicas == 0, nil + } +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/resource_container_linux.go b/vendor/k8s.io/kubernetes/pkg/util/resource_container_linux.go index 8d166045e040..a844e4c14532 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/resource_container_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/resource_container_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/resource_container_unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/resource_container_unsupported.go index a8ee51927b0c..ba861b0dfe49 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/resource_container_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/resource_container_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/runner.go b/vendor/k8s.io/kubernetes/pkg/util/runner.go index 60645cf0ec85..9e977ee1e987 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/runner.go +++ b/vendor/k8s.io/kubernetes/pkg/util/runner.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/runtime/runtime.go b/vendor/k8s.io/kubernetes/pkg/util/runtime/runtime.go index 641846a2d244..976de49d582e 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/runtime/runtime.go +++ b/vendor/k8s.io/kubernetes/pkg/util/runtime/runtime.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,19 +23,27 @@ import ( "github.com/golang/glog" ) -// For testing, bypass HandleCrash. -var ReallyCrash bool +var ( + // ReallyCrash controls the behavior of HandleCrash and now defaults + // true. It's still exposed so components can optionally set to false + // to restore prior behavior. + ReallyCrash = true +) // PanicHandlers is a list of functions which will be invoked when a panic happens. var PanicHandlers = []func(interface{}){logPanic} -//TODO search the public functions -// HandleCrash simply catches a crash and logs an error. Meant to be called via defer. -// Additional context-specific handlers can be provided, and will be called in case of panic +// HandleCrash simply catches a crash and logs an error. Meant to be called via +// defer. Additional context-specific handlers can be provided, and will be +// called in case of panic. HandleCrash actually crashes, after calling the +// handlers and logging the panic message. +// +// TODO: remove this function. We are switching to a world where it's safe for +// apiserver to panic, since it will be restarted by kubelet. At the beginning +// of the Kubernetes project, nothing was going to restart apiserver and so +// catching panics was important. But it's actually much simpler for montoring +// software if we just exit when an unexpected panic happens. func HandleCrash(additionalHandlers ...func(interface{})) { - if ReallyCrash { - return - } if r := recover(); r != nil { for _, fn := range PanicHandlers { fn(r) @@ -43,13 +51,17 @@ func HandleCrash(additionalHandlers ...func(interface{})) { for _, fn := range additionalHandlers { fn(r) } + if ReallyCrash { + // Actually proceed to panic. + panic(r) + } } } // logPanic logs the caller tree when a panic occurs. func logPanic(r interface{}) { callers := getCallers(r) - glog.Errorf("Recovered from panic: %#v (%v)\n%v", r, r, callers) + glog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers) } func getCallers(r interface{}) string { diff --git a/vendor/k8s.io/kubernetes/pkg/util/selinux/doc.go b/vendor/k8s.io/kubernetes/pkg/util/selinux/doc.go index 9b9901504465..c379043875a0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/selinux/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/selinux/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux.go b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux.go index 4343b78f5750..c8c42afbd8e9 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_linux.go b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_linux.go index 4a6214ad10d1..f3c720561a04 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_unsupported.go b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_unsupported.go index 4fc7496bfd88..22a2f1a94b98 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/util/selinux/selinux_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/byte.go b/vendor/k8s.io/kubernetes/pkg/util/sets/byte.go index fe1068cdfe08..45f5d4f67ffd 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/byte.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/byte.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/doc.go b/vendor/k8s.io/kubernetes/pkg/util/sets/doc.go index a27cb62f593d..c5e541621f40 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/empty.go b/vendor/k8s.io/kubernetes/pkg/util/sets/empty.go index 73ac74c14f0d..5654edd77302 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/empty.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/empty.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/int.go b/vendor/k8s.io/kubernetes/pkg/util/sets/int.go index e7a2b5db18f2..4b8c331b5392 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/int.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/int.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/int64.go b/vendor/k8s.io/kubernetes/pkg/util/sets/int64.go index f31da7750130..b6a97e70d865 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/int64.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/int64.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/string.go b/vendor/k8s.io/kubernetes/pkg/util/sets/string.go index 572aa915765c..2094b3205ea0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/string.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/string.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/slice/slice.go b/vendor/k8s.io/kubernetes/pkg/util/slice/slice.go index f32dbabcf41f..2e1d7ccb53c3 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/slice/slice.go +++ b/vendor/k8s.io/kubernetes/pkg/util/slice/slice.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/strategicpatch/patch.go b/vendor/k8s.io/kubernetes/pkg/util/strategicpatch/patch.go index 676713bc86af..18d80f9b8d62 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/strategicpatch/patch.go +++ b/vendor/k8s.io/kubernetes/pkg/util/strategicpatch/patch.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import ( "sort" "k8s.io/kubernetes/pkg/util/json" - forkedjson "k8s.io/kubernetes/third_party/forked/json" + forkedjson "k8s.io/kubernetes/third_party/forked/golang/json" "github.com/davecgh/go-spew/spew" "github.com/ghodss/yaml" diff --git a/vendor/k8s.io/kubernetes/pkg/util/string_flag.go b/vendor/k8s.io/kubernetes/pkg/util/string_flag.go index 4208bf5f6d07..9d6a00a15924 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/string_flag.go +++ b/vendor/k8s.io/kubernetes/pkg/util/string_flag.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/strings/escape.go b/vendor/k8s.io/kubernetes/pkg/util/strings/escape.go index d00207bf87da..ba7f8504b483 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/strings/escape.go +++ b/vendor/k8s.io/kubernetes/pkg/util/strings/escape.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/strings/strings.go b/vendor/k8s.io/kubernetes/pkg/util/strings/strings.go index db5abb45eefd..2bcb174afc78 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/strings/strings.go +++ b/vendor/k8s.io/kubernetes/pkg/util/strings/strings.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/sysctl/sysctl.go b/vendor/k8s.io/kubernetes/pkg/util/sysctl/sysctl.go index 9398a7ac31e0..bbf52736c197 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sysctl/sysctl.go +++ b/vendor/k8s.io/kubernetes/pkg/util/sysctl/sysctl.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/system/system_utils.go b/vendor/k8s.io/kubernetes/pkg/util/system/system_utils.go index 57576abebdec..e0998872bfd0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/system/system_utils.go +++ b/vendor/k8s.io/kubernetes/pkg/util/system/system_utils.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/template.go b/vendor/k8s.io/kubernetes/pkg/util/template.go index 1f9668533bb8..d09d7dc86743 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/template.go +++ b/vendor/k8s.io/kubernetes/pkg/util/template.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/term/resize.go b/vendor/k8s.io/kubernetes/pkg/util/term/resize.go new file mode 100644 index 000000000000..3d78c8664197 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/term/resize.go @@ -0,0 +1,144 @@ +/* +Copyright 2016 The Kubernetes 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 term + +import ( + "fmt" + + "github.com/docker/docker/pkg/term" + "k8s.io/kubernetes/pkg/util/runtime" +) + +// Size represents the width and height of a terminal. +type Size struct { + Width uint16 + Height uint16 +} + +// GetSize returns the current size of the user's terminal. If it isn't a terminal, +// nil is returned. +func (t TTY) GetSize() *Size { + outFd, isTerminal := term.GetFdInfo(t.Out) + if !isTerminal { + return nil + } + return GetSize(outFd) +} + +// GetSize returns the current size of the terminal associated with fd. +func GetSize(fd uintptr) *Size { + winsize, err := term.GetWinsize(fd) + if err != nil { + runtime.HandleError(fmt.Errorf("unable to get terminal size: %v", err)) + return nil + } + + return &Size{Width: winsize.Width, Height: winsize.Height} +} + +// MonitorSize monitors the terminal's size. It returns a TerminalSizeQueue primed with +// initialSizes, or nil if there's no TTY present. +func (t *TTY) MonitorSize(initialSizes ...*Size) TerminalSizeQueue { + outFd, isTerminal := term.GetFdInfo(t.Out) + if !isTerminal { + return nil + } + + t.sizeQueue = &sizeQueue{ + t: *t, + // make it buffered so we can send the initial terminal sizes without blocking, prior to starting + // the streaming below + resizeChan: make(chan Size, len(initialSizes)), + stopResizing: make(chan struct{}), + } + + t.sizeQueue.monitorSize(outFd, initialSizes...) + + return t.sizeQueue +} + +// TerminalSizeQueue is capable of returning terminal resize events as they occur. +type TerminalSizeQueue interface { + // Next returns the new terminal size after the terminal has been resized. It returns nil when + // monitoring has been stopped. + Next() *Size +} + +// sizeQueue implements TerminalSizeQueue +type sizeQueue struct { + t TTY + // resizeChan receives a Size each time the user's terminal is resized. + resizeChan chan Size + stopResizing chan struct{} +} + +// make sure sizeQueue implements the TerminalSizeQueue interface +var _ TerminalSizeQueue = &sizeQueue{} + +// monitorSize primes resizeChan with initialSizes and then monitors for resize events. With each +// new event, it sends the current terminal size to resizeChan. +func (s *sizeQueue) monitorSize(outFd uintptr, initialSizes ...*Size) { + // send the initial sizes + for i := range initialSizes { + if initialSizes[i] != nil { + s.resizeChan <- *initialSizes[i] + } + } + + resizeEvents := make(chan Size, 1) + + monitorResizeEvents(outFd, resizeEvents, s.stopResizing) + + // listen for resize events in the background + go func() { + defer runtime.HandleCrash() + + for { + select { + case size, ok := <-resizeEvents: + if !ok { + return + } + + select { + // try to send the size to resizeChan, but don't block + case s.resizeChan <- size: + // send successful + default: + // unable to send / no-op + } + case <-s.stopResizing: + return + } + } + }() +} + +// Next returns the new terminal size after the terminal has been resized. It returns nil when +// monitoring has been stopped. +func (s *sizeQueue) Next() *Size { + size, ok := <-s.resizeChan + if !ok { + return nil + } + return &size +} + +// stop stops the background goroutine that is monitoring for terminal resizes. +func (s *sizeQueue) stop() { + close(s.stopResizing) +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents.go b/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents.go new file mode 100644 index 000000000000..70858ed03f0d --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents.go @@ -0,0 +1,60 @@ +// +build !windows + +/* +Copyright 2016 The Kubernetes 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 term + +import ( + "os" + "os/signal" + "syscall" + + "k8s.io/kubernetes/pkg/util/runtime" +) + +// monitorResizeEvents spawns a goroutine that waits for SIGWINCH signals (these indicate the +// terminal has resized). After receiving a SIGWINCH, this gets the terminal size and tries to send +// it to the resizeEvents channel. The goroutine stops when the stop channel is closed. +func monitorResizeEvents(fd uintptr, resizeEvents chan<- Size, stop chan struct{}) { + go func() { + defer runtime.HandleCrash() + + winch := make(chan os.Signal, 1) + signal.Notify(winch, syscall.SIGWINCH) + defer signal.Stop(winch) + + for { + select { + case <-winch: + size := GetSize(fd) + if size == nil { + return + } + + // try to send size + select { + case resizeEvents <- *size: + // success + default: + // not sent + } + case <-stop: + return + } + } + }() +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents_windows.go b/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents_windows.go new file mode 100644 index 000000000000..e994d28da314 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/term/resizeevents_windows.go @@ -0,0 +1,61 @@ +/* +Copyright 2016 The Kubernetes 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 term + +import ( + "time" + + "k8s.io/kubernetes/pkg/util/runtime" +) + +// monitorResizeEvents spawns a goroutine that periodically gets the terminal size and tries to send +// it to the resizeEvents channel if the size has changed. The goroutine stops when the stop channel +// is closed. +func monitorResizeEvents(fd uintptr, resizeEvents chan<- Size, stop chan struct{}) { + go func() { + defer runtime.HandleCrash() + + size := GetSize(fd) + if size == nil { + return + } + lastSize := *size + + for { + // see if we need to stop running + select { + case <-stop: + return + default: + } + + size := GetSize(fd) + if size == nil { + return + } + + if size.Height != lastSize.Height || size.Width != lastSize.Width { + lastSize.Height = size.Height + lastSize.Width = size.Width + resizeEvents <- *size + } + + // sleep to avoid hot looping + time.Sleep(250 * time.Millisecond) + } + }() +} diff --git a/vendor/k8s.io/kubernetes/pkg/api/resource/deep_copy.go b/vendor/k8s.io/kubernetes/pkg/util/term/setsize.go similarity index 61% rename from vendor/k8s.io/kubernetes/pkg/api/resource/deep_copy.go rename to vendor/k8s.io/kubernetes/pkg/util/term/setsize.go index 4efc0406f0d1..944d4e5ab671 100644 --- a/vendor/k8s.io/kubernetes/pkg/api/resource/deep_copy.go +++ b/vendor/k8s.io/kubernetes/pkg/util/term/setsize.go @@ -1,5 +1,7 @@ +// +build !windows + /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,19 +16,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -package resource +package term import ( - inf "gopkg.in/inf.v0" - - conversion "k8s.io/kubernetes/pkg/conversion" + "github.com/docker/docker/pkg/term" ) -func DeepCopy_resource_Quantity(in Quantity, out *Quantity, c *conversion.Cloner) error { - *out = in - if in.d.Dec != nil { - tmp := &inf.Dec{} - out.d.Dec = tmp.Set(in.d.Dec) - } - return nil +// SetSize sets the terminal size associated with fd. +func SetSize(fd uintptr, size Size) error { + return term.SetWinsize(fd, &term.Winsize{Height: size.Height, Width: size.Width}) } diff --git a/vendor/k8s.io/kubernetes/pkg/util/intstr/deep_copy_generated.go b/vendor/k8s.io/kubernetes/pkg/util/term/setsize_unsupported.go similarity index 57% rename from vendor/k8s.io/kubernetes/pkg/util/intstr/deep_copy_generated.go rename to vendor/k8s.io/kubernetes/pkg/util/term/setsize_unsupported.go index 29aef022349d..dd3de3126b3f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/intstr/deep_copy_generated.go +++ b/vendor/k8s.io/kubernetes/pkg/util/term/setsize_unsupported.go @@ -1,7 +1,7 @@ -// +build !ignore_autogenerated +// +build windows /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,17 +16,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -// This file was autogenerated by deepcopy-gen. Do not edit it manually! +package term -package intstr - -import ( - conversion "k8s.io/kubernetes/pkg/conversion" -) - -func DeepCopy_intstr_IntOrString(in IntOrString, out *IntOrString, c *conversion.Cloner) error { - out.Type = in.Type - out.IntVal = in.IntVal - out.StrVal = in.StrVal +func SetSize(fd uintptr, size Size) error { + // NOP return nil } diff --git a/vendor/k8s.io/kubernetes/pkg/util/term/term.go b/vendor/k8s.io/kubernetes/pkg/util/term/term.go new file mode 100644 index 000000000000..58baee8310d4 --- /dev/null +++ b/vendor/k8s.io/kubernetes/pkg/util/term/term.go @@ -0,0 +1,110 @@ +/* +Copyright 2016 The Kubernetes 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 term + +import ( + "io" + "os" + + "github.com/docker/docker/pkg/term" + + "k8s.io/kubernetes/pkg/util/interrupt" +) + +// SafeFunc is a function to be invoked by TTY. +type SafeFunc func() error + +// TTY helps invoke a function and preserve the state of the terminal, even if the process is +// terminated during execution. It also provides support for terminal resizing for remote command +// execution/attachment. +type TTY struct { + // In is a reader representing stdin. It is a required field. + In io.Reader + // Out is a writer representing stdout. It must be set to support terminal resizing. It is an + // optional field. + Out io.Writer + // Raw is true if the terminal should be set raw. + Raw bool + // TryDev indicates the TTY should try to open /dev/tty if the provided input + // is not a file descriptor. + TryDev bool + // Parent is an optional interrupt handler provided to this function - if provided + // it will be invoked after the terminal state is restored. If it is not provided, + // a signal received during the TTY will result in os.Exit(0) being invoked. + Parent *interrupt.Handler + + // sizeQueue is set after a call to MonitorSize() and is used to monitor SIGWINCH signals when the + // user's terminal resizes. + sizeQueue *sizeQueue +} + +// IsTerminalIn returns true if t.In is a terminal. Does not check /dev/tty +// even if TryDev is set. +func (t TTY) IsTerminalIn() bool { + return IsTerminal(t.In) +} + +// IsTerminalOut returns true if t.Out is a terminal. Does not check /dev/tty +// even if TryDev is set. +func (t TTY) IsTerminalOut() bool { + return IsTerminal(t.Out) +} + +// IsTerminal returns whether the passed object is a terminal or not +func IsTerminal(i interface{}) bool { + _, terminal := term.GetFdInfo(i) + return terminal +} + +// Safe invokes the provided function and will attempt to ensure that when the +// function returns (or a termination signal is sent) that the terminal state +// is reset to the condition it was in prior to the function being invoked. If +// t.Raw is true the terminal will be put into raw mode prior to calling the function. +// If the input file descriptor is not a TTY and TryDev is true, the /dev/tty file +// will be opened (if available). +func (t TTY) Safe(fn SafeFunc) error { + inFd, isTerminal := term.GetFdInfo(t.In) + + if !isTerminal && t.TryDev { + if f, err := os.Open("/dev/tty"); err == nil { + defer f.Close() + inFd = f.Fd() + isTerminal = term.IsTerminal(inFd) + } + } + if !isTerminal { + return fn() + } + + var state *term.State + var err error + if t.Raw { + state, err = term.MakeRaw(inFd) + } else { + state, err = term.SaveState(inFd) + } + if err != nil { + return err + } + return interrupt.Chain(t.Parent, func() { + if t.sizeQueue != nil { + t.sizeQueue.stop() + } + + term.RestoreTerminal(inFd, state) + }).Run(fn) +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/trace.go b/vendor/k8s.io/kubernetes/pkg/util/trace.go index ed9da94b3284..fe93db8df6f4 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/trace.go +++ b/vendor/k8s.io/kubernetes/pkg/util/trace.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/umask.go b/vendor/k8s.io/kubernetes/pkg/util/umask.go index 48311f4e337b..35ccce50bd57 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/umask.go +++ b/vendor/k8s.io/kubernetes/pkg/util/umask.go @@ -1,7 +1,7 @@ // +build !windows /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/umask_windows.go b/vendor/k8s.io/kubernetes/pkg/util/umask_windows.go index 0f97c26edb37..8c1b2cbc7d5f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/umask_windows.go +++ b/vendor/k8s.io/kubernetes/pkg/util/umask_windows.go @@ -1,7 +1,7 @@ // +build windows /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/util.go b/vendor/k8s.io/kubernetes/pkg/util/util.go index 4826a448b144..7a9414957849 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/util.go +++ b/vendor/k8s.io/kubernetes/pkg/util/util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/uuid.go b/vendor/k8s.io/kubernetes/pkg/util/uuid.go index 7e1396f12893..23abe1156997 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/uuid.go +++ b/vendor/k8s.io/kubernetes/pkg/util/uuid.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/validation/field/errors.go b/vendor/k8s.io/kubernetes/pkg/util/validation/field/errors.go index 203f7cc8f5cb..b4a6c5cd5985 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/validation/field/errors.go +++ b/vendor/k8s.io/kubernetes/pkg/util/validation/field/errors.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/validation/field/path.go b/vendor/k8s.io/kubernetes/pkg/util/validation/field/path.go index 30ff5a8f788a..2efc8eec76d9 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/validation/field/path.go +++ b/vendor/k8s.io/kubernetes/pkg/util/validation/field/path.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/util/validation/validation.go index 9361a4bfacb9..6e6a0270ca46 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/util/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -85,10 +85,10 @@ func IsValidLabelValue(value string) []string { return errs } -const DNS1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" +const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" const DNS1123LabelMaxLength int = 63 -var dns1123LabelRegexp = regexp.MustCompile("^" + DNS1123LabelFmt + "$") +var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$") // IsDNS1123Label tests for a string that conforms to the definition of a label in // DNS (RFC 1123). @@ -98,15 +98,15 @@ func IsDNS1123Label(value string) []string { errs = append(errs, MaxLenError(DNS1123LabelMaxLength)) } if !dns1123LabelRegexp.MatchString(value) { - errs = append(errs, RegexError(DNS1123LabelFmt, "my-name", "123-abc")) + errs = append(errs, RegexError(dns1123LabelFmt, "my-name", "123-abc")) } return errs } -const DNS1123SubdomainFmt string = DNS1123LabelFmt + "(\\." + DNS1123LabelFmt + ")*" +const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*" const DNS1123SubdomainMaxLength int = 253 -var dns1123SubdomainRegexp = regexp.MustCompile("^" + DNS1123SubdomainFmt + "$") +var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$") // IsDNS1123Subdomain tests for a string that conforms to the definition of a // subdomain in DNS (RFC 1123). @@ -116,15 +116,15 @@ func IsDNS1123Subdomain(value string) []string { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !dns1123SubdomainRegexp.MatchString(value) { - errs = append(errs, RegexError(DNS1123SubdomainFmt, "example.com")) + errs = append(errs, RegexError(dns1123SubdomainFmt, "example.com")) } return errs } -const DNS952LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?" +const dns952LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?" const DNS952LabelMaxLength int = 24 -var dns952LabelRegexp = regexp.MustCompile("^" + DNS952LabelFmt + "$") +var dns952LabelRegexp = regexp.MustCompile("^" + dns952LabelFmt + "$") // IsDNS952Label tests for a string that conforms to the definition of a label in // DNS (RFC 952). @@ -134,24 +134,30 @@ func IsDNS952Label(value string) []string { errs = append(errs, MaxLenError(DNS952LabelMaxLength)) } if !dns952LabelRegexp.MatchString(value) { - errs = append(errs, RegexError(DNS952LabelFmt, "my-name", "abc-123")) + errs = append(errs, RegexError(dns952LabelFmt, "my-name", "abc-123")) } return errs } -const CIdentifierFmt string = "[A-Za-z_][A-Za-z0-9_]*" +const cIdentifierFmt string = "[A-Za-z_][A-Za-z0-9_]*" -var cIdentifierRegexp = regexp.MustCompile("^" + CIdentifierFmt + "$") +var cIdentifierRegexp = regexp.MustCompile("^" + cIdentifierFmt + "$") // IsCIdentifier tests for a string that conforms the definition of an identifier // in C. This checks the format, but not the length. -func IsCIdentifier(value string) bool { - return cIdentifierRegexp.MatchString(value) +func IsCIdentifier(value string) []string { + if !cIdentifierRegexp.MatchString(value) { + return []string{RegexError(cIdentifierFmt, "my_name", "MY_NAME", "MyName")} + } + return nil } // IsValidPortNum tests that the argument is a valid, non-zero port number. -func IsValidPortNum(port int) bool { - return 0 < port && port < 65536 +func IsValidPortNum(port int) []string { + if 1 <= port && port <= 65535 { + return nil + } + return []string{InclusiveRangeError(1, 65535)} } // Now in libcontainer UID/GID limits is 0 ~ 1<<31 - 1 @@ -163,67 +169,99 @@ const ( maxGroupID = math.MaxInt32 ) -// IsValidGroupId tests that the argument is a valid gids. -func IsValidGroupId(gid int64) bool { - return minGroupID <= gid && gid <= maxGroupID +// IsValidGroupId tests that the argument is a valid Unix GID. +func IsValidGroupId(gid int64) []string { + if minGroupID <= gid && gid <= maxGroupID { + return nil + } + return []string{InclusiveRangeError(minGroupID, maxGroupID)} } -// IsValidUserId tests that the argument is a valid uids. -func IsValidUserId(uid int64) bool { - return minUserID <= uid && uid <= maxUserID +// IsValidUserId tests that the argument is a valid Unix UID. +func IsValidUserId(uid int64) []string { + if minUserID <= uid && uid <= maxUserID { + return nil + } + return []string{InclusiveRangeError(minUserID, maxUserID)} } -const doubleHyphensFmt string = ".*(--).*" - -var doubleHyphensRegexp = regexp.MustCompile("^" + doubleHyphensFmt + "$") - -const IdentifierNoHyphensBeginEndFmt string = "[a-z0-9]([a-z0-9-]*[a-z0-9])*" - -var identifierNoHyphensBeginEndRegexp = regexp.MustCompile("^" + IdentifierNoHyphensBeginEndFmt + "$") - -const atLeastOneLetterFmt string = ".*[a-z].*" - -var atLeastOneLetterRegexp = regexp.MustCompile("^" + atLeastOneLetterFmt + "$") - -// IsValidPortName check that the argument is valid syntax. It must be non empty and no more than 15 characters long -// It must contains at least one letter [a-z] and it must contains only [a-z0-9-]. -// Hypens ('-') cannot be leading or trailing character of the string and cannot be adjacent to other hyphens. -// Although RFC 6335 allows upper and lower case characters but case is ignored for comparison purposes: (HTTP -// and http denote the same service). -func IsValidPortName(port string) bool { - if len(port) < 1 || len(port) > 15 { - return false +var portNameCharsetRegex = regexp.MustCompile("^[-a-z0-9]+$") +var portNameOneLetterRegexp = regexp.MustCompile("[a-z]") + +// IsValidPortName check that the argument is valid syntax. It must be +// non-empty and no more than 15 characters long. It may contain only [-a-z0-9] +// and must contain at least one letter [a-z]. It must not start or end with a +// hyphen, nor contain adjacent hyphens. +// +// Note: We only allow lower-case characters, even though RFC 6335 is case +// insensitive. +func IsValidPortName(port string) []string { + var errs []string + if len(port) > 15 { + errs = append(errs, MaxLenError(15)) + } + if !portNameCharsetRegex.MatchString(port) { + errs = append(errs, "must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)") } - if doubleHyphensRegexp.MatchString(port) { - return false + if !portNameOneLetterRegexp.MatchString(port) { + errs = append(errs, "must contain at least one letter (a-z)") } - if identifierNoHyphensBeginEndRegexp.MatchString(port) && atLeastOneLetterRegexp.MatchString(port) { - return true + if strings.Contains(port, "--") { + errs = append(errs, "must not contain consecutive hyphens") } - return false + if len(port) > 0 && (port[0] == '-' || port[len(port)-1] == '-') { + errs = append(errs, "must not begin or end with a hyphen") + } + return errs } // IsValidIP tests that the argument is a valid IP address. -func IsValidIP(value string) bool { - return net.ParseIP(value) != nil +func IsValidIP(value string) []string { + if net.ParseIP(value) == nil { + return []string{"must be a valid IP address, (e.g. 10.9.8.7)"} + } + return nil } const percentFmt string = "[0-9]+%" var percentRegexp = regexp.MustCompile("^" + percentFmt + "$") -func IsValidPercent(percent string) bool { - return percentRegexp.MatchString(percent) +func IsValidPercent(percent string) []string { + if !percentRegexp.MatchString(percent) { + return []string{RegexError(percentFmt, "1%", "93%")} + } + return nil } -const HTTPHeaderNameFmt string = "[-A-Za-z0-9]+" +const httpHeaderNameFmt string = "[-A-Za-z0-9]+" -var httpHeaderNameRegexp = regexp.MustCompile("^" + HTTPHeaderNameFmt + "$") +var httpHeaderNameRegexp = regexp.MustCompile("^" + httpHeaderNameFmt + "$") // IsHTTPHeaderName checks that a string conforms to the Go HTTP library's // definition of a valid header field name (a stricter subset than RFC7230). -func IsHTTPHeaderName(value string) bool { - return httpHeaderNameRegexp.MatchString(value) +func IsHTTPHeaderName(value string) []string { + if !httpHeaderNameRegexp.MatchString(value) { + return []string{RegexError(httpHeaderNameFmt, "X-Header-Name")} + } + return nil +} + +const configMapKeyFmt = "\\.?" + dns1123SubdomainFmt + +var configMapKeyRegexp = regexp.MustCompile("^" + configMapKeyFmt + "$") + +// IsConfigMapKey tests for a string that conforms to the definition of a +// subdomain in DNS (RFC 1123), except that a leading dot is allowed +func IsConfigMapKey(value string) []string { + var errs []string + if len(value) > DNS1123SubdomainMaxLength { + errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) + } + if !configMapKeyRegexp.MatchString(value) { + errs = append(errs, RegexError(configMapKeyFmt, "key.name")) + } + return errs } // MaxLenError returns a string explanation of a "string too long" validation @@ -260,3 +298,9 @@ func prefixEach(msgs []string, prefix string) []string { } return msgs } + +// InclusiveRangeError returns a string explanation of a numeric "must be +// between" validation failure. +func InclusiveRangeError(lo, hi int) string { + return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi) +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/wait/doc.go b/vendor/k8s.io/kubernetes/pkg/util/wait/doc.go index 240397a221eb..ff89dc170e86 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/wait/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/wait/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/wait/wait.go b/vendor/k8s.io/kubernetes/pkg/util/wait/wait.go index b56560e75c27..517577c8c8ba 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/wait/wait.go +++ b/vendor/k8s.io/kubernetes/pkg/util/wait/wait.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,8 +20,6 @@ import ( "errors" "math/rand" "time" - - "k8s.io/kubernetes/pkg/util/runtime" ) // For any test of the style: @@ -64,13 +62,14 @@ func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) { // stop channel is already closed. Pass NeverStop to Until if you // don't want it stop. func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) { - select { - case <-stopCh: - return - default: - } - for { + + select { + case <-stopCh: + return + default: + } + jitteredPeriod := period if jitterFactor > 0.0 { jitteredPeriod = Jitter(period, jitterFactor) @@ -82,22 +81,18 @@ func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding b } func() { - defer runtime.HandleCrash() f() }() if sliding { t = time.NewTimer(jitteredPeriod) - } else { - // The timer we created could already have fired, so be - // careful and check stopCh first. - select { - case <-stopCh: - return - default: - } } + // NOTE: b/c there is no priority selection in golang + // it is possible for this to race, meaning we could + // trigger t.C and stopCh, and t.C select falls through. + // In order to mitigate we re-check stopCh at the beginning + // of every loop to prevent extra executions of f(). select { case <-stopCh: return diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/default_rate_limiters.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/default_rate_limiters.go index 6ca484b62cba..cf3c4d94eac0 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/default_rate_limiters.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/default_rate_limiters.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/delaying_queue.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/delaying_queue.go index 429d15c4a1e8..a9aae96aa594 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/delaying_queue.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/delaying_queue.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import ( "sort" "time" - "k8s.io/kubernetes/pkg/util" + "k8s.io/kubernetes/pkg/util/clock" utilruntime "k8s.io/kubernetes/pkg/util/runtime" ) @@ -34,16 +34,17 @@ type DelayingInterface interface { // NewDelayingQueue constructs a new workqueue with delayed queuing ability func NewDelayingQueue() DelayingInterface { - return newDelayingQueue(util.RealClock{}) + return newDelayingQueue(clock.RealClock{}) } -func newDelayingQueue(clock util.Clock) DelayingInterface { +func newDelayingQueue(clock clock.Clock) DelayingInterface { ret := &delayingType{ - Interface: New(), - clock: clock, - heartbeat: clock.Tick(maxWait), - stopCh: make(chan struct{}), - waitingForAddCh: make(chan waitFor, 1000), + Interface: New(), + clock: clock, + heartbeat: clock.Tick(maxWait), + stopCh: make(chan struct{}), + waitingTimeByEntry: map[t]time.Time{}, + waitingForAddCh: make(chan waitFor, 1000), } go ret.waitingLoop() @@ -56,7 +57,7 @@ type delayingType struct { Interface // clock tracks time for delayed firing - clock util.Clock + clock clock.Clock // stopCh lets us signal a shutdown to the waiting loop stopCh chan struct{} @@ -66,6 +67,8 @@ type delayingType struct { // waitingForAdd is an ordered slice of items to be added to the contained work queue waitingForAdd []waitFor + // waitingTimeByEntry holds wait time by entry, so we can lookup pre-existing indexes + waitingTimeByEntry map[t]time.Time // waitingForAddCh is a buffered channel that feeds waitingForAdd waitingForAddCh chan waitFor } @@ -118,6 +121,7 @@ func (q *delayingType) waitingLoop() { if q.Interface.ShuttingDown() { // discard waiting entries q.waitingForAdd = nil + q.waitingTimeByEntry = nil return } @@ -130,6 +134,7 @@ func (q *delayingType) waitingLoop() { break } q.Add(entry.data) + delete(q.waitingTimeByEntry, entry.data) readyEntries++ } q.waitingForAdd = q.waitingForAdd[readyEntries:] @@ -152,7 +157,7 @@ func (q *delayingType) waitingLoop() { case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { - q.waitingForAdd = insert(q.waitingForAdd, waitEntry) + q.waitingForAdd = insert(q.waitingForAdd, q.waitingTimeByEntry, waitEntry) } else { q.Add(waitEntry.data) } @@ -162,7 +167,7 @@ func (q *delayingType) waitingLoop() { select { case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { - q.waitingForAdd = insert(q.waitingForAdd, waitEntry) + q.waitingForAdd = insert(q.waitingForAdd, q.waitingTimeByEntry, waitEntry) } else { q.Add(waitEntry.data) } @@ -177,7 +182,20 @@ func (q *delayingType) waitingLoop() { // inserts the given entry into the sorted entries list // same semantics as append()... the given slice may be modified, // and the returned value should be used -func insert(entries []waitFor, entry waitFor) []waitFor { +func insert(entries []waitFor, knownEntries map[t]time.Time, entry waitFor) []waitFor { + // if the entry is already in our retry list and the existing time is before the new one, just skip it + existingTime, exists := knownEntries[entry.data] + if exists && existingTime.Before(entry.readyAt) { + return entries + } + + // if the entry exists and is scheduled for later, go ahead and remove the entry + if exists { + if existingIndex := findEntryIndex(entries, existingTime, entry.data); existingIndex >= 0 && existingIndex < len(entries) { + entries = append(entries[:existingIndex], entries[existingIndex+1:]...) + } + } + insertionIndex := sort.Search(len(entries), func(i int) bool { return entry.readyAt.Before(entries[i].readyAt) }) @@ -189,5 +207,24 @@ func insert(entries []waitFor, entry waitFor) []waitFor { // insert the record entries[insertionIndex] = entry + knownEntries[entry.data] = entry.readyAt + return entries } + +// findEntryIndex returns the index for an existing entry +func findEntryIndex(entries []waitFor, existingTime time.Time, data t) int { + index := sort.Search(len(entries), func(i int) bool { + return entries[i].readyAt.After(existingTime) || existingTime == entries[i].readyAt + }) + + // we know this is the earliest possible index, but there could be multiple with the same time + // iterate from here to find the dupe + for ; index < len(entries); index++ { + if entries[index].data == data { + break + } + } + + return index +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/doc.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/doc.go index d53d36d9f2d9..2a00c74ac5f5 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/parallelizer.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/parallelizer.go index 9b773d538856..a9305935bb22 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/parallelizer.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/parallelizer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/queue.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/queue.go index 40f2ba2fa7a0..63fdd81910c6 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/queue.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/queue.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/workqueue/rate_limitting_queue.go b/vendor/k8s.io/kubernetes/pkg/util/workqueue/rate_limitting_queue.go index 272ba52d9e3d..a4f86eb10ae4 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/workqueue/rate_limitting_queue.go +++ b/vendor/k8s.io/kubernetes/pkg/util/workqueue/rate_limitting_queue.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/wsstream/conn.go b/vendor/k8s.io/kubernetes/pkg/util/wsstream/conn.go index 84e619671687..eb0b4b28bb13 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/wsstream/conn.go +++ b/vendor/k8s.io/kubernetes/pkg/util/wsstream/conn.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/wsstream/doc.go b/vendor/k8s.io/kubernetes/pkg/util/wsstream/doc.go index e94e8b271cd7..e5770acfb0d8 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/wsstream/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/util/wsstream/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/wsstream/stream.go b/vendor/k8s.io/kubernetes/pkg/util/wsstream/stream.go index 034c1216e02d..d16d99817e31 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/wsstream/stream.go +++ b/vendor/k8s.io/kubernetes/pkg/util/wsstream/stream.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder.go b/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder.go index a48a6ce864d2..6a9f05a58744 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder.go +++ b/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/version/base.go b/vendor/k8s.io/kubernetes/pkg/version/base.go index fab882195168..c377705fe8f1 100644 --- a/vendor/k8s.io/kubernetes/pkg/version/base.go +++ b/vendor/k8s.io/kubernetes/pkg/version/base.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -39,10 +39,10 @@ var ( // them irrelevant. (Next we'll take it out, which may muck with // scripts consuming the kubectl version output - but most of // these should be looking at gitVersion already anyways.) - gitMajor string = "1" // major version, always numeric - gitMinor string = "3" // minor version, numeric possibly followed by "+" + gitMajor string = "" // major version, always numeric + gitMinor string = "" // minor version, numeric possibly followed by "+" - // semantic version, dervied by build scripts (see + // semantic version, derived by build scripts (see // https://github.com/kubernetes/kubernetes/blob/master/docs/design/versioning.md // for a detailed discussion of this field) // @@ -51,7 +51,7 @@ var ( // semantic version is a git hash, but the version itself is no // longer the direct output of "git describe", but a slight // translation to be semver compliant. - gitVersion string = "v1.3.5+$Format:%h$" + gitVersion string = "v0.0.0-master+$Format:%h$" gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" diff --git a/vendor/k8s.io/kubernetes/pkg/version/doc.go b/vendor/k8s.io/kubernetes/pkg/version/doc.go index c0397829d45c..ccedec76f619 100644 --- a/vendor/k8s.io/kubernetes/pkg/version/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/version/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/version/semver.go b/vendor/k8s.io/kubernetes/pkg/version/semver.go index 1b5a845ad28b..1f4067e217bb 100644 --- a/vendor/k8s.io/kubernetes/pkg/version/semver.go +++ b/vendor/k8s.io/kubernetes/pkg/version/semver.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/version/version.go b/vendor/k8s.io/kubernetes/pkg/version/version.go index b8ac0d6c35f3..1e931321773a 100644 --- a/vendor/k8s.io/kubernetes/pkg/version/version.go +++ b/vendor/k8s.io/kubernetes/pkg/version/version.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/attacher.go b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/attacher.go index 9b254655e622..e4a710e08f8b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/attacher.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/attacher.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs.go b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs.go index fba3ed1f03c5..b2831da3a577 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_util.go b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_util.go index 76ebe72adc5a..723d15c33756 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -116,6 +116,12 @@ func verifyDevicePath(devicePaths []string) (string, error) { // Unmount the global mount path, which should be the only one, and delete it. func unmountPDAndRemoveGlobalPath(globalMountPath string, mounter mount.Interface) error { + if pathExists, pathErr := pathExists(globalMountPath); pathErr != nil { + return fmt.Errorf("Error checking if path exists: %v", pathErr) + } else if !pathExists { + glog.V(5).Infof("Warning: Unmount skipped because path does not exist: %v", globalMountPath) + return nil + } err := mounter.Unmount(globalMountPath) os.Remove(globalMountPath) return err diff --git a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/doc.go index 09c41729f250..8632d39c4e55 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_file.go b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_file.go index 24e5ce27a5c6..9201abb16ac8 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_file.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_file.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_util.go b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_util.go index 5d068c2c844c..12ee098a0925 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/azure_util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/doc.go index 119e45790185..91fe54372e5b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/azure_file/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/azure_file/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cephfs/cephfs.go b/vendor/k8s.io/kubernetes/pkg/volume/cephfs/cephfs.go index 9fe57b0b7490..18574ee9aeec 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cephfs/cephfs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cephfs/cephfs.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cephfs/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/cephfs/doc.go index 7ce1ec74674b..0805915467aa 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cephfs/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cephfs/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cinder/attacher.go b/vendor/k8s.io/kubernetes/pkg/volume/cinder/attacher.go index e3f031c67212..ecf11e1c7492 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cinder/attacher.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cinder/attacher.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -279,6 +279,12 @@ func pathExists(path string) (bool, error) { // Unmount the global mount path, which should be the only one, and delete it. func unmountPDAndRemoveGlobalPath(globalMountPath string, mounter mount.Interface) error { + if pathExists, pathErr := pathExists(globalMountPath); pathErr != nil { + return fmt.Errorf("Error checking if path exists: %v", pathErr) + } else if !pathExists { + glog.V(5).Infof("Warning: Unmount skipped because path does not exist: %v", globalMountPath) + return nil + } err := mounter.Unmount(globalMountPath) os.Remove(globalMountPath) return err diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder.go b/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder.go index e161f5a4c7d8..75e8a6d7352f 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder_util.go b/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder_util.go index 8f513cb6a10f..afd22d2cb333 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cinder/cinder_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/cinder/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/cinder/doc.go index a3c5da052f79..08559bc14764 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/cinder/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/cinder/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/configmap/configmap.go b/vendor/k8s.io/kubernetes/pkg/volume/configmap/configmap.go index baabc7dde759..98c00c44ed20 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/configmap/configmap.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/configmap/configmap.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/configmap/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/configmap/doc.go index 7d5c6c873097..565a19260411 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/configmap/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/configmap/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/doc.go index e75b8a31424e..df39f32913c1 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/downwardapi/downwardapi.go b/vendor/k8s.io/kubernetes/pkg/volume/downwardapi/downwardapi.go index e5c58c4b6838..184b2c5859d7 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/downwardapi/downwardapi.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/downwardapi/downwardapi.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/doc.go index 143ed0ec3540..10d7abd212fb 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir.go b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir.go index 04f5bfa64b81..0653b2556ffd 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_linux.go b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_linux.go index d1ecf2b93443..41e474f9d77b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_unsupported.go b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_unsupported.go index c73a8b777d47..32ab046f1bad 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/empty_dir/empty_dir_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/fc/disk_manager.go b/vendor/k8s.io/kubernetes/pkg/volume/fc/disk_manager.go index 8221f6b62de2..7a0e210fb725 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/fc/disk_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/fc/disk_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/fc/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/fc/doc.go index 454597efd599..3f23662adb12 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/fc/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/fc/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/fc/fc.go b/vendor/k8s.io/kubernetes/pkg/volume/fc/fc.go index 6ebd64532313..96e851879492 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/fc/fc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/fc/fc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/fc/fc_util.go b/vendor/k8s.io/kubernetes/pkg/volume/fc/fc_util.go index 3da539668748..ab3c5ca45f81 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/fc/fc_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/fc/fc_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume.go b/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume.go index 6ea0ef7c6489..eb4642ca7c00 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume_util.go b/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume_util.go index 094a107fbfe6..80a490a01d91 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/flexvolume/flexvolume_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/flocker/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/flocker/doc.go index e07a0d519aa1..440e74ed14d8 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/flocker/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/flocker/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/flocker/plugin.go b/vendor/k8s.io/kubernetes/pkg/volume/flocker/plugin.go index 13c2484a73d6..9bdf9bc3e689 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/flocker/plugin.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/flocker/plugin.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -223,8 +223,10 @@ func (b flockerMounter) updateDatasetPrimary(datasetID, primaryUUID string) erro return err } - timeoutChan := time.NewTimer(timeoutWaitingForVolume).C - tickChan := time.NewTicker(tickerWaitingForVolume).C + timeoutChan := time.NewTimer(timeoutWaitingForVolume) + defer timeoutChan.Stop() + tickChan := time.NewTicker(tickerWaitingForVolume) + defer tickChan.Stop() for { if s, err := b.client.GetDatasetState(datasetID); err == nil && s.Primary == primaryUUID { @@ -232,12 +234,12 @@ func (b flockerMounter) updateDatasetPrimary(datasetID, primaryUUID string) erro } select { - case <-timeoutChan: + case <-timeoutChan.C: return fmt.Errorf( "Timed out waiting for the dataset_id: '%s' to be moved to the primary: '%s'\n%v", datasetID, primaryUUID, err, ) - case <-tickChan: + case <-tickChan.C: break } } diff --git a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/attacher.go b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/attacher.go index a84cf9ed8c20..c60a02aeaeeb 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/attacher.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/attacher.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/doc.go index 7d9f99f0108b..39b5db1d9a6b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_pd.go b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_pd.go index bc6cedc1ee35..a3d57bd0e0c4 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_pd.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_pd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_util.go b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_util.go index 717b9b0df100..4b0a58c41b19 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/gce_pd/gce_util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -125,7 +125,14 @@ func verifyDevicePath(devicePaths []string, sdBeforeSet sets.String) (string, er } // Unmount the global PD mount, which should be the only one, and delete it. +// Does nothing if globalMountPath does not exist. func unmountPDAndRemoveGlobalPath(globalMountPath string, mounter mount.Interface) error { + if pathExists, pathErr := pathExists(globalMountPath); pathErr != nil { + return fmt.Errorf("Error checking if path exists: %v", pathErr) + } else if !pathExists { + glog.V(5).Infof("Warning: Unmount skipped because path does not exist: %v", globalMountPath) + return nil + } err := mounter.Unmount(globalMountPath) os.Remove(globalMountPath) return err diff --git a/vendor/k8s.io/kubernetes/pkg/volume/git_repo/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/git_repo/doc.go index 07ec8382a08b..349182085efa 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/git_repo/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/git_repo/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/git_repo/git_repo.go b/vendor/k8s.io/kubernetes/pkg/volume/git_repo/git_repo.go index 2bc17f409119..9d2c2ca3a83e 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/git_repo/git_repo.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/git_repo/git_repo.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/doc.go index 7b910e59276a..8184f296a440 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs.go b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs.go index 5983290c5b6b..bbaea800aff3 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs_util.go b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs_util.go index c5872dac8f7d..40cbd61ab6df 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/glusterfs/glusterfs_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/host_path/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/host_path/doc.go index 76ab89d0a33f..94f5690f21d0 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/host_path/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/host_path/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/host_path/host_path.go b/vendor/k8s.io/kubernetes/pkg/volume/host_path/host_path.go index 7f0b26a4c298..93d20d62e4f4 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/host_path/host_path.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/host_path/host_path.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/disk_manager.go b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/disk_manager.go index bd34ca9c98c6..960f6c08264b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/disk_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/disk_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/doc.go index d9d146a10816..e0588b2cf669 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi.go b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi.go index 3f5ab03d2d13..9ca787c183c7 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi_util.go b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi_util.go index c9c92beb4042..dd35a8280f3f 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/iscsi/iscsi_util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import ( "os" "path" "path/filepath" + "regexp" "strings" "time" @@ -35,15 +36,15 @@ import ( type StatFunc func(string) (os.FileInfo, error) type GlobFunc func(string) ([]string, error) -func waitForPathToExist(devicePath string, maxRetries int, deviceInterface string) bool { +func waitForPathToExist(devicePath string, maxRetries int, deviceTransport string) bool { // This makes unit testing a lot easier - return waitForPathToExistInternal(devicePath, maxRetries, deviceInterface, os.Stat, filepath.Glob) + return waitForPathToExistInternal(devicePath, maxRetries, deviceTransport, os.Stat, filepath.Glob) } -func waitForPathToExistInternal(devicePath string, maxRetries int, deviceInterface string, osStat StatFunc, filepathGlob GlobFunc) bool { +func waitForPathToExistInternal(devicePath string, maxRetries int, deviceTransport string, osStat StatFunc, filepathGlob GlobFunc) bool { for i := 0; i < maxRetries; i++ { var err error - if deviceInterface == "default" { + if deviceTransport == "tcp" { _, err = osStat(devicePath) } else { fpath, _ := filepathGlob(devicePath) @@ -99,12 +100,25 @@ func (util *ISCSIUtil) MakeGlobalPDName(iscsi iscsiDisk) string { func (util *ISCSIUtil) AttachDisk(b iscsiDiskMounter) error { var devicePath string - if b.iface == "default" { + var iscsiTransport string + + out, err := b.plugin.execCommand("iscsiadm", []string{"-m", "iface", "-I", b.iface, "-o", "show"}) + if err != nil { + glog.Errorf("iscsi: could not read iface %s error: %s", b.iface, string(out)) + return err + } + + iscsiTransport = extractTransportname(string(out)) + + if iscsiTransport == "" { + glog.Errorf("iscsi: could not find transport name in iface %s", b.iface) + return errors.New(fmt.Sprintf("Could not parse iface file for %s", b.iface)) + } else if iscsiTransport == "tcp" { devicePath = strings.Join([]string{"/dev/disk/by-path/ip", b.portal, "iscsi", b.iqn, "lun", b.lun}, "-") } else { devicePath = strings.Join([]string{"/dev/disk/by-path/pci", "*", "ip", b.portal, "iscsi", b.iqn, "lun", b.lun}, "-") } - exist := waitForPathToExist(devicePath, 1, b.iface) + exist := waitForPathToExist(devicePath, 1, iscsiTransport) if exist == false { // discover iscsi target out, err := b.plugin.execCommand("iscsiadm", []string{"-m", "discovery", "-t", "sendtargets", "-p", b.portal, "-I", b.iface}) @@ -118,7 +132,7 @@ func (util *ISCSIUtil) AttachDisk(b iscsiDiskMounter) error { glog.Errorf("iscsi: failed to attach disk:Error: %s (%v)", string(out), err) return err } - exist = waitForPathToExist(devicePath, 10, b.iface) + exist = waitForPathToExist(devicePath, 10, iscsiTransport) if !exist { return errors.New("Could not attach disk: Timeout after 10s") } @@ -184,6 +198,23 @@ func (util *ISCSIUtil) DetachDisk(c iscsiDiskUnmounter, mntPath string) error { return nil } +func extractTransportname(ifaceOutput string) (iscsiTransport string) { + re := regexp.MustCompile(`iface.transport_name = (.*)\n`) + + rex_output := re.FindStringSubmatch(ifaceOutput) + if rex_output != nil { + iscsiTransport = rex_output[1] + } else { + return "" + } + + // While iface.transport_name is a required parameter, handle it being unspecified anyways + if iscsiTransport == "" { + iscsiTransport = "tcp" + } + return iscsiTransport +} + func extractDeviceAndPrefix(mntPath string) (string, string, error) { ind := strings.LastIndex(mntPath, "/") if ind < 0 { diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_cached.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_cached.go index cec488dd0f9f..ac0dc9b7a570 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_cached.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/metrics_cached.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_du.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_du.go index 843cfd65df48..95d24caecc66 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_du.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/metrics_du.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil.go index 1c6626c17adc..38b81fcd74c9 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs.go index 856c69547515..d98d36b81f58 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/nfs/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/nfs/doc.go index a735737346e9..df5a513c7f22 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/nfs/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/nfs/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/nfs/nfs.go b/vendor/k8s.io/kubernetes/pkg/volume/nfs/nfs.go index 2cd8bdcc21aa..463addc6b75d 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/nfs/nfs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/nfs/nfs.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/plugins.go b/vendor/k8s.io/kubernetes/pkg/volume/plugins.go index 6a58b68812de..669aff661b69 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/plugins.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/rbd/disk_manager.go b/vendor/k8s.io/kubernetes/pkg/volume/rbd/disk_manager.go index d03b83156155..15d1e8ef073a 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/rbd/disk_manager.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/rbd/disk_manager.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ limitations under the License. */ // -// diskManager interface and diskSetup/TearDown functions abtract commonly used procedures to setup a block volume +// diskManager interface and diskSetup/TearDown functions abstract commonly used procedures to setup a block volume // rbd volume implements diskManager, calls diskSetup when creating a volume, and calls diskTearDown inside volume unmounter. // TODO: consolidate, refactor, and share diskManager among iSCSI, GCE PD, and RBD // diff --git a/vendor/k8s.io/kubernetes/pkg/volume/rbd/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/rbd/doc.go index e9220fb892ee..66f62222594a 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/rbd/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/rbd/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd.go b/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd.go index 9d5a622bc998..94893cd7802b 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd_util.go b/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd_util.go index 133eaea967af..1cfc42b5d719 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/rbd/rbd_util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/secret/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/secret/doc.go index 99b096475849..3e0ec33d2fad 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/secret/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/secret/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/secret/secret.go b/vendor/k8s.io/kubernetes/pkg/volume/secret/secret.go index ec909cb699e8..0a397fa552ac 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/secret/secret.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/secret/secret.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util.go b/vendor/k8s.io/kubernetes/pkg/volume/util.go index 9c2b352b931d..b36632c9f521 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go b/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go index 4d7a4d26715c..542378a85d2f 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util.go b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util.go index 5f18806158ff..9098d7b8597c 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux.go b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux.go index 8933087cc6c9..0d9851140f62 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_unsupported.go b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_unsupported.go index dbc03874a5a1..6afb1f139154 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/doc.go b/vendor/k8s.io/kubernetes/pkg/volume/util/doc.go index 22409503970b..82c976e7df93 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/fs.go b/vendor/k8s.io/kubernetes/pkg/volume/util/fs.go index b200eed0c93f..be8773bbd6dd 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/fs.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/fs.go @@ -1,7 +1,7 @@ // +build linux darwin /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/fs_unsupported.go b/vendor/k8s.io/kubernetes/pkg/volume/util/fs_unsupported.go index 1349523ee7dd..3df7ef2da562 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/fs_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/fs_unsupported.go @@ -1,7 +1,7 @@ // +build !linux,!darwin /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/io_util.go b/vendor/k8s.io/kubernetes/pkg/volume/util/io_util.go index 309a408f5c0e..e1f30f5c32c1 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/io_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/io_util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go b/vendor/k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go index 0ba530d2847a..9b3743f7bf58 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -65,9 +65,8 @@ func NewNestedPendingOperations(exponentialBackOffOnError bool) NestedPendingOpe g := &nestedPendingOperations{ operations: []operation{}, exponentialBackOffOnError: exponentialBackOffOnError, - lock: &sync.Mutex{}, } - g.cond = sync.NewCond(g.lock) + g.cond = sync.NewCond(&g.lock) return g } @@ -75,7 +74,7 @@ type nestedPendingOperations struct { operations []operation exponentialBackOffOnError bool cond *sync.Cond - lock *sync.Mutex + lock sync.Mutex } type operation struct { diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/operationexecutor/operation_executor.go b/vendor/k8s.io/kubernetes/pkg/volume/util/operationexecutor/operation_executor.go index 0bd9c7910466..28c1e57d750a 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/operationexecutor/operation_executor.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/operationexecutor/operation_executor.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/types" + "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util/nestedpendingoperations" volumetypes "k8s.io/kubernetes/pkg/volume/util/types" @@ -85,7 +86,7 @@ type OperationExecutor interface { // UnmountDevice unmounts the volumes global mount path from the device (for // attachable volumes only, freeing it for detach. It then updates the // actual state of the world to reflect that. - UnmountDevice(deviceToDetach AttachedVolume, actualStateOfWorld ActualStateOfWorldMounterUpdater) error + UnmountDevice(deviceToDetach AttachedVolume, actualStateOfWorld ActualStateOfWorldMounterUpdater, mounter mount.Interface) error // VerifyControllerAttachedVolume checks if the specified volume is present // in the specified nodes AttachedVolumes Status field. It uses kubeClient @@ -214,6 +215,10 @@ type AttachedVolume struct { // PluginIsAttachable indicates that the plugin for this volume implements // the volume.Attacher interface PluginIsAttachable bool + + // DevicePath contains the path on the node where the volume is attached. + // For non-attachable volumes this is empty. + DevicePath string } // MountedVolume represents a volume that has successfully been mounted to a pod. @@ -402,9 +407,10 @@ func (oe *operationExecutor) UnmountVolume( func (oe *operationExecutor) UnmountDevice( deviceToDetach AttachedVolume, - actualStateOfWorld ActualStateOfWorldMounterUpdater) error { + actualStateOfWorld ActualStateOfWorldMounterUpdater, + mounter mount.Interface) error { unmountDeviceFunc, err := - oe.generateUnmountDeviceFunc(deviceToDetach, actualStateOfWorld) + oe.generateUnmountDeviceFunc(deviceToDetach, actualStateOfWorld, mounter) if err != nil { return err } @@ -831,7 +837,8 @@ func (oe *operationExecutor) generateUnmountVolumeFunc( func (oe *operationExecutor) generateUnmountDeviceFunc( deviceToDetach AttachedVolume, - actualStateOfWorld ActualStateOfWorldMounterUpdater) (func() error, error) { + actualStateOfWorld ActualStateOfWorldMounterUpdater, + mounter mount.Interface) (func() error, error) { // Get attacher plugin attachableVolumePlugin, err := oe.volumePluginMgr.FindAttachablePluginBySpec(deviceToDetach.VolumeSpec) @@ -883,6 +890,24 @@ func (oe *operationExecutor) generateUnmountDeviceFunc( deviceToDetach.VolumeSpec.Name(), unmountDeviceErr) } + // Before logging that UnmountDevice succeeded and moving on, + // use mounter.DeviceOpened to check if the device is in use anywhere + // else on the system. Retry if it returns true. + deviceOpened, deviceOpenedErr := mounter.DeviceOpened(deviceToDetach.DevicePath) + if deviceOpenedErr != nil { + return fmt.Errorf( + "UnmountDevice.DeviceOpened failed for volume %q (spec.Name: %q) with: %v", + deviceToDetach.VolumeName, + deviceToDetach.VolumeSpec.Name(), + deviceOpenedErr) + } + // The device is still in use elsewhere. Caller will log and retry. + if deviceOpened { + return fmt.Errorf( + "UnmountDevice failed for volume %q (spec.Name: %q) because the device is in use when it was no longer expected to be in use", + deviceToDetach.VolumeName, + deviceToDetach.VolumeSpec.Name()) + } glog.Infof( "UnmountDevice succeeded for volume %q (spec.Name: %q).", diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/types/types.go b/vendor/k8s.io/kubernetes/pkg/volume/util/types/types.go index 219d9dd4ec2c..1c66503c177d 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/types/types.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/types/types.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package types defines types used only by volume componenets +// Package types defines types used only by volume components package types import "k8s.io/kubernetes/pkg/types" diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/util.go b/vendor/k8s.io/kubernetes/pkg/volume/util/util.go index 6b85dec4c0d0..ca16b12d3d80 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/volumehelper/volumehelper.go b/vendor/k8s.io/kubernetes/pkg/volume/util/volumehelper/volumehelper.go index a761c1fffb6d..2ab765e3cd95 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/volumehelper/volumehelper.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/volumehelper/volumehelper.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/volume.go b/vendor/k8s.io/kubernetes/pkg/volume/volume.go index 4070770ace13..fe8fbe1380e2 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/volume.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/volume.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ type Volume interface { // MetricsProvider exposes metrics (e.g. used,available space) related to a // Volume. type MetricsProvider interface { - // GetMetrics returns the Metrics for the Volume. Maybe expensive for + // GetMetrics returns the Metrics for the Volume. Maybe expensive for // some implementations. GetMetrics() (*Metrics, error) } @@ -107,9 +107,9 @@ type Unmounter interface { // Recycler provides methods to reclaim the volume resource. type Recycler interface { Volume - // Recycle reclaims the resource. Calls to this method should block until + // Recycle reclaims the resource. Calls to this method should block until // the recycling task is complete. Any error returned indicates the volume - // has failed to be reclaimed. A nil return indicates success. + // has failed to be reclaimed. A nil return indicates success. Recycle() error } @@ -122,7 +122,7 @@ type Provisioner interface { Provision() (*api.PersistentVolume, error) } -// Deleter removes the resource from the underlying storage provider. Calls +// Deleter removes the resource from the underlying storage provider. Calls // to this method should block until the deletion is complete. Any error // returned indicates the volume has failed to be reclaimed. A nil return // indicates success. @@ -135,7 +135,7 @@ type Deleter interface { // Attacher can attach a volume to a node. type Attacher interface { // Attaches the volume specified by the given spec to the given host. - // On success, returns the device path where the device was attache don the + // On success, returns the device path where the device was attached on the // node. Attach(spec *Spec, hostName string) (string, error) diff --git a/vendor/k8s.io/kubernetes/pkg/volume/volume_linux.go b/vendor/k8s.io/kubernetes/pkg/volume/volume_linux.go index 07bad5969c4d..cd8b6b2b82e6 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/volume_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/volume_linux.go @@ -1,7 +1,7 @@ // +build linux /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/volume_unsupported.go b/vendor/k8s.io/kubernetes/pkg/volume/volume_unsupported.go index fdd52df912d2..45a6cc5ca7fa 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/volume_unsupported.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/volume_unsupported.go @@ -1,7 +1,7 @@ // +build !linux /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume.go b/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume.go index ecf983547a3e..a640342a75a4 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume_util.go b/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume_util.go index f54d10d586bd..e0546ee6e202 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume_util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/vsphere_volume/vsphere_volume_util.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/doc.go b/vendor/k8s.io/kubernetes/pkg/watch/doc.go index fd9b437e11b0..5fde5e7427a5 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/doc.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/filter.go b/vendor/k8s.io/kubernetes/pkg/watch/filter.go index 1eff5b94964b..3ca27f22c5f7 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/filter.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/filter.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/mux.go b/vendor/k8s.io/kubernetes/pkg/watch/mux.go index 700c26bcadee..ec6de050e5f7 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/mux.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/mux.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/streamwatcher.go b/vendor/k8s.io/kubernetes/pkg/watch/streamwatcher.go index 2802a9e01f4f..26cf61d052fd 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/streamwatcher.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/streamwatcher.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/until.go b/vendor/k8s.io/kubernetes/pkg/watch/until.go index 9f34f9d001b2..4259f51bb5ca 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/until.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/until.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/decoder.go b/vendor/k8s.io/kubernetes/pkg/watch/versioned/decoder.go index 2d13ca809ff1..e5865273e292 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/decoder.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/decoder.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/encoder.go b/vendor/k8s.io/kubernetes/pkg/watch/versioned/encoder.go index 8438ee984f38..df23e0bd168d 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/encoder.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/encoder.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.pb.go b/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.pb.go index c1cbbd8ba569..a50a7a2d259c 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.pb.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.pb.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -33,6 +33,9 @@ import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" +import strings "strings" +import reflect "reflect" + import io "io" // Reference imports to suppress errors if they are not otherwise used. @@ -40,9 +43,8 @@ var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} +func (m *Event) Reset() { *m = Event{} } +func (*Event) ProtoMessage() {} func init() { proto.RegisterType((*Event)(nil), "k8s.io.kubernetes.pkg.watch.versioned.Event") @@ -127,6 +129,25 @@ func sovGenerated(x uint64) (n int) { func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (this *Event) String() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&Event{`, + `Type:` + fmt.Sprintf("%v", this.Type) + `,`, + `Object:` + strings.Replace(strings.Replace(this.Object.String(), "RawExtension", "k8s_io_kubernetes_pkg_runtime.RawExtension", 1), `&`, ``, 1) + `,`, + `}`, + }, "") + return s +} +func valueToStringGenerated(v interface{}) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("*%v", pv) +} func (m *Event) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.proto b/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.proto index 5bb702210e2f..8d5506552d94 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.proto +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/generated.proto @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/register.go b/vendor/k8s.io/kubernetes/pkg/watch/versioned/register.go index feaea3b6b799..e90a021a43db 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/register.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/register.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/versioned/types.go b/vendor/k8s.io/kubernetes/pkg/watch/versioned/types.go index ba608aeab029..f8e968ccc025 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/versioned/types.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/versioned/types.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/pkg/watch/watch.go b/vendor/k8s.io/kubernetes/pkg/watch/watch.go index e8fca0a62497..96b2fe3de28b 100644 --- a/vendor/k8s.io/kubernetes/pkg/watch/watch.go +++ b/vendor/k8s.io/kubernetes/pkg/watch/watch.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options/options.go b/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options/options.go index b54bc1e2e7fa..4d84dcd225f3 100644 --- a/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options/options.go +++ b/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/options/options.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -42,6 +42,7 @@ type SchedulerServer struct { func NewSchedulerServer() *SchedulerServer { config := componentconfig.KubeSchedulerConfiguration{} api.Scheme.Convert(&v1alpha1.KubeSchedulerConfiguration{}, &config) + config.LeaderElection.LeaderElect = true s := SchedulerServer{ KubeSchedulerConfiguration: config, } diff --git a/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/server.go b/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/server.go index 16d5e87eb67f..bf7e39ce101f 100644 --- a/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/server.go +++ b/vendor/k8s.io/kubernetes/plugin/cmd/kube-scheduler/app/server.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -76,6 +76,7 @@ func Run(s *options.SchedulerServer) error { } kubeconfig, err := clientcmd.BuildConfigFromFlags(s.Master, s.Kubeconfig) if err != nil { + glog.Errorf("unable to build config from flags: %v", err) return err } @@ -134,6 +135,7 @@ func Run(s *options.SchedulerServer) error { id, err := os.Hostname() if err != nil { + glog.Errorf("unable to get hostname: %v", err) return err } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/admit/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/admit/admission.go index dfbad5f71d9e..b7b528aedfa4 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/admit/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/admit/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/alwayspullimages/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/alwayspullimages/admission.go index 2d2b5147efb6..c0e36709bfda 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/alwayspullimages/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/alwayspullimages/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/admission.go index 832351c39740..50cb5a5f8cb1 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import ( "fmt" "io" + "github.com/golang/glog" "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" @@ -59,9 +60,10 @@ func (p *plugin) Admit(attributes admission.Attributes) (err error) { } affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { - return err + glog.V(5).Infof("Invalid Affinity detected, but we will leave handling of this to validation phase") + return nil } - if affinity.PodAntiAffinity != nil { + if affinity != nil && affinity.PodAntiAffinity != nil { var podAntiAffinityTerms []api.PodAffinityTerm if len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { podAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/doc.go index a2a1acd05026..9fc189b15e29 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/antiaffinity/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/deny/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/deny/admission.go index 4eef85326e09..7b62ea81b330 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/deny/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/deny/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/exec/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/exec/admission.go index d98bff6759d9..25aecca11b74 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/exec/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/exec/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/admission.go index 8db5bf07a37e..0fcbfa9deb78 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package initialresources import ( "flag" + "fmt" "io" "sort" "strings" @@ -89,51 +90,12 @@ func (ir initialResources) Admit(a admission.Attributes) (err error) { // The method veryfies whether resources should be set for the given pod and // if there is estimation available the method fills Request field. func (ir initialResources) estimateAndFillResourcesIfNotSet(pod *api.Pod) { - annotations := []string{} + var annotations []string + for i := range pod.Spec.InitContainers { + annotations = append(annotations, ir.estimateContainer(pod, &pod.Spec.InitContainers[i], "init container")...) + } for i := range pod.Spec.Containers { - c := &pod.Spec.Containers[i] - req := c.Resources.Requests - lim := c.Resources.Limits - var cpu, mem *resource.Quantity - var err error - if _, ok := req[api.ResourceCPU]; !ok { - if _, ok2 := lim[api.ResourceCPU]; !ok2 { - cpu, err = ir.getEstimation(api.ResourceCPU, c, pod.ObjectMeta.Namespace) - if err != nil { - glog.Errorf("Error while trying to estimate resources: %v", err) - } - } - } - if _, ok := req[api.ResourceMemory]; !ok { - if _, ok2 := lim[api.ResourceMemory]; !ok2 { - mem, err = ir.getEstimation(api.ResourceMemory, c, pod.ObjectMeta.Namespace) - if err != nil { - glog.Errorf("Error while trying to estimate resources: %v", err) - } - } - } - - // If Requests doesn't exits and an estimation was made, create Requests. - if req == nil && (cpu != nil || mem != nil) { - c.Resources.Requests = api.ResourceList{} - req = c.Resources.Requests - } - setRes := []string{} - if cpu != nil { - glog.Infof("CPU estimation for container %v in pod %v/%v is %v", c.Name, pod.ObjectMeta.Namespace, pod.ObjectMeta.Name, cpu.String()) - setRes = append(setRes, string(api.ResourceCPU)) - req[api.ResourceCPU] = *cpu - } - if mem != nil { - glog.Infof("Memory estimation for container %v in pod %v/%v is %v", c.Name, pod.ObjectMeta.Namespace, pod.ObjectMeta.Name, mem.String()) - setRes = append(setRes, string(api.ResourceMemory)) - req[api.ResourceMemory] = *mem - } - if len(setRes) > 0 { - sort.Strings(setRes) - a := strings.Join(setRes, ", ") + " request for container " + c.Name - annotations = append(annotations, a) - } + annotations = append(annotations, ir.estimateContainer(pod, &pod.Spec.Containers[i], "container")...) } if len(annotations) > 0 { if pod.ObjectMeta.Annotations == nil { @@ -144,6 +106,53 @@ func (ir initialResources) estimateAndFillResourcesIfNotSet(pod *api.Pod) { } } +func (ir initialResources) estimateContainer(pod *api.Pod, c *api.Container, message string) []string { + var annotations []string + req := c.Resources.Requests + lim := c.Resources.Limits + var cpu, mem *resource.Quantity + var err error + if _, ok := req[api.ResourceCPU]; !ok { + if _, ok2 := lim[api.ResourceCPU]; !ok2 { + cpu, err = ir.getEstimation(api.ResourceCPU, c, pod.ObjectMeta.Namespace) + if err != nil { + glog.Errorf("Error while trying to estimate resources: %v", err) + } + } + } + if _, ok := req[api.ResourceMemory]; !ok { + if _, ok2 := lim[api.ResourceMemory]; !ok2 { + mem, err = ir.getEstimation(api.ResourceMemory, c, pod.ObjectMeta.Namespace) + if err != nil { + glog.Errorf("Error while trying to estimate resources: %v", err) + } + } + } + + // If Requests doesn't exits and an estimation was made, create Requests. + if req == nil && (cpu != nil || mem != nil) { + c.Resources.Requests = api.ResourceList{} + req = c.Resources.Requests + } + setRes := []string{} + if cpu != nil { + glog.Infof("CPU estimation for %s %v in pod %v/%v is %v", message, c.Name, pod.ObjectMeta.Namespace, pod.ObjectMeta.Name, cpu.String()) + setRes = append(setRes, string(api.ResourceCPU)) + req[api.ResourceCPU] = *cpu + } + if mem != nil { + glog.Infof("Memory estimation for %s %v in pod %v/%v is %v", message, c.Name, pod.ObjectMeta.Namespace, pod.ObjectMeta.Name, mem.String()) + setRes = append(setRes, string(api.ResourceMemory)) + req[api.ResourceMemory] = *mem + } + if len(setRes) > 0 { + sort.Strings(setRes) + a := strings.Join(setRes, ", ") + fmt.Sprintf(" request for %s %s", message, c.Name) + annotations = append(annotations, a) + } + return annotations +} + func (ir initialResources) getEstimation(kind api.ResourceName, c *api.Container, ns string) (*resource.Quantity, error) { end := time.Now() start := end.Add(-week) diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/data_source.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/data_source.go index a8b41621d5cc..2836dd81c51b 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/data_source.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/data_source.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/gcm.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/gcm.go index 4a55c03a3cc4..a60d4519a903 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/gcm.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/gcm.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/hawkular.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/hawkular.go index 1d276d7cfc1b..4599b41228ca 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/hawkular.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/hawkular.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/influxdb.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/influxdb.go index d72f16fcb0c5..357b28a22d5d 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/influxdb.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/initialresources/influxdb.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/admission.go index 6b6d8331fe4a..500f292f9e21 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -384,7 +384,7 @@ func sum(inputs []api.ResourceList) api.ResourceList { return result } -// DefaultLimitRangerActions is the default implementatation of LimitRangerActions. +// DefaultLimitRangerActions is the default implementation of LimitRangerActions. type DefaultLimitRangerActions struct{} // ensure DefaultLimitRangerActions implements the LimitRangerActions interface. @@ -448,6 +448,24 @@ func PodLimitFunc(limitRange *api.LimitRange, pod *api.Pod) error { } } } + for j := range pod.Spec.InitContainers { + container := &pod.Spec.InitContainers[j] + for k, v := range limit.Min { + if err := minConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil { + errs = append(errs, err) + } + } + for k, v := range limit.Max { + if err := maxConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil { + errs = append(errs, err) + } + } + for k, v := range limit.MaxLimitRequestRatio { + if err := limitRequestRatioConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil { + errs = append(errs, err) + } + } + } } // enforce pod limits on init containers diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/interfaces.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/interfaces.go index b5eb6632f2e2..8f1222851bef 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/interfaces.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/limitranger/interfaces.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision/admission.go index 9ffb530b7a32..3f248ef5982c 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/autoprovision/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,12 +21,11 @@ import ( clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "fmt" "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" + "k8s.io/kubernetes/pkg/controller/framework/informers" ) func init() { @@ -40,10 +39,12 @@ func init() { // It is useful in deployments that do not want to restrict creation of a namespace prior to its usage. type provision struct { *admission.Handler - client clientset.Interface - store cache.Store + client clientset.Interface + informerFactory informers.SharedInformerFactory } +var _ = admission.WantsInformerFactory(&provision{}) + func (p *provision) Admit(a admission.Attributes) (err error) { // if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do // if we're here, then the API server has found a route, which means that if we have a non-empty namespace @@ -59,7 +60,7 @@ func (p *provision) Admit(a admission.Attributes) (err error) { }, Status: api.NamespaceStatus{}, } - _, exists, err := p.store.Get(namespace) + _, exists, err := p.informerFactory.Namespaces().Informer().GetStore().Get(namespace) if err != nil { return admission.NewForbidden(a, err) } @@ -75,28 +76,19 @@ func (p *provision) Admit(a admission.Attributes) (err error) { // NewProvision creates a new namespace provision admission control handler func NewProvision(c clientset.Interface) admission.Interface { - store := cache.NewStore(cache.MetaNamespaceKeyFunc) - reflector := cache.NewReflector( - &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return c.Core().Namespaces().List(options) - }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return c.Core().Namespaces().Watch(options) - }, - }, - &api.Namespace{}, - store, - 0, - ) - reflector.Run() - return createProvision(c, store) -} - -func createProvision(c clientset.Interface, store cache.Store) admission.Interface { return &provision{ Handler: admission.NewHandler(admission.Create), client: c, - store: store, } } + +func (p *provision) SetInformerFactory(f informers.SharedInformerFactory) { + p.informerFactory = f +} + +func (p *provision) Validate() error { + if p.informerFactory == nil { + return fmt.Errorf("namespace autoprovision plugin needs SharedInformerFactory") + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/exists/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/exists/admission.go index 0986fabe4df1..ab031ee607bf 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/exists/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/exists/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,16 +18,14 @@ package exists import ( "io" - "time" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + "fmt" "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/errors" - "k8s.io/kubernetes/pkg/client/cache" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/watch" + "k8s.io/kubernetes/pkg/controller/framework/informers" ) func init() { @@ -41,10 +39,12 @@ func init() { // It is useful in deployments that want to enforce pre-declaration of a Namespace resource. type exists struct { *admission.Handler - client clientset.Interface - store cache.Store + client clientset.Interface + informerFactory informers.SharedInformerFactory } +var _ = admission.WantsInformerFactory(&exists{}) + func (e *exists) Admit(a admission.Attributes) (err error) { // if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do // if we're here, then the API server has found a route, which means that if we have a non-empty namespace @@ -60,7 +60,7 @@ func (e *exists) Admit(a admission.Attributes) (err error) { }, Status: api.NamespaceStatus{}, } - _, exists, err := e.store.Get(namespace) + _, exists, err := e.informerFactory.Namespaces().Informer().GetStore().Get(namespace) if err != nil { return errors.NewInternalError(err) } @@ -82,24 +82,19 @@ func (e *exists) Admit(a admission.Attributes) (err error) { // NewExists creates a new namespace exists admission control handler func NewExists(c clientset.Interface) admission.Interface { - store := cache.NewStore(cache.MetaNamespaceKeyFunc) - reflector := cache.NewReflector( - &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return c.Core().Namespaces().List(options) - }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return c.Core().Namespaces().Watch(options) - }, - }, - &api.Namespace{}, - store, - 5*time.Minute, - ) - reflector.Run() return &exists{ client: c, - store: store, Handler: admission.NewHandler(admission.Create, admission.Update, admission.Delete), } } + +func (e *exists) SetInformerFactory(f informers.SharedInformerFactory) { + e.informerFactory = f +} + +func (e *exists) Validate() error { + if e.informerFactory == nil { + return fmt.Errorf("namespace exists plugin needs a namespace informer") + } + return nil +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/lifecycle/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/lifecycle/admission.go index 997ee263b5ce..e75f56397c41 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/lifecycle/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/namespace/lifecycle/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/admission.go index 915ea63a5a4d..a2c92ebc87d8 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/doc.go index 65d520bbad18..22f486b5c372 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/persistentvolume/label/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/admission.go index 5ddd6db3dc42..244d338eefc5 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package resourcequota import ( "io" - "sort" - "strings" "time" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" @@ -28,7 +26,6 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/quota" "k8s.io/kubernetes/pkg/quota/install" - utilruntime "k8s.io/kubernetes/pkg/util/runtime" ) func init() { @@ -44,7 +41,7 @@ func init() { type quotaAdmission struct { *admission.Handler - evaluator *quotaEvaluator + evaluator Evaluator } type liveLookupEntry struct { @@ -56,13 +53,13 @@ type liveLookupEntry struct { // using the provided registry. The registry must have the capability to handle group/kinds that // are persisted by the server this admission controller is intercepting func NewResourceQuota(client clientset.Interface, registry quota.Registry, numEvaluators int, stopCh <-chan struct{}) (admission.Interface, error) { - evaluator, err := newQuotaEvaluator(client, registry) + quotaAccessor, err := newQuotaAccessor(client) if err != nil { return nil, err } + go quotaAccessor.Run(stopCh) - defer utilruntime.HandleCrash() - go evaluator.Run(numEvaluators, stopCh) + evaluator := NewQuotaEvaluator(quotaAccessor, registry, nil, numEvaluators, stopCh) return "aAdmission{ Handler: admission.NewHandler(admission.Create, admission.Update), @@ -77,47 +74,5 @@ func (q *quotaAdmission) Admit(a admission.Attributes) (err error) { return nil } - // if we do not know how to evaluate use for this kind, just ignore - evaluators := q.evaluator.registry.Evaluators() - evaluator, found := evaluators[a.GetKind().GroupKind()] - if !found { - return nil - } - - // for this kind, check if the operation could mutate any quota resources - // if no resources tracked by quota are impacted, then just return - op := a.GetOperation() - operationResources := evaluator.OperationResources(op) - if len(operationResources) == 0 { - return nil - } - - return q.evaluator.evaluate(a) -} - -// prettyPrint formats a resource list for usage in errors -// it outputs resources sorted in increasing order -func prettyPrint(item api.ResourceList) string { - parts := []string{} - keys := []string{} - for key := range item { - keys = append(keys, string(key)) - } - sort.Strings(keys) - for _, key := range keys { - value := item[api.ResourceName(key)] - constraint := key + "=" + value.String() - parts = append(parts, constraint) - } - return strings.Join(parts, ",") -} - -// hasUsageStats returns true if for each hard constraint there is a value for its current usage -func hasUsageStats(resourceQuota *api.ResourceQuota) bool { - for resourceName := range resourceQuota.Status.Hard { - if _, found := resourceQuota.Status.Used[resourceName]; !found { - return false - } - } - return true + return q.evaluator.Evaluate(a) } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/controller.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/controller.go index 5431c9e16300..e88b33aa75dc 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/controller.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/controller.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,46 +18,38 @@ package resourcequota import ( "fmt" + "sort" + "strings" "sync" "time" "github.com/golang/glog" - lru "github.com/hashicorp/golang-lru" - - clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/admission" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" - "k8s.io/kubernetes/pkg/client/cache" "k8s.io/kubernetes/pkg/quota" - "k8s.io/kubernetes/pkg/runtime" - "k8s.io/kubernetes/pkg/storage/etcd" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/util/workqueue" - "k8s.io/kubernetes/pkg/watch" ) +// Evaluator is used to see if quota constraints are satisfied. +type Evaluator interface { + // Evaluate takes an operation and checks to see if quota constraints are satisfied. It returns an error if they are not. + // The default implementation process related operations in chunks when possible. + Evaluate(a admission.Attributes) error +} + type quotaEvaluator struct { - client clientset.Interface + quotaAccessor QuotaAccessor + // lockAquisitionFunc acquires any required locks and returns a cleanup method to defer + lockAquisitionFunc func([]api.ResourceQuota) func() - // indexer that holds quota objects by namespace - indexer cache.Indexer // registry that knows how to measure usage for objects registry quota.Registry - // liveLookups holds the last few live lookups we've done to help ammortize cost on repeated lookup failures. - // This let's us handle the case of latent caches, by looking up actual results for a namespace on cache miss/no results. - // We track the lookup result here so that for repeated requests, we don't look it up very often. - liveLookupCache *lru.Cache - liveTTL time.Duration - // updatedQuotas holds a cache of quotas that we've updated. This is used to pull the "really latest" during back to - // back quota evaluations that touch the same quota doc. This only works because we can compare etcd resourceVersions - // for the same resource as integers. Before this change: 22 updates with 12 conflicts. after this change: 15 updates with 0 conflicts - updatedQuotas *lru.Cache - // TODO these are used together to bucket items by namespace and then batch them up for processing. // The technique is valuable for rollup activities to avoid fanout and reduce resource contention. // We could move this into a library if another component needed it. @@ -67,6 +59,11 @@ type quotaEvaluator struct { work map[string][]*admissionWaiter dirtyWork map[string][]*admissionWaiter inProgress sets.String + + // controls the run method so that we can cleanly conform to the Evaluator interface + workers int + stopCh <-chan struct{} + init sync.Once } type admissionWaiter struct { @@ -98,52 +95,34 @@ func newAdmissionWaiter(a admission.Attributes) *admissionWaiter { } } -// newQuotaEvaluator configures an admission controller that can enforce quota constraints +// NewQuotaEvaluator configures an admission controller that can enforce quota constraints // using the provided registry. The registry must have the capability to handle group/kinds that // are persisted by the server this admission controller is intercepting -func newQuotaEvaluator(client clientset.Interface, registry quota.Registry) (*quotaEvaluator, error) { - liveLookupCache, err := lru.New(100) - if err != nil { - return nil, err - } - updatedCache, err := lru.New(100) - if err != nil { - return nil, err - } - lw := &cache.ListWatch{ - ListFunc: func(options api.ListOptions) (runtime.Object, error) { - return client.Core().ResourceQuotas(api.NamespaceAll).List(options) - }, - WatchFunc: func(options api.ListOptions) (watch.Interface, error) { - return client.Core().ResourceQuotas(api.NamespaceAll).Watch(options) - }, - } - indexer, reflector := cache.NewNamespaceKeyedIndexerAndReflector(lw, &api.ResourceQuota{}, 0) - - reflector.Run() +func NewQuotaEvaluator(quotaAccessor QuotaAccessor, registry quota.Registry, lockAquisitionFunc func([]api.ResourceQuota) func(), workers int, stopCh <-chan struct{}) Evaluator { return "aEvaluator{ - client: client, - indexer: indexer, - registry: registry, - liveLookupCache: liveLookupCache, - liveTTL: time.Duration(30 * time.Second), - updatedQuotas: updatedCache, + quotaAccessor: quotaAccessor, + lockAquisitionFunc: lockAquisitionFunc, + + registry: registry, queue: workqueue.New(), work: map[string][]*admissionWaiter{}, dirtyWork: map[string][]*admissionWaiter{}, inProgress: sets.String{}, - }, nil + + workers: workers, + stopCh: stopCh, + } } // Run begins watching and syncing. -func (e *quotaEvaluator) Run(workers int, stopCh <-chan struct{}) { +func (e *quotaEvaluator) run() { defer utilruntime.HandleCrash() - for i := 0; i < workers; i++ { - go wait.Until(e.doWork, time.Second, stopCh) + for i := 0; i < e.workers; i++ { + go wait.Until(e.doWork, time.Second, e.stopCh) } - <-stopCh + <-e.stopCh glog.Infof("Shutting down quota evaluator") e.queue.ShutDown() } @@ -179,7 +158,7 @@ func (e *quotaEvaluator) checkAttributes(ns string, admissionAttributes []*admis } }() - quotas, err := e.getQuotas(ns) + quotas, err := e.quotaAccessor.GetQuotas(ns) if err != nil { for _, admissionAttribute := range admissionAttributes { admissionAttribute.result = err @@ -193,10 +172,15 @@ func (e *quotaEvaluator) checkAttributes(ns string, admissionAttributes []*admis return } + if e.lockAquisitionFunc != nil { + releaseLocks := e.lockAquisitionFunc(quotas) + defer releaseLocks() + } + e.checkQuotas(quotas, admissionAttributes, 3) } -// checkQuotas checks the admission atttributes against the passed quotas. If a quota applies, it will attempt to update it +// checkQuotas checks the admission attributes against the passed quotas. If a quota applies, it will attempt to update it // AFTER it has checked all the admissionAttributes. The method breaks down into phase like this: // 0. make a copy of the quotas to act as a "running" quota so we know what we need to update and can still compare against the // originals @@ -257,14 +241,9 @@ func (e *quotaEvaluator) checkQuotas(quotas []api.ResourceQuota, admissionAttrib continue } - if updatedQuota, err := e.client.Core().ResourceQuotas(newQuota.Namespace).UpdateStatus(&newQuota); err != nil { + if err := e.quotaAccessor.UpdateQuotaStatus(&newQuota); err != nil { updatedFailedQuotas = append(updatedFailedQuotas, newQuota) lastErr = err - - } else { - // update our cache - e.updateCache(updatedQuota) - } } @@ -293,7 +272,7 @@ func (e *quotaEvaluator) checkQuotas(quotas []api.ResourceQuota, admissionAttrib // you've added a new documented, then updated an old one, your resource matches both and you're only checking one // updates for these quota names failed. Get the current quotas in the namespace, compare by name, check to see if the // resource versions have changed. If not, we're going to fall through an fail everything. If they all have, then we can try again - newQuotas, err := e.getQuotas(quotas[0].Namespace) + newQuotas, err := e.quotaAccessor.GetQuotas(quotas[0].Namespace) if err != nil { // this means that updates failed. Anything with a default deny error has failed and we need to let them know for _, admissionAttribute := range admissionAttributes { @@ -416,7 +395,25 @@ func (e *quotaEvaluator) checkRequest(quotas []api.ResourceQuota, a admission.At return quotas, nil } -func (e *quotaEvaluator) evaluate(a admission.Attributes) error { +func (e *quotaEvaluator) Evaluate(a admission.Attributes) error { + e.init.Do(func() { + go e.run() + }) + + // if we do not know how to evaluate use for this kind, just ignore + evaluators := e.registry.Evaluators() + evaluator, found := evaluators[a.GetKind().GroupKind()] + if !found { + return nil + } + // for this kind, check if the operation could mutate any quota resources + // if no resources tracked by quota are impacted, then just return + op := a.GetOperation() + operationResources := evaluator.OperationResources(op) + if len(operationResources) == 0 { + return nil + } + waiter := newAdmissionWaiter(a) e.addWork(waiter) @@ -485,72 +482,29 @@ func (e *quotaEvaluator) getWork() (string, []*admissionWaiter, bool) { return ns, []*admissionWaiter{}, false } -func (e *quotaEvaluator) updateCache(quota *api.ResourceQuota) { - key := quota.Namespace + "/" + quota.Name - e.updatedQuotas.Add(key, quota) +// prettyPrint formats a resource list for usage in errors +// it outputs resources sorted in increasing order +func prettyPrint(item api.ResourceList) string { + parts := []string{} + keys := []string{} + for key := range item { + keys = append(keys, string(key)) + } + sort.Strings(keys) + for _, key := range keys { + value := item[api.ResourceName(key)] + constraint := key + "=" + value.String() + parts = append(parts, constraint) + } + return strings.Join(parts, ",") } -var etcdVersioner = etcd.APIObjectVersioner{} - -// checkCache compares the passed quota against the value in the look-aside cache and returns the newer -// if the cache is out of date, it deletes the stale entry. This only works because of etcd resourceVersions -// being monotonically increasing integers -func (e *quotaEvaluator) checkCache(quota *api.ResourceQuota) *api.ResourceQuota { - key := quota.Namespace + "/" + quota.Name - uncastCachedQuota, ok := e.updatedQuotas.Get(key) - if !ok { - return quota - } - cachedQuota := uncastCachedQuota.(*api.ResourceQuota) - - if etcdVersioner.CompareResourceVersion(quota, cachedQuota) >= 0 { - e.updatedQuotas.Remove(key) - return quota - } - return cachedQuota -} - -func (e *quotaEvaluator) getQuotas(namespace string) ([]api.ResourceQuota, error) { - // determine if there are any quotas in this namespace - // if there are no quotas, we don't need to do anything - items, err := e.indexer.Index("namespace", &api.ResourceQuota{ObjectMeta: api.ObjectMeta{Namespace: namespace, Name: ""}}) - if err != nil { - return nil, fmt.Errorf("Error resolving quota.") - } - - // if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it. - if len(items) == 0 { - lruItemObj, ok := e.liveLookupCache.Get(namespace) - if !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) { - // TODO: If there are multiple operations at the same time and cache has just expired, - // this may cause multiple List operations being issued at the same time. - // If there is already in-flight List() for a given namespace, we should wait until - // it is finished and cache is updated instead of doing the same, also to avoid - // throttling - see #22422 for details. - liveList, err := e.client.Core().ResourceQuotas(namespace).List(api.ListOptions{}) - if err != nil { - return nil, err - } - newEntry := liveLookupEntry{expiry: time.Now().Add(e.liveTTL)} - for i := range liveList.Items { - newEntry.items = append(newEntry.items, &liveList.Items[i]) - } - e.liveLookupCache.Add(namespace, newEntry) - lruItemObj = newEntry - } - lruEntry := lruItemObj.(liveLookupEntry) - for i := range lruEntry.items { - items = append(items, lruEntry.items[i]) +// hasUsageStats returns true if for each hard constraint there is a value for its current usage +func hasUsageStats(resourceQuota *api.ResourceQuota) bool { + for resourceName := range resourceQuota.Status.Hard { + if _, found := resourceQuota.Status.Used[resourceName]; !found { + return false } } - - resourceQuotas := []api.ResourceQuota{} - for i := range items { - quota := items[i].(*api.ResourceQuota) - quota = e.checkCache(quota) - // always make a copy. We're going to muck around with this and we should never mutate the originals - resourceQuotas = append(resourceQuotas, *quota) - } - - return resourceQuotas, nil + return true } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/doc.go index 69d96109577f..28923b16d833 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/resource_access.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/resource_access.go new file mode 100644 index 000000000000..dfa08106bfaa --- /dev/null +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/resourcequota/resource_access.go @@ -0,0 +1,179 @@ +/* +Copyright 2016 The Kubernetes 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 resourcequota + +import ( + "fmt" + "time" + + "github.com/golang/glog" + lru "github.com/hashicorp/golang-lru" + + clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" + + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/client/cache" + "k8s.io/kubernetes/pkg/runtime" + "k8s.io/kubernetes/pkg/storage/etcd" + utilruntime "k8s.io/kubernetes/pkg/util/runtime" + "k8s.io/kubernetes/pkg/watch" +) + +// QuotaAccessor abstracts the get/set logic from the rest of the Evaluator. This could be a test stub, a straight passthrough, +// or most commonly a series of deconflicting caches. +type QuotaAccessor interface { + // UpdateQuotaStatus is called to persist final status. This method should write to persistent storage. + // An error indicates that write didn't complete successfully. + UpdateQuotaStatus(newQuota *api.ResourceQuota) error + + // GetQuotas gets all possible quotas for a given namespace + GetQuotas(namespace string) ([]api.ResourceQuota, error) +} + +type quotaAccessor struct { + client clientset.Interface + + // indexer that holds quota objects by namespace + indexer cache.Indexer + reflector *cache.Reflector + + // liveLookups holds the last few live lookups we've done to help ammortize cost on repeated lookup failures. + // This let's us handle the case of latent caches, by looking up actual results for a namespace on cache miss/no results. + // We track the lookup result here so that for repeated requests, we don't look it up very often. + liveLookupCache *lru.Cache + liveTTL time.Duration + // updatedQuotas holds a cache of quotas that we've updated. This is used to pull the "really latest" during back to + // back quota evaluations that touch the same quota doc. This only works because we can compare etcd resourceVersions + // for the same resource as integers. Before this change: 22 updates with 12 conflicts. after this change: 15 updates with 0 conflicts + updatedQuotas *lru.Cache +} + +// newQuotaAccessor creates an object that conforms to the QuotaAccessor interface to be used to retrieve quota objects. +func newQuotaAccessor(client clientset.Interface) (*quotaAccessor, error) { + liveLookupCache, err := lru.New(100) + if err != nil { + return nil, err + } + updatedCache, err := lru.New(100) + if err != nil { + return nil, err + } + lw := &cache.ListWatch{ + ListFunc: func(options api.ListOptions) (runtime.Object, error) { + return client.Core().ResourceQuotas(api.NamespaceAll).List(options) + }, + WatchFunc: func(options api.ListOptions) (watch.Interface, error) { + return client.Core().ResourceQuotas(api.NamespaceAll).Watch(options) + }, + } + indexer, reflector := cache.NewNamespaceKeyedIndexerAndReflector(lw, &api.ResourceQuota{}, 0) + + return "aAccessor{ + client: client, + indexer: indexer, + reflector: reflector, + liveLookupCache: liveLookupCache, + liveTTL: time.Duration(30 * time.Second), + updatedQuotas: updatedCache, + }, nil +} + +// Run begins watching and syncing. +func (e *quotaAccessor) Run(stopCh <-chan struct{}) { + defer utilruntime.HandleCrash() + + e.reflector.RunUntil(stopCh) + + <-stopCh + glog.Infof("Shutting down quota accessor") +} + +func (e *quotaAccessor) UpdateQuotaStatus(newQuota *api.ResourceQuota) error { + updatedQuota, err := e.client.Core().ResourceQuotas(newQuota.Namespace).UpdateStatus(newQuota) + if err != nil { + return err + } + + key := newQuota.Namespace + "/" + newQuota.Name + e.updatedQuotas.Add(key, updatedQuota) + return nil +} + +var etcdVersioner = etcd.APIObjectVersioner{} + +// checkCache compares the passed quota against the value in the look-aside cache and returns the newer +// if the cache is out of date, it deletes the stale entry. This only works because of etcd resourceVersions +// being monotonically increasing integers +func (e *quotaAccessor) checkCache(quota *api.ResourceQuota) *api.ResourceQuota { + key := quota.Namespace + "/" + quota.Name + uncastCachedQuota, ok := e.updatedQuotas.Get(key) + if !ok { + return quota + } + cachedQuota := uncastCachedQuota.(*api.ResourceQuota) + + if etcdVersioner.CompareResourceVersion(quota, cachedQuota) >= 0 { + e.updatedQuotas.Remove(key) + return quota + } + return cachedQuota +} + +func (e *quotaAccessor) GetQuotas(namespace string) ([]api.ResourceQuota, error) { + // determine if there are any quotas in this namespace + // if there are no quotas, we don't need to do anything + items, err := e.indexer.Index("namespace", &api.ResourceQuota{ObjectMeta: api.ObjectMeta{Namespace: namespace, Name: ""}}) + if err != nil { + return nil, fmt.Errorf("Error resolving quota.") + } + + // if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it. + if len(items) == 0 { + lruItemObj, ok := e.liveLookupCache.Get(namespace) + if !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) { + // TODO: If there are multiple operations at the same time and cache has just expired, + // this may cause multiple List operations being issued at the same time. + // If there is already in-flight List() for a given namespace, we should wait until + // it is finished and cache is updated instead of doing the same, also to avoid + // throttling - see #22422 for details. + liveList, err := e.client.Core().ResourceQuotas(namespace).List(api.ListOptions{}) + if err != nil { + return nil, err + } + newEntry := liveLookupEntry{expiry: time.Now().Add(e.liveTTL)} + for i := range liveList.Items { + newEntry.items = append(newEntry.items, &liveList.Items[i]) + } + e.liveLookupCache.Add(namespace, newEntry) + lruItemObj = newEntry + } + lruEntry := lruItemObj.(liveLookupEntry) + for i := range lruEntry.items { + items = append(items, lruEntry.items[i]) + } + } + + resourceQuotas := []api.ResourceQuota{} + for i := range items { + quota := items[i].(*api.ResourceQuota) + quota = e.checkCache(quota) + // always make a copy. We're going to muck around with this and we should never mutate the originals + resourceQuotas = append(resourceQuotas, *quota) + } + + return resourceQuotas, nil +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy/admission.go index e3bc36805bb9..aa61609c1c1f 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/security/podsecuritypolicy/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny/admission.go index c7fa3901695b..941a277cf782 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/securitycontext/scdeny/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/admission.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/admission.go index 82e1bfacca37..c61ba2d57624 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/admission.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/admission.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/doc.go index 50a8b061498f..54d763bb9095 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/admission/serviceaccount/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/doc.go index d4b0f43cbbf0..6f6a93034c49 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/keystone.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/keystone.go index 6a7c8c8014c9..2ba449edeb0d 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/keystone.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/keystone/keystone.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/passwordfile/passwordfile.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/passwordfile/passwordfile.go index 8daf1efb3619..2042416840c0 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/passwordfile/passwordfile.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/password/passwordfile/passwordfile.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/basicauth/basicauth.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/basicauth/basicauth.go index 62d78a7254ec..a43a751b5e51 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/basicauth/basicauth.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/basicauth/basicauth.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union/union.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union/union.go index c0b8a0b9a202..5c34b4d5fcd4 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union/union.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/union/union.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/doc.go index 6c92c97837fa..570c1ac59902 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/x509.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/x509.go index 310898dd8474..827df5a1b430 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/x509.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/request/x509/x509.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package x509 import ( "crypto/x509" + "encoding/asn1" "net/http" "k8s.io/kubernetes/pkg/auth/user" @@ -104,7 +105,13 @@ var DNSNameUserConversion = UserConversionFunc(func(chain []*x509.Certificate) ( // EmailAddressUserConversion builds user info from a certificate chain using the first EmailAddress on the certificate var EmailAddressUserConversion = UserConversionFunc(func(chain []*x509.Certificate) (user.Info, bool, error) { + var emailAddressOID asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 9, 1} if len(chain[0].EmailAddresses) == 0 { + for _, name := range chain[0].Subject.Names { + if name.Type.Equal(emailAddressOID) { + return &user.DefaultInfo{Name: name.Value.(string)}, true, nil + } + } return nil, false, nil } return &user.DefaultInfo{Name: chain[0].EmailAddresses[0]}, true, nil diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/oidc/oidc.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/oidc/oidc.go index 7b1741180f00..4a0e191ca9b1 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/oidc/oidc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/oidc/oidc.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,16 +14,28 @@ See the License for the specific language governing permissions and limitations under the License. */ -// oidc implements the authenticator.Token interface using the OpenID Connect protocol. +/* +oidc implements the authenticator.Token interface using the OpenID Connect protocol. + + config := oidc.OIDCOptions{ + IssuerURL: "https://accounts.google.com", + ClientID: os.Getenv("GOOGLE_CLIENT_ID"), + UsernameClaim: "email", + } + tokenAuthenticator, err := oidc.New(config) +*/ package oidc import ( "crypto/tls" "crypto/x509" + "errors" "fmt" "net/http" "net/url" - "time" + "strings" + "sync" + "sync/atomic" "github.com/coreos/go-oidc/jose" "github.com/coreos/go-oidc/oidc" @@ -31,43 +43,61 @@ import ( "k8s.io/kubernetes/pkg/auth/user" "k8s.io/kubernetes/pkg/util/crypto" "k8s.io/kubernetes/pkg/util/net" -) - -const ( - DefaultRetries = 5 - DefaultBackoff = time.Second * 3 + "k8s.io/kubernetes/pkg/util/runtime" ) type OIDCOptions struct { - IssuerURL string - ClientID string - CAFile string + // IssuerURL is the URL the provider signs ID Tokens as. This will be the "iss" + // field of all tokens produced by the provider and is used for configuration + // discovery. + // + // The URL is usually the provider's URL without a path, for example + // "https://accounts.google.com" or "https://login.salesforce.com". + // + // The provider must implement configuration discovery. + // See: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig + IssuerURL string + + // ClientID the JWT must be issued for, the "sub" field. This plugin only trusts a single + // client to ensure the plugin can be used with public providers. + // + // The plugin supports the "authorized party" OpenID Connect claim, which allows + // specialized providers to issue tokens to a client for a different client. + // See: https://openid.net/specs/openid-connect-core-1_0.html#IDToken + ClientID string + + // Path to a PEM encoded root certificate of the provider. + CAFile string + + // UsernameClaim is the JWT field to use as the user's username. UsernameClaim string - GroupsClaim string - // 0 disables retry - MaxRetries int - RetryBackoff time.Duration + // GroupsClaim, if specified, causes the OIDCAuthenticator to try to populate the user's + // groups with a ID Token field. If the GrouppClaim field is present in a ID Token the value + // must be a list of strings. + GroupsClaim string } type OIDCAuthenticator struct { - clientConfig oidc.ClientConfig - client *oidc.Client - usernameClaim string - groupsClaim string - stopSyncProvider chan struct{} - maxRetries int - retryBackoff time.Duration + issuerURL string + + trustedClientID string + + usernameClaim string + groupsClaim string + + httpClient *http.Client + + // Contains an *oidc.Client. Do not access directly. Use client() method. + oidcClient atomic.Value + + // Guards the close method and is used to lock during initialization and closing. + mu sync.Mutex + close func() // May be nil } -// New creates a new OpenID Connect client with the given issuerURL and clientID. -// NOTE(yifan): For now we assume the server provides the "jwks_uri" so we don't -// need to manager the key sets by ourselves. +// New creates a token authenticator which validates OpenID Connect ID Tokens. func New(opts OIDCOptions) (*OIDCAuthenticator, error) { - var cfg oidc.ProviderConfig - var err error - var roots *x509.CertPool - url, err := url.Parse(opts.IssuerURL) if err != nil { return nil, err @@ -77,14 +107,18 @@ func New(opts OIDCOptions) (*OIDCAuthenticator, error) { return nil, fmt.Errorf("'oidc-issuer-url' (%q) has invalid scheme (%q), require 'https'", opts.IssuerURL, url.Scheme) } + if opts.UsernameClaim == "" { + return nil, errors.New("no username claim provided") + } + + var roots *x509.CertPool if opts.CAFile != "" { roots, err = crypto.CertPoolFromFile(opts.CAFile) if err != nil { - glog.Errorf("Failed to read the CA file: %v", err) + return nil, fmt.Errorf("Failed to read the CA file: %v", err) } - } - if roots == nil { - glog.Info("No x509 certificates provided, will use host's root CA set") + } else { + glog.Info("OIDC: No x509 certificates provided, will use host's root CA set") } // Copied from http.DefaultTransport. @@ -94,61 +128,86 @@ func New(opts OIDCOptions) (*OIDCAuthenticator, error) { TLSClientConfig: &tls.Config{RootCAs: roots}, }) - hc := &http.Client{} - hc.Transport = tr - - maxRetries := opts.MaxRetries - if maxRetries < 0 { - maxRetries = DefaultRetries + authenticator := &OIDCAuthenticator{ + issuerURL: opts.IssuerURL, + trustedClientID: opts.ClientID, + usernameClaim: opts.UsernameClaim, + groupsClaim: opts.GroupsClaim, + httpClient: &http.Client{Transport: tr}, } - retryBackoff := opts.RetryBackoff - if retryBackoff < 0 { - retryBackoff = DefaultBackoff + + // Attempt to initialize the authenticator asynchronously. + // + // Ignore errors instead of returning it since the OpenID Connect provider might not be + // available yet, for instance if it's running on the cluster and needs the API server + // to come up first. Errors will be logged within the client() method. + go func() { + defer runtime.HandleCrash() + authenticator.client() + }() + + return authenticator, nil +} + +// Close stops all goroutines used by the authenticator. +func (a *OIDCAuthenticator) Close() { + a.mu.Lock() + defer a.mu.Unlock() + + if a.close != nil { + a.close() } + return +} - for i := 0; i <= maxRetries; i++ { - if i == maxRetries { - return nil, fmt.Errorf("failed to fetch provider config after %v retries", maxRetries) - } +func (a *OIDCAuthenticator) client() (*oidc.Client, error) { + // Fast check to see if client has already been initialized. + if client := a.oidcClient.Load(); client != nil { + return client.(*oidc.Client), nil + } - cfg, err = oidc.FetchProviderConfig(hc, opts.IssuerURL) - if err == nil { - break - } - glog.Errorf("Failed to fetch provider config, trying again in %v: %v", retryBackoff, err) - time.Sleep(retryBackoff) + // Acquire lock, then recheck initialization. + a.mu.Lock() + defer a.mu.Unlock() + if client := a.oidcClient.Load(); client != nil { + return client.(*oidc.Client), nil } - glog.Infof("Fetched provider config from %s: %#v", opts.IssuerURL, cfg) + // Try to initialize client. + providerConfig, err := oidc.FetchProviderConfig(a.httpClient, strings.TrimSuffix(a.issuerURL, "/")) + if err != nil { + glog.Errorf("oidc authenticator: failed to fetch provider discovery data: %v", err) + return nil, fmt.Errorf("fetch provider config: %v", err) + } - ccfg := oidc.ClientConfig{ - HTTPClient: hc, - Credentials: oidc.ClientCredentials{ID: opts.ClientID}, - ProviderConfig: cfg, + clientConfig := oidc.ClientConfig{ + HTTPClient: a.httpClient, + Credentials: oidc.ClientCredentials{ID: a.trustedClientID}, + ProviderConfig: providerConfig, } - client, err := oidc.NewClient(ccfg) + client, err := oidc.NewClient(clientConfig) if err != nil { - return nil, err + glog.Errorf("oidc authenticator: failed to create client: %v", err) + return nil, fmt.Errorf("create client: %v", err) } // SyncProviderConfig will start a goroutine to periodically synchronize the provider config. - // The synchronization interval is set by the expiration length of the config, and has a mininum + // The synchronization interval is set by the expiration length of the config, and has a minimum // and maximum threshold. - stop := client.SyncProviderConfig(opts.IssuerURL) - - return &OIDCAuthenticator{ - ccfg, - client, - opts.UsernameClaim, - opts.GroupsClaim, - stop, - maxRetries, - retryBackoff, - }, nil + stop := client.SyncProviderConfig(a.issuerURL) + a.oidcClient.Store(client) + a.close = func() { + // This assumes the stop is an unbuffered channel. + // So instead of closing the channel, we send am empty struct here. + // This guarantees that when this function returns, there is no flying requests, + // because a send to an unbuffered channel happens after the receive from the channel. + stop <- struct{}{} + } + return client, nil } -// AuthenticateToken decodes and verifies a JWT using the OIDC client, if the verification succeeds, +// AuthenticateToken decodes and verifies a ID Token using the OIDC client, if the verification succeeds, // then it will extract the user info from the JWT claims. func (a *OIDCAuthenticator) AuthenticateToken(value string) (user.Info, bool, error) { jwt, err := jose.ParseJWT(value) @@ -156,7 +215,11 @@ func (a *OIDCAuthenticator) AuthenticateToken(value string) (user.Info, bool, er return nil, false, err } - if err := a.client.VerifyJWT(jwt); err != nil { + client, err := a.client() + if err != nil { + return nil, false, err + } + if err := client.VerifyJWT(jwt); err != nil { return nil, false, err } @@ -180,7 +243,7 @@ func (a *OIDCAuthenticator) AuthenticateToken(value string) (user.Info, bool, er username = claim default: // For all other cases, use issuerURL + claim as the user name. - username = fmt.Sprintf("%s#%s", a.clientConfig.ProviderConfig.Issuer, claim) + username = fmt.Sprintf("%s#%s", a.issuerURL, claim) } // TODO(yifan): Add UID, also populate the issuer to upper layer. @@ -198,12 +261,3 @@ func (a *OIDCAuthenticator) AuthenticateToken(value string) (user.Info, bool, er } return info, true, nil } - -// Close closes the OIDC authenticator, this will close the provider sync goroutine. -func (a *OIDCAuthenticator) Close() { - // This assumes the s.stopSyncProvider is an unbuffered channel. - // So instead of closing the channel, we send am empty struct here. - // This guarantees that when this function returns, there is no flying requests, - // because a send to an unbuffered channel happens after the receive from the channel. - a.stopSyncProvider <- struct{}{} -} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile/tokenfile.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile/tokenfile.go index 52520741e699..24f76da80d81 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile/tokenfile.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/tokenfile/tokenfile.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/webhook/webhook.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/webhook/webhook.go index b6a41083017a..2c55e1b1566c 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/webhook/webhook.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/webhook/webhook.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/rbac.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/rbac.go index a1bf309a39fa..bfcb49d16c19 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/rbac.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/rbac.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import ( "k8s.io/kubernetes/pkg/apis/rbac" "k8s.io/kubernetes/pkg/apis/rbac/validation" "k8s.io/kubernetes/pkg/auth/authorizer" - "k8s.io/kubernetes/pkg/auth/user" "k8s.io/kubernetes/pkg/registry/clusterrole" "k8s.io/kubernetes/pkg/registry/clusterrolebinding" "k8s.io/kubernetes/pkg/registry/role" @@ -35,38 +34,36 @@ type RBACAuthorizer struct { authorizationRuleResolver validation.AuthorizationRuleResolver } -func (r *RBACAuthorizer) Authorize(attr authorizer.Attributes) error { - if r.superUser != "" && attr.GetUserName() == r.superUser { - return nil +func (r *RBACAuthorizer) Authorize(attr authorizer.Attributes) (bool, string, error) { + if r.superUser != "" && attr.GetUser() != nil && attr.GetUser().GetName() == r.superUser { + return true, "", nil } - userInfo := &user.DefaultInfo{ - Name: attr.GetUserName(), - Groups: attr.GetGroups(), - } - - ctx := api.WithNamespace(api.WithUser(api.NewContext(), userInfo), attr.GetNamespace()) + ctx := api.WithNamespace(api.WithUser(api.NewContext(), attr.GetUser()), attr.GetNamespace()) // Frame the authorization request as a privilege escalation check. var requestedRule rbac.PolicyRule if attr.IsResourceRequest() { - resource := attr.GetResource() - if len(attr.GetSubresource()) > 0 { - resource = attr.GetResource() + "/" + attr.GetSubresource() - } requestedRule = rbac.PolicyRule{ Verbs: []string{attr.GetVerb()}, APIGroups: []string{attr.GetAPIGroup()}, // TODO(ericchiang): add api version here too? - Resources: []string{resource}, + Resources: []string{attr.GetResource()}, ResourceNames: []string{attr.GetName()}, } } else { requestedRule = rbac.PolicyRule{ + Verbs: []string{attr.GetVerb()}, NonResourceURLs: []string{attr.GetPath()}, } } - return validation.ConfirmNoEscalation(ctx, r.authorizationRuleResolver, []rbac.PolicyRule{requestedRule}) + // TODO(nhlfr): Try to find more lightweight way to check attributes than escalation checks. + err := validation.ConfirmNoEscalation(ctx, r.authorizationRuleResolver, []rbac.PolicyRule{requestedRule}) + if err != nil { + return false, err.Error(), nil + } + + return true, "", nil } func New(roleRegistry role.Registry, roleBindingRegistry rolebinding.Registry, clusterRoleRegistry clusterrole.Registry, clusterRoleBindingRegistry clusterrolebinding.Registry, superUser string) *RBACAuthorizer { diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/gencerts.sh b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/gencerts.sh index 7983d38796fb..8d7896fa5ee0 100755 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/gencerts.sh +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/gencerts.sh @@ -1,6 +1,6 @@ #!/bin/bash -# Copyright 2016 The Kubernetes Authors All rights reserved. +# Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ outfile=certs_test.go cat > $outfile << EOF /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/webhook.go b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/webhook.go index f4b844ea3879..1b4b463e2d42 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/webhook.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/auth/authorizer/webhook/webhook.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,10 +19,11 @@ package webhook import ( "encoding/json" - "errors" "fmt" "time" + "github.com/golang/glog" + "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/authorization/v1beta1" "k8s.io/kubernetes/pkg/auth/authorizer" @@ -126,13 +127,16 @@ func newWithBackoff(kubeConfigFile string, authorizedTTL, unauthorizedTTL, initi // } // } // -func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (err error) { - r := &v1beta1.SubjectAccessReview{ - Spec: v1beta1.SubjectAccessReviewSpec{ - User: attr.GetUserName(), - Groups: attr.GetGroups(), - }, +func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (authorized bool, reason string, err error) { + r := &v1beta1.SubjectAccessReview{} + if user := attr.GetUser(); user != nil { + r.Spec = v1beta1.SubjectAccessReviewSpec{ + User: user.GetName(), + Groups: user.GetGroups(), + Extra: user.GetExtra(), + } } + if attr.IsResourceRequest() { r.Spec.ResourceAttributes = &v1beta1.ResourceAttributes{ Namespace: attr.GetNamespace(), @@ -151,7 +155,7 @@ func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (err error) { } key, err := json.Marshal(r.Spec) if err != nil { - return err + return false, "", err } if entry, ok := w.responseCache.Get(string(key)); ok { r.Status = entry.(v1beta1.SubjectAccessReviewStatus) @@ -160,14 +164,19 @@ func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (err error) { return w.RestClient.Post().Body(r).Do() }) if err := result.Error(); err != nil { - return err + // An error here indicates bad configuration or an outage. Log for debugging. + glog.Errorf("Failed to make webhook authorizer request: %v", err) + return false, "", err } var statusCode int - if result.StatusCode(&statusCode); statusCode < 200 || statusCode >= 300 { - return fmt.Errorf("Error contacting webhook: %d", statusCode) + result.StatusCode(&statusCode) + switch { + case statusCode < 200, + statusCode >= 300: + return false, "", fmt.Errorf("Error contacting webhook: %d", statusCode) } if err := result.Into(r); err != nil { - return err + return false, "", err } if r.Status.Allowed { w.responseCache.Add(string(key), r.Status, w.authorizedTTL) @@ -175,11 +184,5 @@ func (w *WebhookAuthorizer) Authorize(attr authorizer.Attributes) (err error) { w.responseCache.Add(string(key), r.Status, w.unauthorizedTTL) } } - if r.Status.Allowed { - return nil - } - if r.Status.Reason != "" { - return errors.New(r.Status.Reason) - } - return errors.New("unauthorized") + return r.Status.Allowed, r.Status.Reason, nil } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/gcp/gcp.go b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/gcp/gcp.go index 1efbb20f11a6..32cbb3625504 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/gcp/gcp.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/gcp/gcp.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/oidc/oidc.go b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/oidc/oidc.go index 3ad279c106e9..690a452307f4 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/oidc/oidc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/oidc/oidc.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/plugins.go b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/plugins.go index 2b422ddda023..17d3ad427888 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/plugins.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/client/auth/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/doc.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/doc.go index 6a23039404e4..6d63763f42e4 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/doc.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/listers.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/listers.go index 7db0e8bebc7f..3aea446c3087 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/listers.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/listers.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,20 +27,23 @@ import ( // NodeLister interface represents anything that can list nodes for a scheduler. type NodeLister interface { - List() (list api.NodeList, err error) + // We explicitly return []*api.Node, instead of api.NodeList, to avoid + // performing expensive copies that are unneded. + List() ([]*api.Node, error) } // FakeNodeLister implements NodeLister on a []string for test purposes. -type FakeNodeLister api.NodeList +type FakeNodeLister []*api.Node // List returns nodes as a []string. -func (f FakeNodeLister) List() (api.NodeList, error) { - return api.NodeList(f), nil +func (f FakeNodeLister) List() ([]*api.Node, error) { + return f, nil } // PodLister interface represents anything that can list pods for a scheduler. type PodLister interface { - // TODO: make this exactly the same as client's Pods(ns).List() method, by returning a api.PodList + // We explicitly return []*api.Pod, instead of api.PodList, to avoid + // performing expensive copies that are unneded. List(labels.Selector) ([]*api.Pod, error) } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/error.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/error.go index fd4777ccde86..cd9d8b53823c 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/error.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/error.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ var ( ErrServiceAffinityViolated = newPredicateFailureError("CheckServiceAffinity") ErrMaxVolumeCountExceeded = newPredicateFailureError("MaxVolumeCount") ErrNodeUnderMemoryPressure = newPredicateFailureError("NodeUnderMemoryPressure") + ErrNodeUnderDiskPressure = newPredicateFailureError("NodeUnderDiskPressure") // ErrFakePredicate is used for test only. The fake predicates returning false also returns error // as ErrFakePredicate. ErrFakePredicate = newPredicateFailureError("FakePredicateError") diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/predicates.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/predicates.go index ecc0caee9014..cfd54147b800 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/predicates.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates/predicates.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/client/cache" - qosutil "k8s.io/kubernetes/pkg/kubelet/qos/util" + "k8s.io/kubernetes/pkg/kubelet/qos" "k8s.io/kubernetes/pkg/labels" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" @@ -65,6 +65,25 @@ func (c *CachedNodeInfo) GetNodeInfo(id string) (*api.Node, error) { return node.(*api.Node), nil } +// podMetadata is a type that is passed as metadata for predicate functions +type predicateMetadata struct { + podBestEffort bool + podRequest *schedulercache.Resource + podPorts map[int]bool +} + +func PredicateMetadata(pod *api.Pod) interface{} { + if pod == nil { + // We cannot compute metadata, just return nil + return nil + } + return &predicateMetadata{ + podBestEffort: isPodBestEffort(pod), + podRequest: getResourceRequest(pod), + podPorts: getUsedPorts(pod), + } +} + func isVolumeConflict(volume api.Volume, pod *api.Pod) bool { // fast path if there is no conflict checking targets. if volume.GCEPersistentDisk == nil && volume.AWSElasticBlockStore == nil && volume.RBD == nil { @@ -106,7 +125,7 @@ func isVolumeConflict(volume api.Volume, pod *api.Pod) bool { // - AWS EBS forbids any two pods mounting the same volume ID // - Ceph RBD forbids if any two pods share at least same monitor, and match pool and image. // TODO: migrate this into some per-volume specific code? -func NoDiskConflict(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func NoDiskConflict(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { for _, v := range pod.Spec.Volumes { for _, ev := range nodeInfo.Pods() { if isVolumeConflict(v, ev) { @@ -156,7 +175,7 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace } else if vol.PersistentVolumeClaim != nil { pvcName := vol.PersistentVolumeClaim.ClaimName if pvcName == "" { - return fmt.Errorf("PersistentVolumeClaim had no name: %q", pvcName) + return fmt.Errorf("PersistentVolumeClaim had no name") } pvc, err := c.pvcInfo.GetPersistentVolumeClaimInfo(namespace, pvcName) if err != nil { @@ -169,6 +188,10 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace return nil } + if pvc == nil { + return fmt.Errorf("PersistentVolumeClaim not found: %q", pvcName) + } + pvName := pvc.Spec.VolumeName if pvName == "" { return fmt.Errorf("PersistentVolumeClaim is not bound: %q", pvcName) @@ -186,6 +209,10 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace return nil } + if pv == nil { + return fmt.Errorf("PersistentVolume not found: %q", pvName) + } + if id, ok := c.filter.FilterPersistentVolume(pv); ok { filteredVolumes[id] = true } @@ -195,7 +222,13 @@ func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []api.Volume, namespace return nil } -func (c *MaxPDVolumeCountChecker) predicate(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func (c *MaxPDVolumeCountChecker) predicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + // If a pod doesn't have any volume attached to it, the predicate will always be true. + // Thus we make a fast path for it, to avoid unnecessary computations in this case. + if len(pod.Spec.Volumes) == 0 { + return true, nil + } + newVolumes := make(map[string]bool) if err := c.filterVolumes(pod.Spec.Volumes, pod.Namespace, newVolumes); err != nil { return false, err @@ -293,7 +326,13 @@ func NewVolumeZonePredicate(pvInfo PersistentVolumeInfo, pvcInfo PersistentVolum return c.predicate } -func (c *VolumeZoneChecker) predicate(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func (c *VolumeZoneChecker) predicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + // If a pod doesn't have any volume attached to it, the predicate will always be true. + // Thus we make a fast path for it, to avoid unnecessary computations in this case. + if len(pod.Spec.Volumes) == 0 { + return true, nil + } + node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") @@ -322,7 +361,7 @@ func (c *VolumeZoneChecker) predicate(pod *api.Pod, nodeInfo *schedulercache.Nod if volume.PersistentVolumeClaim != nil { pvcName := volume.PersistentVolumeClaim.ClaimName if pvcName == "" { - return false, fmt.Errorf("PersistentVolumeClaim had no name: %q", pvcName) + return false, fmt.Errorf("PersistentVolumeClaim had no name") } pvc, err := c.pvcInfo.GetPersistentVolumeClaimInfo(namespace, pvcName) if err != nil { @@ -363,107 +402,72 @@ func (c *VolumeZoneChecker) predicate(pod *api.Pod, nodeInfo *schedulercache.Nod return true, nil } -type resourceRequest struct { - milliCPU int64 - memory int64 - nvidiaGPU int64 -} - -func getResourceRequest(pod *api.Pod) resourceRequest { - result := resourceRequest{} +func getResourceRequest(pod *api.Pod) *schedulercache.Resource { + result := schedulercache.Resource{} for _, container := range pod.Spec.Containers { requests := container.Resources.Requests - result.memory += requests.Memory().Value() - result.milliCPU += requests.Cpu().MilliValue() - result.nvidiaGPU += requests.NvidiaGPU().Value() + result.Memory += requests.Memory().Value() + result.MilliCPU += requests.Cpu().MilliValue() + result.NvidiaGPU += requests.NvidiaGPU().Value() } // take max_resource(sum_pod, any_init_container) for _, container := range pod.Spec.InitContainers { requests := container.Resources.Requests - if mem := requests.Memory().Value(); mem > result.memory { - result.memory = mem - } - if cpu := requests.Cpu().MilliValue(); cpu > result.milliCPU { - result.milliCPU = cpu - } - } - return result -} - -func CheckPodsExceedingFreeResources(pods []*api.Pod, allocatable api.ResourceList) (fitting []*api.Pod, notFittingCPU, notFittingMemory, notFittingNvidiaGPU []*api.Pod) { - totalMilliCPU := allocatable.Cpu().MilliValue() - totalMemory := allocatable.Memory().Value() - totalNvidiaGPU := allocatable.NvidiaGPU().Value() - milliCPURequested := int64(0) - memoryRequested := int64(0) - nvidiaGPURequested := int64(0) - for _, pod := range pods { - podRequest := getResourceRequest(pod) - fitsCPU := (totalMilliCPU - milliCPURequested) >= podRequest.milliCPU - fitsMemory := (totalMemory - memoryRequested) >= podRequest.memory - fitsNVidiaGPU := (totalNvidiaGPU - nvidiaGPURequested) >= podRequest.nvidiaGPU - if !fitsCPU { - // the pod doesn't fit due to CPU request - notFittingCPU = append(notFittingCPU, pod) - continue + if mem := requests.Memory().Value(); mem > result.Memory { + result.Memory = mem } - if !fitsMemory { - // the pod doesn't fit due to Memory request - notFittingMemory = append(notFittingMemory, pod) - continue - } - if !fitsNVidiaGPU { - // the pod doesn't fit due to NvidiaGPU request - notFittingNvidiaGPU = append(notFittingNvidiaGPU, pod) - continue + if cpu := requests.Cpu().MilliValue(); cpu > result.MilliCPU { + result.MilliCPU = cpu } - // the pod fits - milliCPURequested += podRequest.milliCPU - memoryRequested += podRequest.memory - nvidiaGPURequested += podRequest.nvidiaGPU - fitting = append(fitting, pod) } - return + return &result } func podName(pod *api.Pod) string { return pod.Namespace + "/" + pod.Name } -func PodFitsResources(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func PodFitsResources(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") } - allocatable := node.Status.Allocatable - allowedPodNumber := allocatable.Pods().Value() - if int64(len(nodeInfo.Pods()))+1 > allowedPodNumber { + allowedPodNumber := nodeInfo.AllowedPodNumber() + if len(nodeInfo.Pods())+1 > allowedPodNumber { return false, - newInsufficientResourceError(podCountResourceName, 1, int64(len(nodeInfo.Pods())), allowedPodNumber) + newInsufficientResourceError(podCountResourceName, 1, int64(len(nodeInfo.Pods())), int64(allowedPodNumber)) } - podRequest := getResourceRequest(pod) - if podRequest.milliCPU == 0 && podRequest.memory == 0 && podRequest.nvidiaGPU == 0 { + + var podRequest *schedulercache.Resource + if predicateMeta, ok := meta.(*predicateMetadata); ok { + podRequest = predicateMeta.podRequest + } else { + // We couldn't parse metadata - fallback to computing it. + podRequest = getResourceRequest(pod) + } + if podRequest.MilliCPU == 0 && podRequest.Memory == 0 && podRequest.NvidiaGPU == 0 { return true, nil } - totalMilliCPU := allocatable.Cpu().MilliValue() - totalMemory := allocatable.Memory().Value() - totalNvidiaGPU := allocatable.NvidiaGPU().Value() - - if totalMilliCPU < podRequest.milliCPU+nodeInfo.RequestedResource().MilliCPU { + allocatable := nodeInfo.AllocatableResource() + if allocatable.MilliCPU < podRequest.MilliCPU+nodeInfo.RequestedResource().MilliCPU { return false, - newInsufficientResourceError(cpuResourceName, podRequest.milliCPU, nodeInfo.RequestedResource().MilliCPU, totalMilliCPU) + newInsufficientResourceError(cpuResourceName, podRequest.MilliCPU, nodeInfo.RequestedResource().MilliCPU, allocatable.MilliCPU) } - if totalMemory < podRequest.memory+nodeInfo.RequestedResource().Memory { + if allocatable.Memory < podRequest.Memory+nodeInfo.RequestedResource().Memory { return false, - newInsufficientResourceError(memoryResourceName, podRequest.memory, nodeInfo.RequestedResource().Memory, totalMemory) + newInsufficientResourceError(memoryResourceName, podRequest.Memory, nodeInfo.RequestedResource().Memory, allocatable.Memory) } - if totalNvidiaGPU < podRequest.nvidiaGPU+nodeInfo.RequestedResource().NvidiaGPU { + if allocatable.NvidiaGPU < podRequest.NvidiaGPU+nodeInfo.RequestedResource().NvidiaGPU { return false, - newInsufficientResourceError(nvidiaGpuResourceName, podRequest.nvidiaGPU, nodeInfo.RequestedResource().NvidiaGPU, totalNvidiaGPU) + newInsufficientResourceError(nvidiaGpuResourceName, podRequest.NvidiaGPU, nodeInfo.RequestedResource().NvidiaGPU, allocatable.NvidiaGPU) + } + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.Infof("Schedule Pod %+v on Node %+v is allowed, Node is running only %v out of %v Pods.", + podName(pod), node.Name, len(nodeInfo.Pods()), allowedPodNumber) } - glog.V(10).Infof("Schedule Pod %+v on Node %+v is allowed, Node is running only %v out of %v Pods.", - podName(pod), node.Name, len(nodeInfo.Pods()), allowedPodNumber) return true, nil } @@ -484,7 +488,7 @@ func nodeMatchesNodeSelectorTerms(node *api.Node, nodeSelectorTerms []api.NodeSe } // The pod can only schedule onto nodes that satisfy requirements in both NodeAffinity and nodeSelector. -func PodMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { +func podMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { // Check if node.Labels match pod.Spec.NodeSelector. if len(pod.Spec.NodeSelector) > 0 { selector := labels.SelectorFromSet(pod.Spec.NodeSelector) @@ -508,7 +512,7 @@ func PodMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { // 5. zero-length non-nil []NodeSelectorRequirement matches no nodes also, just for simplicity // 6. non-nil empty NodeSelectorRequirement is not allowed nodeAffinityMatches := true - if affinity.NodeAffinity != nil { + if affinity != nil && affinity.NodeAffinity != nil { nodeAffinity := affinity.NodeAffinity // if no required NodeAffinity requirements, will do no-op, means select all nodes. // TODO: Replace next line with subsequent commented-out line when implement RequiredDuringSchedulingRequiredDuringExecution. @@ -536,18 +540,18 @@ func PodMatchesNodeLabels(pod *api.Pod, node *api.Node) bool { return nodeAffinityMatches } -func PodSelectorMatches(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func PodSelectorMatches(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") } - if PodMatchesNodeLabels(pod, node) { + if podMatchesNodeLabels(pod, node) { return true, nil } return false, ErrNodeSelectorNotMatch } -func PodFitsHost(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func PodFitsHost(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { if len(pod.Spec.NodeName) == 0 { return true, nil } @@ -586,7 +590,7 @@ func NewNodeLabelPredicate(labels []string, presence bool) algorithm.FitPredicat // Alternately, eliminating nodes that have a certain label, regardless of value, is also useful // A node may have a label with "retiring" as key and the date as the value // and it may be desirable to avoid scheduling new pods on this node -func (n *NodeLabelChecker) CheckNodeLabelPresence(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func (n *NodeLabelChecker) CheckNodeLabelPresence(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") @@ -629,7 +633,12 @@ func NewServiceAffinityPredicate(podLister algorithm.PodLister, serviceLister al // - L is listed in the ServiceAffinity object that is passed into the function // - the pod does not have any NodeSelector for L // - some other pod from the same service is already scheduled onto a node that has value V for label L -func (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + node := nodeInfo.Node() + if node == nil { + return false, fmt.Errorf("node not found") + } + var affinitySelector labels.Selector // check if the pod being scheduled has the affinity labels specified in its NodeSelector @@ -689,11 +698,6 @@ func (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, nodeInfo *scheduler affinitySelector = labels.Set(affinityLabels).AsSelector() } - node := nodeInfo.Node() - if node == nil { - return false, fmt.Errorf("node not found") - } - // check if the node matches the selector if affinitySelector.Matches(labels.Set(node.Labels)) { return true, nil @@ -701,17 +705,22 @@ func (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, nodeInfo *scheduler return false, ErrServiceAffinityViolated } -func PodFitsHostPorts(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { - wantPorts := getUsedPorts(pod) +func PodFitsHostPorts(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + var wantPorts map[int]bool + if predicateMeta, ok := meta.(*predicateMetadata); ok { + wantPorts = predicateMeta.podPorts + } else { + // We couldn't parse metadata - fallback to computing it. + wantPorts = getUsedPorts(pod) + } if len(wantPorts) == 0 { return true, nil } + + // TODO: Aggregate it at the NodeInfo level. existingPorts := getUsedPorts(nodeInfo.Pods()...) for wport := range wantPorts { - if wport == 0 { - continue - } - if existingPorts[wport] { + if wport != 0 && existingPorts[wport] { return false, ErrPodNotFitsHostPorts } } @@ -719,11 +728,12 @@ func PodFitsHostPorts(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, er } func getUsedPorts(pods ...*api.Pod) map[int]bool { - // TODO: Aggregate it at the NodeInfo level. ports := make(map[int]bool) for _, pod := range pods { - for _, container := range pod.Spec.Containers { - for _, podPort := range container.Ports { + for j := range pod.Spec.Containers { + container := &pod.Spec.Containers[j] + for k := range container.Ports { + podPort := &container.Ports[k] // "0" is explicitly ignored in PodFitsHostPorts, // which is the only function that uses this value. if podPort.HostPort != 0 { @@ -747,21 +757,21 @@ func haveSame(a1, a2 []string) bool { return false } -func GeneralPredicates(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { - fit, err := PodFitsResources(pod, nodeInfo) +func GeneralPredicates(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + fit, err := PodFitsResources(pod, meta, nodeInfo) if !fit { return fit, err } - fit, err = PodFitsHost(pod, nodeInfo) + fit, err = PodFitsHost(pod, meta, nodeInfo) if !fit { return fit, err } - fit, err = PodFitsHostPorts(pod, nodeInfo) + fit, err = PodFitsHostPorts(pod, meta, nodeInfo) if !fit { return fit, err } - fit, err = PodSelectorMatches(pod, nodeInfo) + fit, err = PodSelectorMatches(pod, meta, nodeInfo) if !fit { return fit, err } @@ -783,7 +793,7 @@ func NewPodAffinityPredicate(info NodeInfo, podLister algorithm.PodLister, failu return checker.InterPodAffinityMatches } -func (checker *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func (checker *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") @@ -792,40 +802,89 @@ func (checker *PodAffinityChecker) InterPodAffinityMatches(pod *api.Pod, nodeInf if err != nil { return false, err } - if checker.NodeMatchPodAffinityAntiAffinity(pod, allPods, node) { - return true, nil + affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) + if err != nil { + return false, err + } + + // Check if the current node match the inter-pod affinity scheduling constraints. + // Hard inter-pod affinity is not symmetric, check only when affinity.PodAffinity exists. + if affinity != nil && affinity.PodAffinity != nil { + if !checker.NodeMatchesHardPodAffinity(pod, allPods, node, affinity.PodAffinity) { + return false, ErrPodAffinityNotMatch + } + } + + // Hard inter-pod anti-affinity is symmetric, we should always check it + // (also when affinity or affinity.PodAntiAffinity is nil). + var antiAffinity *api.PodAntiAffinity + if affinity != nil { + antiAffinity = affinity.PodAntiAffinity + } + if !checker.NodeMatchesHardPodAntiAffinity(pod, allPods, node, antiAffinity) { + return false, ErrPodAffinityNotMatch } - return false, ErrPodAffinityNotMatch + + return true, nil } // AnyPodMatchesPodAffinityTerm checks if any of given pods can match the specific podAffinityTerm. -func (checker *PodAffinityChecker) AnyPodMatchesPodAffinityTerm(pod *api.Pod, allPods []*api.Pod, node *api.Node, podAffinityTerm api.PodAffinityTerm) (bool, error) { +// First return value indicates whether a matching pod exists on a node that matches the topology key, +// while the second return value indicates whether a matching pod exists anywhere. +// TODO: Do we really need any pod matching, or all pods matching? I think the latter. +func (checker *PodAffinityChecker) AnyPodMatchesPodAffinityTerm(pod *api.Pod, allPods []*api.Pod, node *api.Node, podAffinityTerm api.PodAffinityTerm) (bool, bool, error) { + matchingPodExists := false for _, ep := range allPods { - match, err := checker.failureDomains.CheckIfPodMatchPodAffinityTerm(ep, pod, podAffinityTerm, - func(ep *api.Pod) (*api.Node, error) { return checker.info.GetNodeInfo(ep.Spec.NodeName) }, - func(pod *api.Pod) (*api.Node, error) { return node, nil }, - ) - if err != nil || match { - return match, err + epNode, err := checker.info.GetNodeInfo(ep.Spec.NodeName) + if err != nil { + return false, matchingPodExists, err + } + match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(ep, pod, &podAffinityTerm) + if err != nil { + return false, matchingPodExists, err + } + + if match { + matchingPodExists = true + if checker.failureDomains.NodesHaveSameTopologyKey(node, epNode, podAffinityTerm.TopologyKey) { + return true, matchingPodExists, nil + } + } + } + return false, matchingPodExists, nil +} + +func getPodAffinityTerms(podAffinity *api.PodAffinity) (terms []api.PodAffinityTerm) { + if podAffinity != nil { + if len(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { + terms = podAffinity.RequiredDuringSchedulingIgnoredDuringExecution } + // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. + //if len(podAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { + // terms = append(terms, podAffinity.RequiredDuringSchedulingRequiredDuringExecution...) + //} + } + return terms +} + +func getPodAntiAffinityTerms(podAntiAffinity *api.PodAntiAffinity) (terms []api.PodAffinityTerm) { + if podAntiAffinity != nil { + if len(podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { + terms = podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution + } + // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. + //if len(podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { + // terms = append(terms, podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...) + //} } - return false, nil + return terms } // Checks whether the given node has pods which satisfy all the required pod affinity scheduling rules. // If node has pods which satisfy all the required pod affinity scheduling rules then return true. func (checker *PodAffinityChecker) NodeMatchesHardPodAffinity(pod *api.Pod, allPods []*api.Pod, node *api.Node, podAffinity *api.PodAffinity) bool { - var podAffinityTerms []api.PodAffinityTerm - if len(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { - podAffinityTerms = podAffinity.RequiredDuringSchedulingIgnoredDuringExecution - } - // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. - //if len(podAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { - // podAffinityTerms = append(podAffinityTerms, podAffinity.RequiredDuringSchedulingRequiredDuringExecution...) - //} - - for _, podAffinityTerm := range podAffinityTerms { - podAffinityTermMatches, err := checker.AnyPodMatchesPodAffinityTerm(pod, allPods, node, podAffinityTerm) + for _, podAffinityTerm := range getPodAffinityTerms(podAffinity) { + podAffinityTermMatches, matchingPodExists, err := checker.AnyPodMatchesPodAffinityTerm(pod, allPods, node, podAffinityTerm) if err != nil { glog.V(10).Infof("Cannot schedule pod %+v onto node %v, an error ocurred when checking existing pods on the node for PodAffinityTerm %v err: %v", podName(pod), node.Name, podAffinityTerm, err) @@ -833,31 +892,16 @@ func (checker *PodAffinityChecker) NodeMatchesHardPodAffinity(pod *api.Pod, allP } if !podAffinityTermMatches { - // TODO: Think about whether this can be simplified once we have controllerRef - // Check if it is in special case that the requiredDuringScheduling affinity requirement can be disregarded. // If the requiredDuringScheduling affinity requirement matches a pod's own labels and namespace, and there are no other such pods // anywhere, then disregard the requirement. // This allows rules like "schedule all of the pods of this collection to the same zone" to not block forever // because the first pod of the collection can't be scheduled. - names := priorityutil.GetNamespacesFromPodAffinityTerm(pod, podAffinityTerm) - labelSelector, err := unversioned.LabelSelectorAsSelector(podAffinityTerm.LabelSelector) - if err != nil || !names.Has(pod.Namespace) || !labelSelector.Matches(labels.Set(pod.Labels)) { + match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(pod, pod, &podAffinityTerm) + if err != nil || !match || matchingPodExists { glog.V(10).Infof("Cannot schedule pod %+v onto node %v, because none of the existing pods on this node satisfy the PodAffinityTerm %v, err: %+v", podName(pod), node.Name, podAffinityTerm, err) return false } - - // the affinity is to put the pod together with other pods from its same service or controller - filteredPods := priorityutil.FilterPodsByNameSpaces(names, allPods) - for _, filteredPod := range filteredPods { - // if found an existing pod from same service or RC, - // the affinity scheduling rules cannot be disregarded. - if labelSelector.Matches(labels.Set(filteredPod.Labels)) { - glog.V(10).Infof("Cannot schedule pod %+v onto node %v, because none of the existing pods on this node satisfy the PodAffinityTerm %v", - podName(pod), node.Name, podAffinityTerm) - return false - } - } } } // all the required pod affinity scheduling rules satisfied @@ -873,21 +917,12 @@ func (checker *PodAffinityChecker) NodeMatchesHardPodAffinity(pod *api.Pod, allP // scheduling rules and scheduling the pod onto the node won't // break any existing pods' anti-affinity rules, then return true. func (checker *PodAffinityChecker) NodeMatchesHardPodAntiAffinity(pod *api.Pod, allPods []*api.Pod, node *api.Node, podAntiAffinity *api.PodAntiAffinity) bool { - var podAntiAffinityTerms []api.PodAffinityTerm - if len(podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { - podAntiAffinityTerms = podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution - } - // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. - //if len(podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { - // podAntiAffinityTerms = append(podAntiAffinityTerms, podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...) - //} - // foreach element podAntiAffinityTerm of podAntiAffinityTerms // if the pod matches the term (breaks the anti-affinity), // don't schedule the pod onto this node. - for _, podAntiAffinityTerm := range podAntiAffinityTerms { - podAntiAffinityTermMatches, err := checker.AnyPodMatchesPodAffinityTerm(pod, allPods, node, podAntiAffinityTerm) - if err != nil || podAntiAffinityTermMatches == true { + for _, podAntiAffinityTerm := range getPodAntiAffinityTerms(podAntiAffinity) { + podAntiAffinityTermMatches, _, err := checker.AnyPodMatchesPodAffinityTerm(pod, allPods, node, podAntiAffinityTerm) + if err != nil || podAntiAffinityTermMatches { glog.V(10).Infof("Cannot schedule pod %+v onto node %v, because not all the existing pods on this node satisfy the PodAntiAffinityTerm %v, err: %v", podName(pod), node.Name, podAntiAffinityTerm, err) return false @@ -903,32 +938,24 @@ func (checker *PodAffinityChecker) NodeMatchesHardPodAntiAffinity(pod *api.Pod, glog.V(10).Infof("Failed to get Affinity from Pod %+v, err: %+v", podName(pod), err) return false } - if epAffinity.PodAntiAffinity != nil { - var epAntiAffinityTerms []api.PodAffinityTerm - if len(epAffinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { - epAntiAffinityTerms = epAffinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution + if epAffinity == nil { + continue + } + epNode, err := checker.info.GetNodeInfo(ep.Spec.NodeName) + if err != nil { + glog.V(10).Infof("Failed to get node from Pod %+v, err: %+v", podName(ep), err) + return false + } + for _, epAntiAffinityTerm := range getPodAntiAffinityTerms(epAffinity.PodAntiAffinity) { + match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(pod, ep, &epAntiAffinityTerm) + if err != nil { + glog.V(10).Infof("Failed to get label selector from anti-affinityterm %+v of existing pod %+v, err: %+v", epAntiAffinityTerm, podName(pod), err) + return false } - // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. - //if len(epAffinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { - // epAntiAffinityTerms = append(epAntiAffinityTerms, epAffinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...) - //} - - for _, epAntiAffinityTerm := range epAntiAffinityTerms { - labelSelector, err := unversioned.LabelSelectorAsSelector(epAntiAffinityTerm.LabelSelector) - if err != nil { - glog.V(10).Infof("Failed to get label selector from anti-affinityterm %+v of existing pod %+v, err: %+v", epAntiAffinityTerm, podName(pod), err) - return false - } - - names := priorityutil.GetNamespacesFromPodAffinityTerm(ep, epAntiAffinityTerm) - if (len(names) == 0 || names.Has(pod.Namespace)) && labelSelector.Matches(labels.Set(pod.Labels)) { - epNode, err := checker.info.GetNodeInfo(ep.Spec.NodeName) - if err != nil || checker.failureDomains.NodesHaveSameTopologyKey(node, epNode, epAntiAffinityTerm.TopologyKey) { - glog.V(10).Infof("Cannot schedule Pod %+v, onto node %v because the pod would break the PodAntiAffinityTerm %+v, of existing pod %+v, err: %v", - podName(pod), node.Name, epAntiAffinityTerm, podName(ep), err) - return false - } - } + if match && checker.failureDomains.NodesHaveSameTopologyKey(node, epNode, epAntiAffinityTerm.TopologyKey) { + glog.V(10).Infof("Cannot schedule Pod %+v, onto node %v because the pod would break the PodAntiAffinityTerm %+v, of existing pod %+v, err: %v", + podName(pod), node.Name, epAntiAffinityTerm, podName(ep), err) + return false } } } @@ -937,45 +964,11 @@ func (checker *PodAffinityChecker) NodeMatchesHardPodAntiAffinity(pod *api.Pod, return true } -// NodeMatchPodAffinityAntiAffinity checks if the node matches -// the requiredDuringScheduling affinity/anti-affinity rules indicated by the pod. -func (checker *PodAffinityChecker) NodeMatchPodAffinityAntiAffinity(pod *api.Pod, allPods []*api.Pod, node *api.Node) bool { - // Parse required affinity scheduling rules. - affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) - if err != nil { - glog.V(10).Infof("Failed to get Affinity from Pod %+v, err: %+v", podName(pod), err) - return false - } - - // check if the current node match the inter-pod affinity scheduling rules. - if affinity.PodAffinity != nil { - if !checker.NodeMatchesHardPodAffinity(pod, allPods, node, affinity.PodAffinity) { - return false - } - } - - // check if the current node match the inter-pod anti-affinity scheduling rules. - if affinity.PodAntiAffinity != nil { - if !checker.NodeMatchesHardPodAntiAffinity(pod, allPods, node, affinity.PodAntiAffinity) { - return false - } - } - return true -} - -type TolerationMatch struct { - info NodeInfo -} - -func NewTolerationMatchPredicate(info NodeInfo) algorithm.FitPredicate { - tolerationMatch := &TolerationMatch{ - info: info, - } - return tolerationMatch.PodToleratesNodeTaints -} - -func (t *TolerationMatch) PodToleratesNodeTaints(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func PodToleratesNodeTaints(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() + if node == nil { + return false, fmt.Errorf("node not found") + } taints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) if err != nil { @@ -1004,7 +997,8 @@ func tolerationsToleratesTaints(tolerations []api.Toleration, taints []api.Taint return false } - for _, taint := range taints { + for i := range taints { + taint := &taints[i] // skip taints that have effect PreferNoSchedule, since it is for priorities if taint.Effect == api.TaintEffectPreferNoSchedule { continue @@ -1020,19 +1014,29 @@ func tolerationsToleratesTaints(tolerations []api.Toleration, taints []api.Taint // Determine if a pod is scheduled with best-effort QoS func isPodBestEffort(pod *api.Pod) bool { - return qosutil.GetPodQos(pod) == qosutil.BestEffort + return qos.GetPodQOS(pod) == qos.BestEffort } // CheckNodeMemoryPressurePredicate checks if a pod can be scheduled on a node // reporting memory pressure condition. -func CheckNodeMemoryPressurePredicate(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) { +func CheckNodeMemoryPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { node := nodeInfo.Node() if node == nil { return false, fmt.Errorf("node not found") } + var podBestEffort bool + + predicateMeta, ok := meta.(*predicateMetadata) + if ok { + podBestEffort = predicateMeta.podBestEffort + } else { + // We couldn't parse metadata - fallback to computing it. + podBestEffort = isPodBestEffort(pod) + } + // pod is not BestEffort pod - if !isPodBestEffort(pod) { + if !podBestEffort { return true, nil } @@ -1045,3 +1049,21 @@ func CheckNodeMemoryPressurePredicate(pod *api.Pod, nodeInfo *schedulercache.Nod return true, nil } + +// CheckNodeDiskPressurePredicate checks if a pod can be scheduled on a node +// reporting disk pressure condition. +func CheckNodeDiskPressurePredicate(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) { + node := nodeInfo.Node() + if node == nil { + return false, fmt.Errorf("node not found") + } + + // is node under presure? + for _, cond := range node.Status.Conditions { + if cond.Type == api.NodeDiskPressure && cond.Status == api.ConditionTrue { + return false, ErrNodeUnderDiskPressure + } + } + + return true, nil +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go index c1a84862a019..5889402b2a4f 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/interpod_affinity.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,9 +17,11 @@ limitations under the License. package priorities import ( + "sync" + "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/util/workqueue" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/predicates" priorityutil "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util" @@ -35,7 +37,12 @@ type InterPodAffinity struct { failureDomains priorityutil.Topologies } -func NewInterPodAffinityPriority(info predicates.NodeInfo, nodeLister algorithm.NodeLister, podLister algorithm.PodLister, hardPodAffinityWeight int, failureDomains []string) algorithm.PriorityFunction { +func NewInterPodAffinityPriority( + info predicates.NodeInfo, + nodeLister algorithm.NodeLister, + podLister algorithm.PodLister, + hardPodAffinityWeight int, + failureDomains []string) algorithm.PriorityFunction { interPodAffinity := &InterPodAffinity{ info: info, nodeLister: nodeLister, @@ -46,36 +53,60 @@ func NewInterPodAffinityPriority(info predicates.NodeInfo, nodeLister algorithm. return interPodAffinity.CalculateInterPodAffinityPriority } -// countPodsThatMatchPodAffinityTerm counts the number of given pods that match the podAffinityTerm. -func (ipa *InterPodAffinity) CountPodsThatMatchPodAffinityTerm(pod *api.Pod, podsForMatching []*api.Pod, node *api.Node, podAffinityTerm api.PodAffinityTerm) (int, error) { - matchedCount := 0 - for _, ep := range podsForMatching { - match, err := ipa.failureDomains.CheckIfPodMatchPodAffinityTerm(ep, pod, podAffinityTerm, - func(ep *api.Pod) (*api.Node, error) { - return ipa.info.GetNodeInfo(ep.Spec.NodeName) - }, - func(pod *api.Pod) (*api.Node, error) { - return node, nil - }, - ) - if err != nil { - return 0, err - } - if match { - matchedCount++ - } +type podAffinityPriorityMap struct { + sync.Mutex + + // nodes contain all nodes that should be considered + nodes []*api.Node + // counts store the mapping from node name to so-far computed score of + // the node. + counts map[string]float64 + // failureDomains contain default failure domains keys + failureDomains priorityutil.Topologies + // The first error that we faced. + firstError error +} + +func newPodAffinityPriorityMap(nodes []*api.Node, failureDomains priorityutil.Topologies) *podAffinityPriorityMap { + return &podAffinityPriorityMap{ + nodes: nodes, + counts: make(map[string]float64, len(nodes)), + failureDomains: failureDomains, + } +} + +func (p *podAffinityPriorityMap) setError(err error) { + p.Lock() + defer p.Unlock() + if p.firstError == nil { + p.firstError = err + } +} + +func (p *podAffinityPriorityMap) processTerm(term *api.PodAffinityTerm, podDefiningAffinityTerm, podToCheck *api.Pod, fixedNode *api.Node, weight float64) { + match, err := priorityutil.PodMatchesTermsNamespaceAndSelector(podToCheck, podDefiningAffinityTerm, term) + if err != nil { + p.setError(err) + return + } + if match { + func() { + p.Lock() + defer p.Unlock() + for _, node := range p.nodes { + if p.failureDomains.NodesHaveSameTopologyKey(node, fixedNode, term.TopologyKey) { + p.counts[node.Name] += weight + } + } + }() } - return matchedCount, nil } -// CountWeightByPodMatchAffinityTerm counts the weight to topologyCounts for all the given pods that match the podAffinityTerm. -func (ipa *InterPodAffinity) CountWeightByPodMatchAffinityTerm(pod *api.Pod, podsForMatching []*api.Pod, weight int, podAffinityTerm api.PodAffinityTerm, node *api.Node) (int, error) { - if weight == 0 { - return 0, nil +func (p *podAffinityPriorityMap) processTerms(terms []api.WeightedPodAffinityTerm, podDefiningAffinityTerm, podToCheck *api.Pod, fixedNode *api.Node, multiplier int) { + for i := range terms { + term := &terms[i] + p.processTerm(&term.PodAffinityTerm, podDefiningAffinityTerm, podToCheck, fixedNode, float64(term.Weight*multiplier)) } - // get the pods which are there in that particular node - podsMatchedCount, err := ipa.CountPodsThatMatchPodAffinityTerm(pod, podsForMatching, node, podAffinityTerm) - return weight * podsMatchedCount, err } // compute a sum by iterating through the elements of weightedPodAffinityTerm and adding @@ -83,134 +114,128 @@ func (ipa *InterPodAffinity) CountWeightByPodMatchAffinityTerm(pod *api.Pod, pod // that node; the node(s) with the highest sum are the most preferred. // Symmetry need to be considered for preferredDuringSchedulingIgnoredDuringExecution from podAffinity & podAntiAffinity, // symmetry need to be considered for hard requirements from podAffinity -func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } - allPods, err := ipa.podLister.List(labels.Everything()) - if err != nil { - return nil, err - } +func (ipa *InterPodAffinity) CalculateInterPodAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { return nil, err } + hasAffinityConstraints := affinity != nil && affinity.PodAffinity != nil + hasAntiAffinityConstraints := affinity != nil && affinity.PodAntiAffinity != nil + + allNodeNames := make([]string, 0, len(nodeNameToInfo)) + for name := range nodeNameToInfo { + allNodeNames = append(allNodeNames, name) + } // convert the topology key based weights to the node name based weights - var maxCount int - var minCount int - counts := map[string]int{} - for _, node := range nodes.Items { - totalCount := 0 - // count weights for the weighted pod affinity - if affinity.PodAffinity != nil { - for _, weightedTerm := range affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution { - weightedCount, err := ipa.CountWeightByPodMatchAffinityTerm(pod, allPods, weightedTerm.Weight, weightedTerm.PodAffinityTerm, &node) - if err != nil { - return nil, err - } - totalCount += weightedCount - } + var maxCount float64 + var minCount float64 + // priorityMap stores the mapping from node name to so-far computed score of + // the node. + pm := newPodAffinityPriorityMap(nodes, ipa.failureDomains) + + processPod := func(existingPod *api.Pod) error { + existingPodNode, err := ipa.info.GetNodeInfo(existingPod.Spec.NodeName) + if err != nil { + return err + } + existingPodAffinity, err := api.GetAffinityFromPodAnnotations(existingPod.Annotations) + if err != nil { + return err + } + existingHasAffinityConstraints := existingPodAffinity != nil && existingPodAffinity.PodAffinity != nil + existingHasAntiAffinityConstraints := existingPodAffinity != nil && existingPodAffinity.PodAntiAffinity != nil + + if hasAffinityConstraints { + // For every soft pod affinity term of , if matches the term, + // increment for every node in the cluster with the same + // value as that of `s node by the term`s weight. + terms := affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution + pm.processTerms(terms, pod, existingPod, existingPodNode, 1) + } + if hasAntiAffinityConstraints { + // For every soft pod anti-affinity term of , if matches the term, + // decrement for every node in the cluster with the same + // value as that of `s node by the term`s weight. + terms := affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution + pm.processTerms(terms, pod, existingPod, existingPodNode, -1) } - // count weights for the weighted pod anti-affinity - if affinity.PodAntiAffinity != nil { - for _, weightedTerm := range affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution { - weightedCount, err := ipa.CountWeightByPodMatchAffinityTerm(pod, allPods, (0 - weightedTerm.Weight), weightedTerm.PodAffinityTerm, &node) - if err != nil { - return nil, err + if existingHasAffinityConstraints { + // For every hard pod affinity term of , if matches the term, + // increment for every node in the cluster with the same + // value as that of 's node by the constant + if ipa.hardPodAffinityWeight > 0 { + terms := existingPodAffinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution + // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. + //if len(existingPodAffinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { + // terms = append(terms, existingPodAffinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution...) + //} + for _, term := range terms { + pm.processTerm(&term, existingPod, pod, existingPodNode, float64(ipa.hardPodAffinityWeight)) } - totalCount += weightedCount } + // For every soft pod affinity term of , if matches the term, + // increment for every node in the cluster with the same + // value as that of 's node by the term's weight. + terms := existingPodAffinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution + pm.processTerms(terms, existingPod, pod, existingPodNode, 1) } - - // reverse direction checking: count weights for the inter-pod affinity/anti-affinity rules - // that are indicated by existing pods on the node. - for _, ep := range allPods { - epAffinity, err := api.GetAffinityFromPodAnnotations(ep.Annotations) - if err != nil { - return nil, err - } - - if epAffinity.PodAffinity != nil { - // count the implicit weight for the hard pod affinity indicated by the existing pod. - if ipa.hardPodAffinityWeight > 0 { - var podAffinityTerms []api.PodAffinityTerm - if len(epAffinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 { - podAffinityTerms = epAffinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution - } - // TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution. - //if len(affinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 { - // podAffinityTerms = append(podAffinityTerms, affinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution...) - //} - for _, epAffinityTerm := range podAffinityTerms { - match, err := ipa.failureDomains.CheckIfPodMatchPodAffinityTerm(pod, ep, epAffinityTerm, - func(pod *api.Pod) (*api.Node, error) { return &node, nil }, - func(ep *api.Pod) (*api.Node, error) { return ipa.info.GetNodeInfo(ep.Spec.NodeName) }, - ) - if err != nil { - return nil, err - } - if match { - totalCount += ipa.hardPodAffinityWeight - } - } - } - - // count weight for the weighted pod affinity indicated by the existing pod. - for _, epWeightedTerm := range epAffinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution { - match, err := ipa.failureDomains.CheckIfPodMatchPodAffinityTerm(pod, ep, epWeightedTerm.PodAffinityTerm, - func(pod *api.Pod) (*api.Node, error) { return &node, nil }, - func(ep *api.Pod) (*api.Node, error) { return ipa.info.GetNodeInfo(ep.Spec.NodeName) }, - ) - if err != nil { - return nil, err - } - if match { - totalCount += epWeightedTerm.Weight - } + if existingHasAntiAffinityConstraints { + // For every soft pod anti-affinity term of , if matches the term, + // decrement for every node in the cluster with the same + // value as that of 's node by the term's weight. + terms := existingPodAffinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution + pm.processTerms(terms, existingPod, pod, existingPodNode, -1) + } + return nil + } + processNode := func(i int) { + nodeInfo := nodeNameToInfo[allNodeNames[i]] + if hasAffinityConstraints || hasAntiAffinityConstraints { + // We need to process all the nodes. + for _, existingPod := range nodeInfo.Pods() { + if err := processPod(existingPod); err != nil { + pm.setError(err) } } - - // count weight for the weighted pod anti-affinity indicated by the existing pod. - if epAffinity.PodAntiAffinity != nil { - for _, epWeightedTerm := range epAffinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution { - match, err := ipa.failureDomains.CheckIfPodMatchPodAffinityTerm(pod, ep, epWeightedTerm.PodAffinityTerm, - func(pod *api.Pod) (*api.Node, error) { return &node, nil }, - func(ep *api.Pod) (*api.Node, error) { return ipa.info.GetNodeInfo(ep.Spec.NodeName) }, - ) - if err != nil { - return nil, err - } - if match { - totalCount -= epWeightedTerm.Weight - } + } else { + // The pod doesn't have any constraints - we need to check only existing + // ones that have some. + for _, existingPod := range nodeInfo.PodsWithAffinity() { + if err := processPod(existingPod); err != nil { + pm.setError(err) } } } + } + workqueue.Parallelize(16, len(allNodeNames), processNode) + if pm.firstError != nil { + return nil, pm.firstError + } - counts[node.Name] = totalCount - if counts[node.Name] > maxCount { - maxCount = counts[node.Name] + for _, node := range nodes { + if pm.counts[node.Name] > maxCount { + maxCount = pm.counts[node.Name] } - if counts[node.Name] < minCount { - minCount = counts[node.Name] + if pm.counts[node.Name] < minCount { + minCount = pm.counts[node.Name] } } // calculate final priority score for each node - result := []schedulerapi.HostPriority{} - for _, node := range nodes.Items { + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { fScore := float64(0) if (maxCount - minCount) > 0 { - fScore = 10 * (float64(counts[node.Name]-minCount) / float64(maxCount-minCount)) + fScore = 10 * ((pm.counts[node.Name] - minCount) / (maxCount - minCount)) } result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) - glog.V(10).Infof( - "%v -> %v: InterPodAffinityPriority, Score: (%d)", pod.Name, node.Name, int(fScore), - ) + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.V(10).Infof("%v -> %v: InterPodAffinityPriority, Score: (%d)", pod.Name, node.Name, int(fScore)) + } } - return result, nil } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go index e511c4002163..97a2c9b65443 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/node_affinity.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,35 +20,18 @@ import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -type NodeAffinity struct { - nodeLister algorithm.NodeLister -} - -func NewNodeAffinityPriority(nodeLister algorithm.NodeLister) algorithm.PriorityFunction { - nodeAffinity := &NodeAffinity{ - nodeLister: nodeLister, - } - return nodeAffinity.CalculateNodeAffinityPriority -} - // CalculateNodeAffinityPriority prioritizes nodes according to node affinity scheduling preferences // indicated in PreferredDuringSchedulingIgnoredDuringExecution. Each time a node match a preferredSchedulingTerm, // it will a get an add of preferredSchedulingTerm.Weight. Thus, the more preferredSchedulingTerms // the node satisfies and the more the preferredSchedulingTerm that is satisfied weights, the higher // score the node gets. -func (s *NodeAffinity) CalculateNodeAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - var maxCount int - counts := map[string]int{} - - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } +func CalculateNodeAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + var maxCount float64 + counts := make(map[string]float64, len(nodes)) affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) if err != nil { @@ -58,7 +41,7 @@ func (s *NodeAffinity) CalculateNodeAffinityPriority(pod *api.Pod, nodeNameToInf // A nil element of PreferredDuringSchedulingIgnoredDuringExecution matches no objects. // An element of PreferredDuringSchedulingIgnoredDuringExecution that refers to an // empty PreferredSchedulingTerm matches all objects. - if affinity.NodeAffinity != nil && affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil { + if affinity != nil && affinity.NodeAffinity != nil && affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil { // Match PreferredDuringSchedulingIgnoredDuringExecution term by term. for _, preferredSchedulingTerm := range affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution { if preferredSchedulingTerm.Weight == 0 { @@ -70,9 +53,9 @@ func (s *NodeAffinity) CalculateNodeAffinityPriority(pod *api.Pod, nodeNameToInf return nil, err } - for _, node := range nodes.Items { + for _, node := range nodes { if nodeSelector.Matches(labels.Set(node.Labels)) { - counts[node.Name] += int(preferredSchedulingTerm.Weight) + counts[node.Name] += float64(preferredSchedulingTerm.Weight) } if counts[node.Name] > maxCount { @@ -82,14 +65,19 @@ func (s *NodeAffinity) CalculateNodeAffinityPriority(pod *api.Pod, nodeNameToInf } } - result := []schedulerapi.HostPriority{} - for _, node := range nodes.Items { - fScore := float64(0) + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { if maxCount > 0 { - fScore = 10 * (float64(counts[node.Name]) / float64(maxCount)) + fScore := 10 * (counts[node.Name] / maxCount) + result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.Infof("%v -> %v: NodeAffinityPriority, Score: (%d)", pod.Name, node.Name, int(fScore)) + } + } else { + result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: 0}) } - result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) - glog.V(10).Infof("%v -> %v: NodeAffinityPriority, Score: (%d)", pod.Name, node.Name, int(fScore)) } return result, nil } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/priorities.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/priorities.go index bd03178946b0..4862453aeccd 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/priorities.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/priorities.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -28,9 +28,20 @@ import ( "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) +func getNonZeroRequests(pod *api.Pod) *schedulercache.Resource { + result := &schedulercache.Resource{} + for i := range pod.Spec.Containers { + container := &pod.Spec.Containers[i] + cpu, memory := priorityutil.GetNonzeroRequests(&container.Resources.Requests) + result.MilliCPU += cpu + result.Memory += memory + } + return result +} + // the unused capacity is calculated on a scale of 0-10 // 0 being the lowest priority and 10 being the highest -func calculateScore(requested int64, capacity int64, node string) int { +func calculateScore(requested int64, capacity int64, node string) int64 { if capacity == 0 { return 0 } @@ -39,35 +50,32 @@ func calculateScore(requested int64, capacity int64, node string) int { requested, capacity, node) return 0 } - return int(((capacity - requested) * 10) / capacity) + return ((capacity - requested) * 10) / capacity } // Calculate the resource occupancy on a node. 'node' has information about the resources on the node. // 'pods' is a list of pods currently scheduled on the node. -func calculateResourceOccupancy(pod *api.Pod, node api.Node, nodeInfo *schedulercache.NodeInfo) schedulerapi.HostPriority { - totalMilliCPU := nodeInfo.NonZeroRequest().MilliCPU - totalMemory := nodeInfo.NonZeroRequest().Memory - capacityMilliCPU := node.Status.Allocatable.Cpu().MilliValue() - capacityMemory := node.Status.Allocatable.Memory().Value() - - // Add the resources requested by the current pod being scheduled. - // This also helps differentiate between differently sized, but empty, nodes. - for _, container := range pod.Spec.Containers { - cpu, memory := priorityutil.GetNonzeroRequests(&container.Resources.Requests) - totalMilliCPU += cpu - totalMemory += memory +// TODO: Use Node() from nodeInfo instead of passing it. +func calculateResourceOccupancy(pod *api.Pod, podRequests *schedulercache.Resource, node *api.Node, nodeInfo *schedulercache.NodeInfo) schedulerapi.HostPriority { + allocatableResources := nodeInfo.AllocatableResource() + totalResources := *podRequests + totalResources.MilliCPU += nodeInfo.NonZeroRequest().MilliCPU + totalResources.Memory += nodeInfo.NonZeroRequest().Memory + + cpuScore := calculateScore(totalResources.MilliCPU, allocatableResources.MilliCPU, node.Name) + memoryScore := calculateScore(totalResources.Memory, allocatableResources.Memory, node.Name) + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.V(10).Infof( + "%v -> %v: Least Requested Priority, capacity %d millicores %d memory bytes, total request %d millicores %d memory bytes, score %d CPU %d memory", + pod.Name, node.Name, + allocatableResources.MilliCPU, allocatableResources.Memory, + totalResources.MilliCPU, totalResources.Memory, + cpuScore, memoryScore, + ) } - cpuScore := calculateScore(totalMilliCPU, capacityMilliCPU, node.Name) - memoryScore := calculateScore(totalMemory, capacityMemory, node.Name) - glog.V(10).Infof( - "%v -> %v: Least Requested Priority, capacity %d millicores %d memory bytes, total request %d millicores %d memory bytes, score %d CPU %d memory", - pod.Name, node.Name, - capacityMilliCPU, capacityMemory, - totalMilliCPU, totalMemory, - cpuScore, memoryScore, - ) - return schedulerapi.HostPriority{ Host: node.Name, Score: int((cpuScore + memoryScore) / 2), @@ -78,15 +86,11 @@ func calculateResourceOccupancy(pod *api.Pod, node api.Node, nodeInfo *scheduler // It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes // based on the minimum of the average of the fraction of requested to capacity. // Details: cpu((capacity - sum(requested)) * 10 / capacity) + memory((capacity - sum(requested)) * 10 / capacity) / 2 -func LeastRequestedPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - nodes, err := nodeLister.List() - if err != nil { - return schedulerapi.HostPriorityList{}, err - } - - list := schedulerapi.HostPriorityList{} - for _, node := range nodes.Items { - list = append(list, calculateResourceOccupancy(pod, node, nodeNameToInfo[node.Name])) +func LeastRequestedPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + podResources := getNonZeroRequests(pod) + list := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { + list = append(list, calculateResourceOccupancy(pod, podResources, node, nodeNameToInfo[node.Name])) } return list, nil } @@ -107,20 +111,15 @@ func NewNodeLabelPriority(label string, presence bool) algorithm.PriorityFunctio // CalculateNodeLabelPriority checks whether a particular label exists on a node or not, regardless of its value. // If presence is true, prioritizes nodes that have the specified label, regardless of value. // If presence is false, prioritizes nodes that do not have the specified label. -func (n *NodeLabelPrioritizer) CalculateNodeLabelPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { +func (n *NodeLabelPrioritizer) CalculateNodeLabelPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { var score int - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } - labeledNodes := map[string]bool{} - for _, node := range nodes.Items { + for _, node := range nodes { exists := labels.Set(node.Labels).Has(n.label) labeledNodes[node.Name] = (exists && n.presence) || (!exists && !n.presence) } - result := []schedulerapi.HostPriority{} + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) //score int - scale of 0-10 // 0 being the lowest priority and 10 being the highest for nodeName, success := range labeledNodes { @@ -146,24 +145,18 @@ const ( // based on the total size of those images. // - If none of the images are present, this node will be given the lowest priority. // - If some of the images are present on a node, the larger their sizes' sum, the higher the node's priority. -func ImageLocalityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { +func ImageLocalityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { sumSizeMap := make(map[string]int64) - - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } - - for _, container := range pod.Spec.Containers { - for _, node := range nodes.Items { + for i := range pod.Spec.Containers { + for _, node := range nodes { // Check if this container's image is present and get its size. - imageSize := checkContainerImageOnNode(node, container) + imageSize := checkContainerImageOnNode(node, &pod.Spec.Containers[i]) // Add this size to the total result of this node. sumSizeMap[node.Name] += imageSize } } - result := []schedulerapi.HostPriority{} + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) // score int - scale of 0-10 // 0 being the lowest priority and 10 being the highest. for nodeName, sumSize := range sumSizeMap { @@ -174,7 +167,7 @@ func ImageLocalityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercac } // checkContainerImageOnNode checks if a container image is present on a node and returns its size. -func checkContainerImageOnNode(node api.Node, container api.Container) int64 { +func checkContainerImageOnNode(node *api.Node, container *api.Container) int64 { for _, image := range node.Status.Images { for _, name := range image.Names { if container.Image == name { @@ -212,36 +205,25 @@ func calculateScoreFromSize(sumSize int64) int { // close the two metrics are to each other. // Detail: score = 10 - abs(cpuFraction-memoryFraction)*10. The algorithm is partly inspired by: // "Wei Huang et al. An Energy Efficient Virtual Machine Placement Algorithm with Balanced Resource Utilization" -func BalancedResourceAllocation(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - nodes, err := nodeLister.List() - if err != nil { - return schedulerapi.HostPriorityList{}, err - } - - list := schedulerapi.HostPriorityList{} - for _, node := range nodes.Items { - list = append(list, calculateBalancedResourceAllocation(pod, node, nodeNameToInfo[node.Name])) +func BalancedResourceAllocation(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + podResources := getNonZeroRequests(pod) + list := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { + list = append(list, calculateBalancedResourceAllocation(pod, podResources, node, nodeNameToInfo[node.Name])) } return list, nil } -func calculateBalancedResourceAllocation(pod *api.Pod, node api.Node, nodeInfo *schedulercache.NodeInfo) schedulerapi.HostPriority { - totalMilliCPU := nodeInfo.NonZeroRequest().MilliCPU - totalMemory := nodeInfo.NonZeroRequest().Memory - score := int(0) - // Add the resources requested by the current pod being scheduled. - // This also helps differentiate between differently sized, but empty, nodes. - for _, container := range pod.Spec.Containers { - cpu, memory := priorityutil.GetNonzeroRequests(&container.Resources.Requests) - totalMilliCPU += cpu - totalMemory += memory - } - - capacityMilliCPU := node.Status.Allocatable.Cpu().MilliValue() - capacityMemory := node.Status.Allocatable.Memory().Value() +// TODO: Use Node() from nodeInfo instead of passing it. +func calculateBalancedResourceAllocation(pod *api.Pod, podRequests *schedulercache.Resource, node *api.Node, nodeInfo *schedulercache.NodeInfo) schedulerapi.HostPriority { + allocatableResources := nodeInfo.AllocatableResource() + totalResources := *podRequests + totalResources.MilliCPU += nodeInfo.NonZeroRequest().MilliCPU + totalResources.Memory += nodeInfo.NonZeroRequest().Memory - cpuFraction := fractionOfCapacity(totalMilliCPU, capacityMilliCPU) - memoryFraction := fractionOfCapacity(totalMemory, capacityMemory) + cpuFraction := fractionOfCapacity(totalResources.MilliCPU, allocatableResources.MilliCPU) + memoryFraction := fractionOfCapacity(totalResources.Memory, allocatableResources.Memory) + score := int(0) if cpuFraction >= 1 || memoryFraction >= 1 { // if requested >= capacity, the corresponding host should never be preferrred. score = 0 @@ -253,13 +235,17 @@ func calculateBalancedResourceAllocation(pod *api.Pod, node api.Node, nodeInfo * diff := math.Abs(cpuFraction - memoryFraction) score = int(10 - diff*10) } - glog.V(10).Infof( - "%v -> %v: Balanced Resource Allocation, capacity %d millicores %d memory bytes, total request %d millicores %d memory bytes, score %d", - pod.Name, node.Name, - capacityMilliCPU, capacityMemory, - totalMilliCPU, totalMemory, - score, - ) + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.V(10).Infof( + "%v -> %v: Balanced Resource Allocation, capacity %d millicores %d memory bytes, total request %d millicores %d memory bytes, score %d", + pod.Name, node.Name, + allocatableResources.MilliCPU, allocatableResources.Memory, + totalResources.MilliCPU, totalResources.Memory, + score, + ) + } return schedulerapi.HostPriority{ Host: node.Name, @@ -273,3 +259,77 @@ func fractionOfCapacity(requested, capacity int64) float64 { } return float64(requested) / float64(capacity) } + +type NodePreferAvoidPod struct { + controllerLister algorithm.ControllerLister + replicaSetLister algorithm.ReplicaSetLister +} + +func NewNodePreferAvoidPodsPriority(controllerLister algorithm.ControllerLister, replicaSetLister algorithm.ReplicaSetLister) algorithm.PriorityFunction { + nodePreferAvoid := &NodePreferAvoidPod{ + controllerLister: controllerLister, + replicaSetLister: replicaSetLister, + } + return nodePreferAvoid.CalculateNodePreferAvoidPodsPriority +} + +func (npa *NodePreferAvoidPod) CalculateNodePreferAvoidPodsPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + // TODO: Once we have ownerReference fully implemented, use it to find controller for the pod. + rcs, _ := npa.controllerLister.GetPodControllers(pod) + rss, _ := npa.replicaSetLister.GetPodReplicaSets(pod) + if len(rcs) == 0 && len(rss) == 0 { + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { + result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: 10}) + } + return result, nil + } + + avoidNodes := make(map[string]bool, len(nodes)) + avoidNode := false + for _, node := range nodes { + avoids, err := api.GetAvoidPodsFromNodeAnnotations(node.Annotations) + if err != nil { + continue + } + + avoidNode = false + for i := range avoids.PreferAvoidPods { + avoid := &avoids.PreferAvoidPods[i] + // TODO: Once we have controllerRef implemented there will be at most one owner + // of our pod. That said we won't even need loop theoretically. That said for + // code simplicity, we can get rid of all breaks. + // Also, we can simply compare fields from ownerRef with avoid. + for _, rc := range rcs { + if avoid.PodSignature.PodController.Kind == "ReplicationController" && avoid.PodSignature.PodController.UID == rc.UID { + avoidNode = true + } + } + for _, rs := range rss { + if avoid.PodSignature.PodController.Kind == "ReplicaSet" && avoid.PodSignature.PodController.UID == rs.UID { + avoidNode = true + } + } + if avoidNode { + // false is default value, so we don't even need to set it + // to avoid unnecessary map operations. + avoidNodes[node.Name] = true + break + } + } + } + + var score int + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) + //score int - scale of 0-10 + // 0 being the lowest priority and 10 being the highest + for _, node := range nodes { + if avoidNodes[node.Name] { + score = 0 + } else { + score = 10 + } + result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: score}) + } + return result, nil +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go index caea010e9c98..c2331f3607d7 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/selector_spreading.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,7 +23,8 @@ import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/labels" - utilruntime "k8s.io/kubernetes/pkg/util/runtime" + utilnode "k8s.io/kubernetes/pkg/util/node" + "k8s.io/kubernetes/pkg/util/workqueue" "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" @@ -31,7 +32,7 @@ import ( // The maximum priority value to give to a node // Prioritiy values range from 0-maxPriority -const maxPriority = 10 +const maxPriority float32 = 10 // When zone information is present, give 2/3 of the weighting to zone spreading, 1/3 to node spreading // TODO: Any way to justify this weighting? @@ -54,49 +55,25 @@ func NewSelectorSpreadPriority(podLister algorithm.PodLister, serviceLister algo return selectorSpread.CalculateSpreadPriority } -// Helper function that builds a string identifier that is unique per failure-zone -// Returns empty-string for no zone -func getZoneKey(node *api.Node) string { - labels := node.Labels - if labels == nil { - return "" - } - - region, _ := labels[unversioned.LabelZoneRegion] - failureDomain, _ := labels[unversioned.LabelZoneFailureDomain] - - if region == "" && failureDomain == "" { - return "" - } - - // We include the null character just in case region or failureDomain has a colon - // (We do assume there's no null characters in a region or failureDomain) - // As a nice side-benefit, the null character is not printed by fmt.Print or glog - return region + ":\x00:" + failureDomain -} - // CalculateSpreadPriority spreads pods across hosts and zones, considering pods belonging to the same service or replication controller. // When a pod is scheduled, it looks for services or RCs that match the pod, then finds existing pods that match those selectors. // It favors nodes that have fewer existing matching pods. // i.e. it pushes the scheduler towards a node where there's the smallest number of // pods which match the same service selectors or RC selectors as the pod being scheduled. // Where zone information is included on the nodes, it favors nodes in zones with fewer existing matching pods. -func (s *SelectorSpread) CalculateSpreadPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - selectors := make([]labels.Selector, 0) - services, err := s.serviceLister.GetPodServices(pod) - if err == nil { +func (s *SelectorSpread) CalculateSpreadPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + selectors := make([]labels.Selector, 0, 3) + if services, err := s.serviceLister.GetPodServices(pod); err == nil { for _, service := range services { selectors = append(selectors, labels.SelectorFromSet(service.Spec.Selector)) } } - rcs, err := s.controllerLister.GetPodControllers(pod) - if err == nil { + if rcs, err := s.controllerLister.GetPodControllers(pod); err == nil { for _, rc := range rcs { selectors = append(selectors, labels.SelectorFromSet(rc.Spec.Selector)) } } - rss, err := s.replicaSetLister.GetPodReplicaSets(pod) - if err == nil { + if rss, err := s.replicaSetLister.GetPodReplicaSets(pod); err == nil { for _, rs := range rss { if selector, err := unversioned.LabelSelectorAsSelector(rs.Spec.Selector); err == nil { selectors = append(selectors, selector) @@ -104,133 +81,91 @@ func (s *SelectorSpread) CalculateSpreadPriority(pod *api.Pod, nodeNameToInfo ma } } - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } - // Count similar pods by node - countsByNodeName := map[string]int{} + countsByNodeName := make(map[string]float32, len(nodes)) + countsByZone := make(map[string]float32, 10) + maxCountByNodeName := float32(0) countsByNodeNameLock := sync.Mutex{} if len(selectors) > 0 { - // Create a number of go-routines that will be computing number - // of "similar" pods for given nodes. - workers := 16 - toProcess := make(chan string, len(nodes.Items)) - for i := range nodes.Items { - toProcess <- nodes.Items[i].Name - } - close(toProcess) - - wg := sync.WaitGroup{} - wg.Add(workers) - for i := 0; i < workers; i++ { - go func() { - defer utilruntime.HandleCrash() - defer wg.Done() - for { - nodeName, ok := <-toProcess - if !ok { - return - } - count := 0 - for _, nodePod := range nodeNameToInfo[nodeName].Pods() { - if pod.Namespace != nodePod.Namespace { - continue - } - // When we are replacing a failed pod, we often see the previous - // deleted version while scheduling the replacement. - // Ignore the previous deleted version for spreading purposes - // (it can still be considered for resource restrictions etc.) - if nodePod.DeletionTimestamp != nil { - glog.V(4).Infof("skipping pending-deleted pod: %s/%s", nodePod.Namespace, nodePod.Name) - continue - } - matches := false - for _, selector := range selectors { - if selector.Matches(labels.Set(nodePod.ObjectMeta.Labels)) { - matches = true - break - } - } - if matches { - count++ - } + processNodeFunc := func(i int) { + nodeName := nodes[i].Name + count := float32(0) + for _, nodePod := range nodeNameToInfo[nodeName].Pods() { + if pod.Namespace != nodePod.Namespace { + continue + } + // When we are replacing a failed pod, we often see the previous + // deleted version while scheduling the replacement. + // Ignore the previous deleted version for spreading purposes + // (it can still be considered for resource restrictions etc.) + if nodePod.DeletionTimestamp != nil { + glog.V(4).Infof("skipping pending-deleted pod: %s/%s", nodePod.Namespace, nodePod.Name) + continue + } + matches := false + for _, selector := range selectors { + if selector.Matches(labels.Set(nodePod.ObjectMeta.Labels)) { + matches = true + break } - - func() { - countsByNodeNameLock.Lock() - defer countsByNodeNameLock.Unlock() - countsByNodeName[nodeName] = count - }() } - }() - } - wg.Wait() - } - - // Aggregate by-node information - // Compute the maximum number of pods hosted on any node - maxCountByNodeName := 0 - for _, count := range countsByNodeName { - if count > maxCountByNodeName { - maxCountByNodeName = count - } - } - - // Count similar pods by zone, if zone information is present - countsByZone := map[string]int{} - for i := range nodes.Items { - node := &nodes.Items[i] - - count, found := countsByNodeName[node.Name] - if !found { - continue - } + if matches { + count++ + } + } + zoneId := utilnode.GetZoneKey(nodes[i]) - zoneId := getZoneKey(node) - if zoneId == "" { - continue + countsByNodeNameLock.Lock() + defer countsByNodeNameLock.Unlock() + countsByNodeName[nodeName] = count + if count > maxCountByNodeName { + maxCountByNodeName = count + } + if zoneId != "" { + countsByZone[zoneId] += count + } } - - countsByZone[zoneId] += count + workqueue.Parallelize(16, len(nodes), processNodeFunc) } // Aggregate by-zone information // Compute the maximum number of pods hosted in any zone haveZones := len(countsByZone) != 0 - maxCountByZone := 0 + maxCountByZone := float32(0) for _, count := range countsByZone { if count > maxCountByZone { maxCountByZone = count } } - result := []schedulerapi.HostPriority{} + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) //score int - scale of 0-maxPriority // 0 being the lowest priority and maxPriority being the highest - for i := range nodes.Items { - node := &nodes.Items[i] + for _, node := range nodes { // initializing to the default/max node score of maxPriority - fScore := float32(maxPriority) + fScore := maxPriority if maxCountByNodeName > 0 { - fScore = maxPriority * (float32(maxCountByNodeName-countsByNodeName[node.Name]) / float32(maxCountByNodeName)) + fScore = maxPriority * ((maxCountByNodeName - countsByNodeName[node.Name]) / maxCountByNodeName) } // If there is zone information present, incorporate it if haveZones { - zoneId := getZoneKey(node) + zoneId := utilnode.GetZoneKey(node) if zoneId != "" { - zoneScore := maxPriority * (float32(maxCountByZone-countsByZone[zoneId]) / float32(maxCountByZone)) + zoneScore := maxPriority * ((maxCountByZone - countsByZone[zoneId]) / maxCountByZone) fScore = (fScore * (1.0 - zoneWeighting)) + (zoneWeighting * zoneScore) } } result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) - glog.V(10).Infof( - "%v -> %v: SelectorSpreadPriority, Score: (%d)", pod.Name, node.Name, int(fScore), - ) + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.V(10).Infof( + "%v -> %v: SelectorSpreadPriority, Score: (%d)", pod.Name, node.Name, int(fScore), + ) + } } return result, nil } @@ -253,11 +188,9 @@ func NewServiceAntiAffinityPriority(podLister algorithm.PodLister, serviceLister // CalculateAntiAffinityPriority spreads pods by minimizing the number of pods belonging to the same service // on machines with the same value for a particular label. // The label to be considered is provided to the struct (ServiceAntiAffinity). -func (s *ServiceAntiAffinity) CalculateAntiAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { +func (s *ServiceAntiAffinity) CalculateAntiAffinityPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { var nsServicePods []*api.Pod - - services, err := s.serviceLister.GetPodServices(pod) - if err == nil { + if services, err := s.serviceLister.GetPodServices(pod); err == nil { // just use the first service and get the other pods within the service // TODO: a separate predicate can be created that tries to handle all services for the pod selector := labels.SelectorFromSet(services[0].Spec.Selector) @@ -273,15 +206,10 @@ func (s *ServiceAntiAffinity) CalculateAntiAffinityPriority(pod *api.Pod, nodeNa } } - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } - // separate out the nodes that have the label from the ones that don't otherNodes := []string{} labeledNodes := map[string]string{} - for _, node := range nodes.Items { + for _, node := range nodes { if labels.Set(node.Labels).Has(s.label) { label := labels.Set(node.Labels).Get(s.label) labeledNodes[node.Name] = label diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go index 35a372d68ee5..b299044d2129 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/taint_toleration.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,27 +19,14 @@ package priorities import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/plugin/pkg/scheduler/algorithm" schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api" "k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache" ) -// NodeTaints hold the node lister -type TaintToleration struct { - nodeLister algorithm.NodeLister -} - -// NewTaintTolerationPriority -func NewTaintTolerationPriority(nodeLister algorithm.NodeLister) algorithm.PriorityFunction { - taintToleration := &TaintToleration{ - nodeLister: nodeLister, - } - return taintToleration.ComputeTaintTolerationPriority -} - // CountIntolerableTaintsPreferNoSchedule gives the count of intolerable taints of a pod with effect PreferNoSchedule -func countIntolerableTaintsPreferNoSchedule(taints []api.Taint, tolerations []api.Toleration) (intolerableTaints int) { - for _, taint := range taints { +func countIntolerableTaintsPreferNoSchedule(taints []api.Taint, tolerations []api.Toleration) (intolerableTaints float64) { + for i := range taints { + taint := &taints[i] // check only on taints that have effect PreferNoSchedule if taint.Effect != api.TaintEffectPreferNoSchedule { continue @@ -54,26 +41,21 @@ func countIntolerableTaintsPreferNoSchedule(taints []api.Taint, tolerations []ap // getAllTolerationEffectPreferNoSchedule gets the list of all Toleration with Effect PreferNoSchedule func getAllTolerationPreferNoSchedule(tolerations []api.Toleration) (tolerationList []api.Toleration) { - for _, toleration := range tolerations { + for i := range tolerations { + toleration := &tolerations[i] if len(toleration.Effect) == 0 || toleration.Effect == api.TaintEffectPreferNoSchedule { - tolerationList = append(tolerationList, toleration) + tolerationList = append(tolerationList, *toleration) } } return } // ComputeTaintTolerationPriority prepares the priority list for all the nodes based on the number of intolerable taints on the node -func (s *TaintToleration) ComputeTaintTolerationPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - // counts hold the count of intolerable taints of a pod for a given node - counts := make(map[string]int) - +func ComputeTaintTolerationPriority(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { // the max value of counts - var maxCount int - - nodes, err := nodeLister.List() - if err != nil { - return nil, err - } + var maxCount float64 + // counts hold the count of intolerable taints of a pod for a given node + counts := make(map[string]float64, len(nodes)) tolerations, err := api.GetTolerationsFromPodAnnotations(pod.Annotations) if err != nil { @@ -83,29 +65,36 @@ func (s *TaintToleration) ComputeTaintTolerationPriority(pod *api.Pod, nodeNameT tolerationList := getAllTolerationPreferNoSchedule(tolerations) // calculate the intolerable taints for all the nodes - for _, node := range nodes.Items { + for _, node := range nodes { taints, err := api.GetTaintsFromNodeAnnotations(node.Annotations) if err != nil { return nil, err } count := countIntolerableTaintsPreferNoSchedule(taints, tolerationList) - counts[node.Name] = count - if count > maxCount { - maxCount = count + if count > 0 { + // 0 is default value, so avoid unnecessary map operations. + counts[node.Name] = count + if count > maxCount { + maxCount = count + } } } // The maximum priority value to give to a node // Priority values range from 0 - maxPriority - const maxPriority = 10 - result := []schedulerapi.HostPriority{} - for _, node := range nodes.Items { - fScore := float64(maxPriority) + const maxPriority = float64(10) + result := make(schedulerapi.HostPriorityList, 0, len(nodes)) + for _, node := range nodes { + fScore := maxPriority if maxCount > 0 { - fScore = (1.0 - float64(counts[node.Name])/float64(maxCount)) * 10 + fScore = (1.0 - counts[node.Name]/maxCount) * 10 + } + if glog.V(10) { + // We explicitly don't do glog.V(10).Infof() to avoid computing all the parameters if this is + // not logged. There is visible performance gain from it. + glog.Infof("%v -> %v: Taint Toleration Priority, Score: (%d)", pod.Name, node.Name, int(fScore)) } - glog.V(10).Infof("%v -> %v: Taint Toleration Priority, Score: (%d)", pod.Name, node.Name, int(fScore)) result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: int(fScore)}) } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go index 0e9bee1b5f40..8588471d4795 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/non_zero.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -18,9 +18,6 @@ package util import ( "k8s.io/kubernetes/pkg/api" - "k8s.io/kubernetes/pkg/api/unversioned" - "k8s.io/kubernetes/pkg/labels" - "k8s.io/kubernetes/pkg/util/sets" ) // For each of these resources, a pod that doesn't request the resource explicitly @@ -53,83 +50,3 @@ func GetNonzeroRequests(requests *api.ResourceList) (int64, int64) { } return outMilliCPU, outMemory } - -// FilterPodsByNameSpaces filters the pods based the given list of namespaces, -// empty set of namespaces means all namespaces. -func FilterPodsByNameSpaces(names sets.String, pods []*api.Pod) []*api.Pod { - if len(pods) == 0 || len(names) == 0 { - return pods - } - result := []*api.Pod{} - for _, pod := range pods { - if names.Has(pod.Namespace) { - result = append(result, pod) - } - } - return result -} - -// GetNamespacesFromPodAffinityTerm returns a set of names -// according to the namespaces indicated in podAffinityTerm. -// if the NameSpaces is nil considers the given pod's namespace -// if the Namespaces is empty list then considers all the namespaces -func GetNamespacesFromPodAffinityTerm(pod *api.Pod, podAffinityTerm api.PodAffinityTerm) sets.String { - names := sets.String{} - if podAffinityTerm.Namespaces == nil { - names.Insert(pod.Namespace) - } else if len(podAffinityTerm.Namespaces) != 0 { - names.Insert(podAffinityTerm.Namespaces...) - } - return names -} - -// NodesHaveSameTopologyKeyInternal checks if nodeA and nodeB have same label value with given topologyKey as label key. -func NodesHaveSameTopologyKeyInternal(nodeA, nodeB *api.Node, topologyKey string) bool { - return nodeA.Labels != nil && nodeB.Labels != nil && len(nodeA.Labels[topologyKey]) > 0 && nodeA.Labels[topologyKey] == nodeB.Labels[topologyKey] -} - -type Topologies struct { - DefaultKeys []string -} - -// NodesHaveSameTopologyKey checks if nodeA and nodeB have same label value with given topologyKey as label key. -// If the topologyKey is nil/empty, check if the two nodes have any of the default topologyKeys, and have same corresponding label value. -func (tps *Topologies) NodesHaveSameTopologyKey(nodeA *api.Node, nodeB *api.Node, topologyKey string) bool { - if len(topologyKey) == 0 { - // assumes this is allowed only for PreferredDuringScheduling pod anti-affinity (ensured by api/validation) - for _, defaultKey := range tps.DefaultKeys { - if NodesHaveSameTopologyKeyInternal(nodeA, nodeB, defaultKey) { - return true - } - } - return false - } else { - return NodesHaveSameTopologyKeyInternal(nodeA, nodeB, topologyKey) - } -} - -type getNodeFunc func(*api.Pod) (*api.Node, error) - -// CheckIfPodMatchPodAffinityTerm checks if podB's affinity request is compatible with podA -func (tps *Topologies) CheckIfPodMatchPodAffinityTerm(podA *api.Pod, podB *api.Pod, podBAffinityTerm api.PodAffinityTerm, getNodeA, getNodeB getNodeFunc) (bool, error) { - names := GetNamespacesFromPodAffinityTerm(podB, podBAffinityTerm) - if len(names) != 0 && !names.Has(podA.Namespace) { - return false, nil - } - - labelSelector, err := unversioned.LabelSelectorAsSelector(podBAffinityTerm.LabelSelector) - if err != nil || !labelSelector.Matches(labels.Set(podA.Labels)) { - return false, err - } - - podANode, err := getNodeA(podA) - if err != nil { - return false, err - } - podBNode, err := getNodeB(podB) - if err != nil { - return false, err - } - - return tps.NodesHaveSameTopologyKey(podANode, podBNode, podBAffinityTerm.TopologyKey), nil -} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go new file mode 100644 index 000000000000..36890cb0e9d5 --- /dev/null +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/priorities/util/topologies.go @@ -0,0 +1,78 @@ +/* +Copyright 2016 The Kubernetes 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 util + +import ( + "k8s.io/kubernetes/pkg/api" + "k8s.io/kubernetes/pkg/api/unversioned" + "k8s.io/kubernetes/pkg/labels" + "k8s.io/kubernetes/pkg/util/sets" +) + +// GetNamespacesFromPodAffinityTerm returns a set of names +// according to the namespaces indicated in podAffinityTerm. +// 1. If the namespaces is nil considers the given pod's namespace +// 2. If the namespaces is empty list then considers all the namespaces +func getNamespacesFromPodAffinityTerm(pod *api.Pod, podAffinityTerm api.PodAffinityTerm) sets.String { + names := sets.String{} + if podAffinityTerm.Namespaces == nil { + names.Insert(pod.Namespace) + } else if len(podAffinityTerm.Namespaces) != 0 { + names.Insert(podAffinityTerm.Namespaces...) + } + return names +} + +// PodMatchesTermsNamespaceAndSelector returns true if the given +// matches the namespace and selector defined by `s . +func PodMatchesTermsNamespaceAndSelector(pod *api.Pod, affinityPod *api.Pod, term *api.PodAffinityTerm) (bool, error) { + namespaces := getNamespacesFromPodAffinityTerm(affinityPod, *term) + if len(namespaces) != 0 && !namespaces.Has(pod.Namespace) { + return false, nil + } + + selector, err := unversioned.LabelSelectorAsSelector(term.LabelSelector) + if err != nil || !selector.Matches(labels.Set(pod.Labels)) { + return false, err + } + return true, nil +} + +// nodesHaveSameTopologyKeyInternal checks if nodeA and nodeB have same label value with given topologyKey as label key. +func nodesHaveSameTopologyKeyInternal(nodeA, nodeB *api.Node, topologyKey string) bool { + return nodeA.Labels != nil && nodeB.Labels != nil && len(nodeA.Labels[topologyKey]) > 0 && nodeA.Labels[topologyKey] == nodeB.Labels[topologyKey] +} + +type Topologies struct { + DefaultKeys []string +} + +// NodesHaveSameTopologyKey checks if nodeA and nodeB have same label value with given topologyKey as label key. +// If the topologyKey is nil/empty, check if the two nodes have any of the default topologyKeys, and have same corresponding label value. +func (tps *Topologies) NodesHaveSameTopologyKey(nodeA, nodeB *api.Node, topologyKey string) bool { + if len(topologyKey) == 0 { + // assumes this is allowed only for PreferredDuringScheduling pod anti-affinity (ensured by api/validation) + for _, defaultKey := range tps.DefaultKeys { + if nodesHaveSameTopologyKeyInternal(nodeA, nodeB, defaultKey) { + return true + } + } + return false + } else { + return nodesHaveSameTopologyKeyInternal(nodeA, nodeB, topologyKey) + } +} diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/scheduler_interface.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/scheduler_interface.go index b47f50e23f78..271ff5d55a8b 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/scheduler_interface.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/scheduler_interface.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -27,12 +27,12 @@ import ( type SchedulerExtender interface { // Filter based on extender-implemented predicate functions. The filtered list is // expected to be a subset of the supplied list. - Filter(pod *api.Pod, nodes *api.NodeList) (filteredNodes *api.NodeList, err error) + Filter(pod *api.Pod, nodes []*api.Node) (filteredNodes []*api.Node, err error) // Prioritize based on extender-implemented priority functions. The returned scores & weight // are used to compute the weighted score for an extender. The weighted scores are added to // the scores computed by Kubernetes scheduler. The total scores are used to do the host selection. - Prioritize(pod *api.Pod, nodes *api.NodeList) (hostPriorities *schedulerapi.HostPriorityList, weight int, err error) + Prioritize(pod *api.Pod, nodes []*api.Node) (hostPriorities *schedulerapi.HostPriorityList, weight int, err error) } // ScheduleAlgorithm is an interface implemented by things that know how to schedule pods diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/types.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/types.go index 210670b24ca2..d098bd4ff3a5 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/types.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithm/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,9 +24,9 @@ import ( // FitPredicate is a function that indicates if a pod fits into an existing node. // The failure information is given by the error. -type FitPredicate func(pod *api.Pod, nodeInfo *schedulercache.NodeInfo) (bool, error) +type FitPredicate func(pod *api.Pod, meta interface{}, nodeInfo *schedulercache.NodeInfo) (bool, error) -type PriorityFunction func(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister NodeLister) (schedulerapi.HostPriorityList, error) +type PriorityFunction func(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) type PriorityConfig struct { Function PriorityFunction diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go index 21e8e22990d6..f55f48270802 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/defaults/defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -147,15 +147,13 @@ func defaultPredicates() sets.String { factory.RegisterFitPredicate("GeneralPredicates", predicates.GeneralPredicates), // Fit is determined based on whether a pod can tolerate all of the node's taints - factory.RegisterFitPredicateFactory( - "PodToleratesNodeTaints", - func(args factory.PluginFactoryArgs) algorithm.FitPredicate { - return predicates.NewTolerationMatchPredicate(args.NodeInfo) - }, - ), + factory.RegisterFitPredicate("PodToleratesNodeTaints", predicates.PodToleratesNodeTaints), // Fit is determined by node memory pressure condition. factory.RegisterFitPredicate("CheckNodeMemoryPressure", predicates.CheckNodeMemoryPressurePredicate), + + // Fit is determined by node disk pressure condition. + factory.RegisterFitPredicate("CheckNodeDiskPressure", predicates.CheckNodeDiskPressurePredicate), ) } @@ -176,22 +174,17 @@ func defaultPriorities() sets.String { }, ), factory.RegisterPriorityConfigFactory( - "NodeAffinityPriority", + "NodePreferAvoidPodsPriority", factory.PriorityConfigFactory{ Function: func(args factory.PluginFactoryArgs) algorithm.PriorityFunction { - return priorities.NewNodeAffinityPriority(args.NodeLister) + return priorities.NewNodePreferAvoidPodsPriority(args.ControllerLister, args.ReplicaSetLister) }, - Weight: 1, - }, - ), - factory.RegisterPriorityConfigFactory( - "TaintTolerationPriority", - factory.PriorityConfigFactory{ - Function: func(args factory.PluginFactoryArgs) algorithm.PriorityFunction { - return priorities.NewTaintTolerationPriority(args.NodeLister) - }, - Weight: 1, + // Set this weight large enough to override all other priority functions. + // TODO: Figure out a better way to do this, maybe at same time as fixing #24720. + Weight: 10000, }, ), + factory.RegisterPriorityFunction("NodeAffinityPriority", priorities.CalculateNodeAffinityPriority, 1), + factory.RegisterPriorityFunction("TaintTolerationPriority", priorities.ComputeTaintTolerationPriority, 1), ) } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/plugins.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/plugins.go index f4075928ae97..f85cf0555366 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/plugins.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/latest/latest.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/latest/latest.go index e28ae26b9fc2..dbea2a8af567 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/latest/latest.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/latest/latest.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/register.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/register.go index 3b988f25bfae..2cb08fba7edb 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/register.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/types.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/types.go index 89bbe6373805..29d98a3b281e 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/types.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/register.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/register.go index 8e6d754376cf..2c4507270ca5 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/register.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/types.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/types.go index 89618a56e861..7eef7b5a8642 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/types.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/v1/types.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/validation/validation.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/validation/validation.go index 0ca60c6128e4..d7d2b28851a9 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/validation/validation.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/api/validation/validation.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/extender.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/extender.go index 30b403f36eb1..713e7d13c453 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/extender.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/extender.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -93,16 +93,20 @@ func NewHTTPExtender(config *schedulerapi.ExtenderConfig, apiVersion string) (al // Filter based on extender implemented predicate functions. The filtered list is // expected to be a subset of the supplied list. -func (h *HTTPExtender) Filter(pod *api.Pod, nodes *api.NodeList) (*api.NodeList, error) { +func (h *HTTPExtender) Filter(pod *api.Pod, nodes []*api.Node) ([]*api.Node, error) { var result schedulerapi.ExtenderFilterResult if h.filterVerb == "" { return nodes, nil } + nodeItems := make([]api.Node, 0, len(nodes)) + for _, node := range nodes { + nodeItems = append(nodeItems, *node) + } args := schedulerapi.ExtenderArgs{ Pod: *pod, - Nodes: *nodes, + Nodes: api.NodeList{Items: nodeItems}, } if err := h.send(h.filterVerb, &args, &result); err != nil { @@ -111,26 +115,34 @@ func (h *HTTPExtender) Filter(pod *api.Pod, nodes *api.NodeList) (*api.NodeList, if result.Error != "" { return nil, fmt.Errorf(result.Error) } - return &result.Nodes, nil + nodeResult := make([]*api.Node, 0, len(result.Nodes.Items)) + for i := range result.Nodes.Items { + nodeResult = append(nodeResult, &result.Nodes.Items[i]) + } + return nodeResult, nil } // Prioritize based on extender implemented priority functions. Weight*priority is added // up for each such priority function. The returned score is added to the score computed // by Kubernetes scheduler. The total score is used to do the host selection. -func (h *HTTPExtender) Prioritize(pod *api.Pod, nodes *api.NodeList) (*schedulerapi.HostPriorityList, int, error) { +func (h *HTTPExtender) Prioritize(pod *api.Pod, nodes []*api.Node) (*schedulerapi.HostPriorityList, int, error) { var result schedulerapi.HostPriorityList if h.prioritizeVerb == "" { result := schedulerapi.HostPriorityList{} - for _, node := range nodes.Items { + for _, node := range nodes { result = append(result, schedulerapi.HostPriority{Host: node.Name, Score: 0}) } return &result, 0, nil } + nodeItems := make([]api.Node, 0, len(nodes)) + for _, node := range nodes { + nodeItems = append(nodeItems, *node) + } args := schedulerapi.ExtenderArgs{ Pod: *pod, - Nodes: *nodes, + Nodes: api.NodeList{Items: nodeItems}, } if err := h.send(h.prioritizeVerb, &args, &result); err != nil { diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/factory.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/factory.go index 0bbbcbf3329f..d5264223a53d 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/factory.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/factory.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -48,6 +48,8 @@ import ( const ( SchedulerAnnotationKey = "scheduler.alpha.kubernetes.io/name" + initialGetBackoff = 100 * time.Millisecond + maximalGetBackoff = time.Minute ) // ConfigFactory knows how to fill out a scheduler config with its support functions. @@ -432,8 +434,9 @@ func (f *ConfigFactory) responsibleForPod(pod *api.Pod) bool { } func getNodeConditionPredicate() cache.NodeConditionPredicate { - return func(node api.Node) bool { - for _, cond := range node.Status.Conditions { + return func(node *api.Node) bool { + for i := range node.Status.Conditions { + cond := &node.Status.Conditions[i] // We consider the node for scheduling only when its: // - NodeReady condition status is ConditionTrue, // - NodeOutOfDisk condition status is ConditionFalse, @@ -530,12 +533,20 @@ func (factory *ConfigFactory) makeDefaultErrorFunc(backoff *podBackoff, podQueue } // Get the pod again; it may have changed/been scheduled already. pod = &api.Pod{} - err := factory.Client.Get().Namespace(podID.Namespace).Resource("pods").Name(podID.Name).Do().Into(pod) - if err != nil { - if !errors.IsNotFound(err) { - glog.Errorf("Error getting pod %v for retry: %v; abandoning", podID, err) + getBackoff := initialGetBackoff + for { + if err := factory.Client.Get().Namespace(podID.Namespace).Resource("pods").Name(podID.Name).Do().Into(pod); err == nil { + break } - return + if errors.IsNotFound(err) { + glog.Warningf("A pod %v no longer exists", podID) + return + } + glog.Errorf("Error getting pod %v for retry: %v; retrying...", podID, err) + if getBackoff = getBackoff * 2; getBackoff > maximalGetBackoff { + getBackoff = maximalGetBackoff + } + time.Sleep(getBackoff) } if pod.Spec.NodeName == "" { podQueue.AddIfNotPresent(pod) diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/plugins.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/plugins.go index 9744a49dff10..e6bcdefb9a3c 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/plugins.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/factory/plugins.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -311,7 +311,7 @@ func validatePriorityOrDie(priority schedulerapi.PriorityPolicy) { } } -// ListAlgorithmProviders is called when listing all available algortihm providers in `kube-scheduler --help` +// ListAlgorithmProviders is called when listing all available algorithm providers in `kube-scheduler --help` func ListAlgorithmProviders() string { var availableAlgorithmProviders []string for name := range algorithmProviderMap { diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/generic_scheduler.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/generic_scheduler.go index 86ebbd0b3d0d..48d05c7d9377 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/generic_scheduler.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/generic_scheduler.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import ( "fmt" "sort" "sync" + "sync/atomic" "time" "github.com/golang/glog" @@ -62,6 +63,8 @@ type genericScheduler struct { pods algorithm.PodLister lastNodeIndexLock sync.Mutex lastNodeIndex uint64 + + cachedNodeInfoMap map[string]*schedulercache.NodeInfo } // Schedule tries to schedule the given pod to one of node in the node list. @@ -80,23 +83,23 @@ func (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeListe if err != nil { return "", err } - if len(nodes.Items) == 0 { + if len(nodes) == 0 { return "", ErrNoNodesAvailable } // Used for all fit and priority funcs. - nodeNameToInfo, err := g.cache.GetNodeNameToInfoMap() + err = g.cache.UpdateNodeNameToInfoMap(g.cachedNodeInfoMap) if err != nil { return "", err } trace.Step("Computing predicates") - filteredNodes, failedPredicateMap, err := findNodesThatFit(pod, nodeNameToInfo, g.predicates, nodes, g.extenders) + filteredNodes, failedPredicateMap, err := findNodesThatFit(pod, g.cachedNodeInfoMap, nodes, g.predicates, g.extenders) if err != nil { return "", err } - if len(filteredNodes.Items) == 0 { + if len(filteredNodes) == 0 { return "", &FitError{ Pod: pod, FailedPredicates: failedPredicateMap, @@ -104,7 +107,7 @@ func (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeListe } trace.Step("Prioritizing") - priorityList, err := PrioritizeNodes(pod, nodeNameToInfo, g.prioritizers, algorithm.FakeNodeLister(filteredNodes), g.extenders) + priorityList, err := PrioritizeNodes(pod, g.cachedNodeInfoMap, g.prioritizers, filteredNodes, g.extenders) if err != nil { return "", err } @@ -134,52 +137,69 @@ func (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList // Filters the nodes to find the ones that fit based on the given predicate functions // Each node is passed through the predicate functions to determine if it is a fit -func findNodesThatFit(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate, nodes api.NodeList, extenders []algorithm.SchedulerExtender) (api.NodeList, FailedPredicateMap, error) { - predicateResultLock := sync.Mutex{} - filtered := []api.Node{} +func findNodesThatFit( + pod *api.Pod, + nodeNameToInfo map[string]*schedulercache.NodeInfo, + nodes []*api.Node, + predicateFuncs map[string]algorithm.FitPredicate, + extenders []algorithm.SchedulerExtender) ([]*api.Node, FailedPredicateMap, error) { + var filtered []*api.Node failedPredicateMap := FailedPredicateMap{} - errs := []error{} - checkNode := func(i int) { - nodeName := nodes.Items[i].Name - fits, failedPredicate, err := podFitsOnNode(pod, nodeNameToInfo[nodeName], predicateFuncs) - - predicateResultLock.Lock() - defer predicateResultLock.Unlock() - if err != nil { - errs = append(errs, err) - return + if len(predicateFuncs) == 0 { + filtered = nodes + } else { + // Create filtered list with enough space to avoid growing it + // and allow assigning. + filtered = make([]*api.Node, len(nodes)) + meta := predicates.PredicateMetadata(pod) + errs := []error{} + + var predicateResultLock sync.Mutex + var filteredLen int32 + checkNode := func(i int) { + nodeName := nodes[i].Name + fits, failedPredicate, err := podFitsOnNode(pod, meta, nodeNameToInfo[nodeName], predicateFuncs) + if err != nil { + predicateResultLock.Lock() + errs = append(errs, err) + predicateResultLock.Unlock() + return + } + if fits { + filtered[atomic.AddInt32(&filteredLen, 1)-1] = nodes[i] + } else { + predicateResultLock.Lock() + failedPredicateMap[nodeName] = failedPredicate + predicateResultLock.Unlock() + } } - if fits { - filtered = append(filtered, nodes.Items[i]) - } else { - failedPredicateMap[nodeName] = failedPredicate + workqueue.Parallelize(16, len(nodes), checkNode) + filtered = filtered[:filteredLen] + if len(errs) > 0 { + return []*api.Node{}, FailedPredicateMap{}, errors.NewAggregate(errs) } } - workqueue.Parallelize(16, len(nodes.Items), checkNode) - if len(errs) > 0 { - return api.NodeList{}, FailedPredicateMap{}, errors.NewAggregate(errs) - } if len(filtered) > 0 && len(extenders) != 0 { for _, extender := range extenders { - filteredList, err := extender.Filter(pod, &api.NodeList{Items: filtered}) + filteredList, err := extender.Filter(pod, filtered) if err != nil { - return api.NodeList{}, FailedPredicateMap{}, err + return []*api.Node{}, FailedPredicateMap{}, err } - filtered = filteredList.Items + filtered = filteredList if len(filtered) == 0 { break } } } - return api.NodeList{Items: filtered}, failedPredicateMap, nil + return filtered, failedPredicateMap, nil } // Checks whether node with a given name and NodeInfo satisfies all predicateFuncs. -func podFitsOnNode(pod *api.Pod, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, string, error) { +func podFitsOnNode(pod *api.Pod, meta interface{}, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, string, error) { for _, predicate := range predicateFuncs { - fit, err := predicate(pod, info) + fit, err := predicate(pod, meta, info) if err != nil { switch e := err.(type) { case *predicates.InsufficientResourceError: @@ -221,21 +241,21 @@ func PrioritizeNodes( pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, priorityConfigs []algorithm.PriorityConfig, - nodeLister algorithm.NodeLister, + nodes []*api.Node, extenders []algorithm.SchedulerExtender, ) (schedulerapi.HostPriorityList, error) { - result := schedulerapi.HostPriorityList{} + result := make(schedulerapi.HostPriorityList, 0, len(nodeNameToInfo)) // If no priority configs are provided, then the EqualPriority function is applied // This is required to generate the priority list in the required format if len(priorityConfigs) == 0 && len(extenders) == 0 { - return EqualPriority(pod, nodeNameToInfo, nodeLister) + return EqualPriority(pod, nodeNameToInfo, nodes) } var ( mu = sync.Mutex{} wg = sync.WaitGroup{} - combinedScores = map[string]int{} + combinedScores = make(map[string]int, len(nodeNameToInfo)) errs []error ) @@ -250,7 +270,7 @@ func PrioritizeNodes( defer wg.Done() weight := config.Weight priorityFunc := config.Function - prioritizedList, err := priorityFunc(pod, nodeNameToInfo, nodeLister) + prioritizedList, err := priorityFunc(pod, nodeNameToInfo, nodes) mu.Lock() defer mu.Unlock() @@ -271,16 +291,12 @@ func PrioritizeNodes( // wait for all go routines to finish wg.Wait() - if len(extenders) != 0 && nodeLister != nil { - nodes, err := nodeLister.List() - if err != nil { - return schedulerapi.HostPriorityList{}, err - } + if len(extenders) != 0 && nodes != nil { for _, extender := range extenders { wg.Add(1) go func(ext algorithm.SchedulerExtender) { defer wg.Done() - prioritizedList, weight, err := ext.Prioritize(pod, &nodes) + prioritizedList, weight, err := ext.Prioritize(pod, nodes) if err != nil { // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities return @@ -305,15 +321,9 @@ func PrioritizeNodes( } // EqualPriority is a prioritizer function that gives an equal weight of one to all nodes -func EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) { - nodes, err := nodeLister.List() - if err != nil { - glog.Errorf("Failed to list nodes: %v", err) - return []schedulerapi.HostPriority{}, err - } - - result := []schedulerapi.HostPriority{} - for _, node := range nodes.Items { +func EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodes []*api.Node) (schedulerapi.HostPriorityList, error) { + result := make(schedulerapi.HostPriorityList, len(nodes)) + for _, node := range nodes { result = append(result, schedulerapi.HostPriority{ Host: node.Name, Score: 1, @@ -324,9 +334,10 @@ func EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInf func NewGenericScheduler(cache schedulercache.Cache, predicates map[string]algorithm.FitPredicate, prioritizers []algorithm.PriorityConfig, extenders []algorithm.SchedulerExtender) algorithm.ScheduleAlgorithm { return &genericScheduler{ - cache: cache, - predicates: predicates, - prioritizers: prioritizers, - extenders: extenders, + cache: cache, + predicates: predicates, + prioritizers: prioritizers, + extenders: extenders, + cachedNodeInfoMap: make(map[string]*schedulercache.NodeInfo), } } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/metrics/metrics.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/metrics/metrics.go index 8491be52d722..cd50ceddc9a7 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/metrics/metrics.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/metrics/metrics.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/scheduler.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/scheduler.go index 067cd41a0ba8..eab0c922bb27 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/scheduler.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/scheduler.go @@ -1,5 +1,5 @@ /* -Copyright 2014 The Kubernetes Authors All rights reserved. +Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -140,6 +140,9 @@ func (s *Scheduler) scheduleOne() { err := s.config.Binder.Bind(b) if err != nil { glog.V(1).Infof("Failed to bind pod: %v/%v", pod.Namespace, pod.Name) + if err := s.config.SchedulerCache.ForgetPod(&assumed); err != nil { + glog.Errorf("scheduler cache ForgetPod failed: %v", err) + } s.config.Error(pod, err) s.config.Recorder.Eventf(pod, api.EventTypeNormal, "FailedScheduling", "Binding rejected: %v", err) s.config.PodConditionUpdater.Update(pod, &api.PodCondition{ diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/cache.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/cache.go index a55b0e9feaee..556aea308268 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/cache.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/cache.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -74,14 +74,20 @@ func newSchedulerCache(ttl, period time.Duration, stop <-chan struct{}) *schedul } } -func (cache *schedulerCache) GetNodeNameToInfoMap() (map[string]*NodeInfo, error) { - nodeNameToInfo := make(map[string]*NodeInfo) +func (cache *schedulerCache) UpdateNodeNameToInfoMap(nodeNameToInfo map[string]*NodeInfo) error { cache.mu.Lock() defer cache.mu.Unlock() for name, info := range cache.nodes { - nodeNameToInfo[name] = info.Clone() + if current, ok := nodeNameToInfo[name]; !ok || current.generation != info.generation { + nodeNameToInfo[name] = info.Clone() + } + } + for name := range nodeNameToInfo { + if _, ok := cache.nodes[name]; !ok { + delete(nodeNameToInfo, name) + } } - return nodeNameToInfo, nil + return nil } func (cache *schedulerCache) List(selector labels.Selector) ([]*api.Pod, error) { @@ -126,6 +132,31 @@ func (cache *schedulerCache) assumePod(pod *api.Pod, now time.Time) error { return nil } +func (cache *schedulerCache) ForgetPod(pod *api.Pod) error { + key, err := getPodKey(pod) + if err != nil { + return err + } + + cache.mu.Lock() + defer cache.mu.Unlock() + + _, ok := cache.podStates[key] + switch { + // Only assumed pod can be forgotten. + case ok && cache.assumedPods[key]: + err := cache.removePod(pod) + if err != nil { + return err + } + delete(cache.assumedPods, key) + delete(cache.podStates, key) + default: + return fmt.Errorf("pod state wasn't assumed but get forgotten. Pod key: %v", key) + } + return nil +} + func (cache *schedulerCache) AddPod(pod *api.Pod) error { key, err := getPodKey(pod) if err != nil { diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/interface.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/interface.go index 07330a2a8971..2f0a84b2a2e2 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/interface.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/interface.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -36,13 +36,13 @@ import ( // | | | | Update // + Assume Add v v | //Initial +--------> Assumed +------------+---> Added <--+ -// + | + -// | | | -// | Add | | Remove -// | | | -// | + | -// +-------------> Expired +----> Deleted -// Expire +// ^ + + | + +// | | | | | +// | | | Add | | Remove +// | | | | | +// | | | + | +// +----------------+ +-----------> Expired +----> Deleted +// Forget Expire // // // Note that an assumed pod can expire, because if we haven't received Add event notifying us @@ -61,6 +61,9 @@ type Cache interface { // After expiration, its information would be subtracted. AssumePod(pod *api.Pod) error + // ForgetPod removes an assumed pod from cache. + ForgetPod(pod *api.Pod) error + // AddPod either confirms a pod if it's assumed, or adds it back if it's expired. // If added back, the pod's information would be added again. AddPod(pod *api.Pod) error @@ -80,9 +83,10 @@ type Cache interface { // RemoveNode removes overall information about node. RemoveNode(node *api.Node) error - // GetNodeNameToInfoMap returns a map of node names to node info. The node info contains - // aggregated information of pods scheduled (including assumed to be) on this node. - GetNodeNameToInfoMap() (map[string]*NodeInfo, error) + // UpdateNodeNameToInfoMap updates the passed infoMap to the current contents of Cache. + // The node info contains aggregated information of pods scheduled (including assumed to be) + // on this node. + UpdateNodeNameToInfoMap(infoMap map[string]*NodeInfo) error // List lists all cached pods (including assumed ones). List(labels.Selector) ([]*api.Pod, error) diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/node_info.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/node_info.go index 79890cd3d212..4f0bf9de070c 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/node_info.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/node_info.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -33,12 +33,24 @@ type NodeInfo struct { // Overall node information. node *api.Node + pods []*api.Pod + podsWithAffinity []*api.Pod + // Total requested resource of all pods on this node. // It includes assumed pods which scheduler sends binding to apiserver but // didn't get it as scheduled yet. requestedResource *Resource - pods []*api.Pod nonzeroRequest *Resource + // We store allocatedResources (which is Node.Status.Allocatable.*) explicitly + // as int64, to avoid conversions and accessing map. + allocatableResource *Resource + // We store allowedPodNumber (which is Node.Status.Allocatable.Pods().Value()) + // explicitly as int, to avoid conversions and improve performance. + allowedPodNumber int + + // Whenever NodeInfo changes, generation is bumped. + // This is used to avoid cloning it if the object didn't change. + generation int64 } // Resource is a collection of compute resource. @@ -53,8 +65,11 @@ type Resource struct { // the returned object. func NewNodeInfo(pods ...*api.Pod) *NodeInfo { ni := &NodeInfo{ - requestedResource: &Resource{}, - nonzeroRequest: &Resource{}, + requestedResource: &Resource{}, + nonzeroRequest: &Resource{}, + allocatableResource: &Resource{}, + allowedPodNumber: 0, + generation: 0, } for _, pod := range pods { ni.addPod(pod) @@ -78,6 +93,21 @@ func (n *NodeInfo) Pods() []*api.Pod { return n.pods } +// PodsWithAffinity return all pods with (anti)affinity constraints on this node. +func (n *NodeInfo) PodsWithAffinity() []*api.Pod { + if n == nil { + return nil + } + return n.podsWithAffinity +} + +func (n *NodeInfo) AllowedPodNumber() int { + if n == nil { + return 0 + } + return n.allowedPodNumber +} + // RequestedResource returns aggregated resource request of pods on this node. func (n *NodeInfo) RequestedResource() Resource { if n == nil { @@ -94,13 +124,30 @@ func (n *NodeInfo) NonZeroRequest() Resource { return *n.nonzeroRequest } +// AllocatableResource returns allocatable resources on a given node. +func (n *NodeInfo) AllocatableResource() Resource { + if n == nil { + return emptyResource + } + return *n.allocatableResource +} + func (n *NodeInfo) Clone() *NodeInfo { pods := append([]*api.Pod(nil), n.pods...) clone := &NodeInfo{ - node: n.node, - requestedResource: &(*n.requestedResource), - nonzeroRequest: &(*n.nonzeroRequest), - pods: pods, + node: n.node, + pods: pods, + requestedResource: &(*n.requestedResource), + nonzeroRequest: &(*n.nonzeroRequest), + allocatableResource: &(*n.allocatableResource), + allowedPodNumber: n.allowedPodNumber, + generation: n.generation, + } + if len(n.pods) > 0 { + clone.pods = append([]*api.Pod(nil), n.pods...) + } + if len(n.podsWithAffinity) > 0 { + clone.podsWithAffinity = append([]*api.Pod(nil), n.podsWithAffinity...) } return clone } @@ -114,6 +161,14 @@ func (n *NodeInfo) String() string { return fmt.Sprintf("&NodeInfo{Pods:%v, RequestedResource:%#v, NonZeroRequest: %#v}", podKeys, n.requestedResource, n.nonzeroRequest) } +func hasPodAffinityConstraints(pod *api.Pod) bool { + affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations) + if err != nil || affinity == nil { + return false + } + return affinity.PodAffinity != nil || affinity.PodAntiAffinity != nil +} + // addPod adds pod information to this NodeInfo. func (n *NodeInfo) addPod(pod *api.Pod) { cpu, mem, nvidia_gpu, non0_cpu, non0_mem := calculateResource(pod) @@ -123,6 +178,10 @@ func (n *NodeInfo) addPod(pod *api.Pod) { n.nonzeroRequest.MilliCPU += non0_cpu n.nonzeroRequest.Memory += non0_mem n.pods = append(n.pods, pod) + if hasPodAffinityConstraints(pod) { + n.podsWithAffinity = append(n.podsWithAffinity, pod) + } + n.generation++ } // removePod subtracts pod information to this NodeInfo. @@ -132,6 +191,19 @@ func (n *NodeInfo) removePod(pod *api.Pod) error { return err } + for i := range n.podsWithAffinity { + k2, err := getPodKey(n.podsWithAffinity[i]) + if err != nil { + glog.Errorf("Cannot get pod key, err: %v", err) + continue + } + if k1 == k2 { + // delete the element + n.podsWithAffinity[i] = n.podsWithAffinity[len(n.podsWithAffinity)-1] + n.podsWithAffinity = n.podsWithAffinity[:len(n.podsWithAffinity)-1] + break + } + } for i := range n.pods { k2, err := getPodKey(n.pods[i]) if err != nil { @@ -149,6 +221,7 @@ func (n *NodeInfo) removePod(pod *api.Pod) error { n.requestedResource.NvidiaGPU -= nvidia_gpu n.nonzeroRequest.MilliCPU -= non0_cpu n.nonzeroRequest.Memory -= non0_mem + n.generation++ return nil } } @@ -173,6 +246,11 @@ func calculateResource(pod *api.Pod) (cpu int64, mem int64, nvidia_gpu int64, no // Sets the overall node information. func (n *NodeInfo) SetNode(node *api.Node) error { n.node = node + n.allocatableResource.MilliCPU = node.Status.Allocatable.Cpu().MilliValue() + n.allocatableResource.Memory = node.Status.Allocatable.Memory().Value() + n.allocatableResource.NvidiaGPU = node.Status.Allocatable.NvidiaGPU().Value() + n.allowedPodNumber = int(node.Status.Allocatable.Pods().Value()) + n.generation++ return nil } @@ -183,6 +261,9 @@ func (n *NodeInfo) RemoveNode(node *api.Node) error { // and thus can potentially be observed later, even though they happened before // node removal. This is handled correctly in cache.go file. n.node = nil + n.allocatableResource = &Resource{} + n.allowedPodNumber = 0 + n.generation++ return nil } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/util.go b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/util.go index 7d840b59cd10..12e6848bc57e 100644 --- a/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/util.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache/util.go @@ -1,5 +1,5 @@ /* -Copyright 2015 The Kubernetes Authors All rights reserved. +Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,16 +20,20 @@ import "k8s.io/kubernetes/pkg/api" // CreateNodeNameToInfoMap obtains a list of pods and pivots that list into a map where the keys are node names // and the values are the aggregated information for that node. -func CreateNodeNameToInfoMap(pods []*api.Pod) map[string]*NodeInfo { +func CreateNodeNameToInfoMap(pods []*api.Pod, nodes []*api.Node) map[string]*NodeInfo { nodeNameToInfo := make(map[string]*NodeInfo) for _, pod := range pods { nodeName := pod.Spec.NodeName - nodeInfo, ok := nodeNameToInfo[nodeName] - if !ok { - nodeInfo = NewNodeInfo() - nodeNameToInfo[nodeName] = nodeInfo + if _, ok := nodeNameToInfo[nodeName]; !ok { + nodeNameToInfo[nodeName] = NewNodeInfo() } - nodeInfo.addPod(pod) + nodeNameToInfo[nodeName].addPod(pod) + } + for _, node := range nodes { + if _, ok := nodeNameToInfo[node.Name]; !ok { + nodeNameToInfo[node.Name] = NewNodeInfo() + } + nodeNameToInfo[node.Name].SetNode(node) } return nodeNameToInfo } diff --git a/vendor/k8s.io/kubernetes/plugin/pkg/webhook/webhook.go b/vendor/k8s.io/kubernetes/plugin/pkg/webhook/webhook.go old mode 100644 new mode 100755 index a907444b95c3..593457b1fb9e --- a/vendor/k8s.io/kubernetes/plugin/pkg/webhook/webhook.go +++ b/vendor/k8s.io/kubernetes/plugin/pkg/webhook/webhook.go @@ -1,5 +1,5 @@ /* -Copyright 2016 The Kubernetes Authors All rights reserved. +Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ type GenericWebhook struct { initialBackoff time.Duration } -// New creates a new GenericWebhook from the provided kubeconfig file. +// NewGenericWebhook creates a new GenericWebhook from the provided kubeconfig file. func NewGenericWebhook(kubeConfigFile string, groupVersions []unversioned.GroupVersion, initialBackoff time.Duration) (*GenericWebhook, error) { for _, groupVersion := range groupVersions { if !registered.IsEnabledVersion(groupVersion) { diff --git a/vendor/k8s.io/kubernetes/third_party/golang/expansion/expand.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand.go similarity index 100% rename from vendor/k8s.io/kubernetes/third_party/golang/expansion/expand.go rename to vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand.go diff --git a/vendor/k8s.io/kubernetes/third_party/forked/json/fields.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/json/fields.go similarity index 100% rename from vendor/k8s.io/kubernetes/third_party/forked/json/fields.go rename to vendor/k8s.io/kubernetes/third_party/forked/golang/json/fields.go diff --git a/vendor/k8s.io/kubernetes/third_party/golang/netutil/addr.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/netutil/addr.go similarity index 100% rename from vendor/k8s.io/kubernetes/third_party/golang/netutil/addr.go rename to vendor/k8s.io/kubernetes/third_party/forked/golang/netutil/addr.go diff --git a/vendor/k8s.io/kubernetes/third_party/forked/reflect/deep_equal.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/reflect/deep_equal.go similarity index 100% rename from vendor/k8s.io/kubernetes/third_party/forked/reflect/deep_equal.go rename to vendor/k8s.io/kubernetes/third_party/forked/golang/reflect/deep_equal.go diff --git a/vendor/k8s.io/kubernetes/third_party/forked/golang/reflect/type.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/reflect/type.go new file mode 100644 index 000000000000..67957ee33e9c --- /dev/null +++ b/vendor/k8s.io/kubernetes/third_party/forked/golang/reflect/type.go @@ -0,0 +1,91 @@ +//This package is copied from Go library reflect/type.go. +//The struct tag library provides no way to extract the list of struct tags, only +//a specific tag +package reflect + +import ( + "fmt" + + "strconv" + "strings" +) + +type StructTag struct { + Name string + Value string +} + +func (t StructTag) String() string { + return fmt.Sprintf("%s:%q", t.Name, t.Value) +} + +type StructTags []StructTag + +func (tags StructTags) String() string { + s := make([]string, 0, len(tags)) + for _, tag := range tags { + s = append(s, tag.String()) + } + return "`" + strings.Join(s, " ") + "`" +} + +func (tags StructTags) Has(name string) bool { + for i := range tags { + if tags[i].Name == name { + return true + } + } + return false +} + +// ParseStructTags returns the full set of fields in a struct tag in the order they appear in +// the struct tag. +func ParseStructTags(tag string) (StructTags, error) { + tags := StructTags{} + for tag != "" { + // Skip leading space. + i := 0 + for i < len(tag) && tag[i] == ' ' { + i++ + } + tag = tag[i:] + if tag == "" { + break + } + + // Scan to colon. A space, a quote or a control character is a syntax error. + // Strictly speaking, control chars include the range [0x7f, 0x9f], not just + // [0x00, 0x1f], but in practice, we ignore the multi-byte control characters + // as it is simpler to inspect the tag's bytes than the tag's runes. + i = 0 + for i < len(tag) && tag[i] > ' ' && tag[i] != ':' && tag[i] != '"' && tag[i] != 0x7f { + i++ + } + if i == 0 || i+1 >= len(tag) || tag[i] != ':' || tag[i+1] != '"' { + break + } + name := string(tag[:i]) + tag = tag[i+1:] + + // Scan quoted string to find value. + i = 1 + for i < len(tag) && tag[i] != '"' { + if tag[i] == '\\' { + i++ + } + i++ + } + if i >= len(tag) { + break + } + qvalue := string(tag[:i+1]) + tag = tag[i+1:] + + value, err := strconv.Unquote(qvalue) + if err != nil { + return nil, err + } + tags = append(tags, StructTag{Name: name, Value: value}) + } + return tags, nil +} diff --git a/vendor/k8s.io/kubernetes/third_party/forked/json/LICENSE b/vendor/k8s.io/kubernetes/third_party/forked/json/LICENSE deleted file mode 100644 index 74487567632c..000000000000 --- a/vendor/k8s.io/kubernetes/third_party/forked/json/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/k8s.io/kubernetes/third_party/forked/reflect/LICENSE b/vendor/k8s.io/kubernetes/third_party/forked/reflect/LICENSE deleted file mode 100644 index 74487567632c..000000000000 --- a/vendor/k8s.io/kubernetes/third_party/forked/reflect/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.